@cowprotocol/widget-react 0.14.3 → 0.14.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/index.mjs +35 -35
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),T=require("react");class F{constructor(t){this.key=t}postMessageToWindow(t,n,r){const p=typeof r=="object"?r:{},h={key:this.key,method:n,...p};t.postMessage(h,"*")}listenToMessageFromWindow(t,n,r){const p=h=>{!G(h.data)||h.data.key!==this.key||h.data.method!==n||r(h.data)};return t.addEventListener("message",p),p}stopListeningToMessageFromWindow(t,n,r){t.removeEventListener("message",r)}stopListeningWindowListener(t,n){t.removeEventListener("message",n)}}function G(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var g=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e.SEND_PROVIDER_META_INFO="SEND_PROVIDER_META_INFO",e.REQUEST_PROVIDER_META_INFO="REQUEST_PROVIDER_META_INFO",e))(g||{});const P=new F("cowSwapIframeRpcProviderTransport");function q(e){if(e.isWalletConnect)return e?.session?.peer?.metadata}function $(e,t){return t.find(n=>n.provider===e)?.info}const B=["connect","disconnect","close","chainChanged","accountsChanged"],U=[];window.addEventListener("eip6963:announceProvider",e=>{const t=e;U.push(t.detail)});class J{constructor(t){this.iframeWidow=t}ethereumProvider=null;requestWaitingForConnection={};disconnect(){this.ethereumProvider=null,P.stopListeningToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),P.stopListeningToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest)}onConnect(t){this.ethereumProvider?this.disconnect():P.listenToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),B.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))}),P.listenToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest)}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:p}=t;if(!this.ethereumProvider||!n)return;(p==="enable"?this.ethereumProvider.request({method:"eth_requestAccounts",id:n}):this.ethereumProvider.request({...t,id:n})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:w}}))}processRpcCallFromWindow=({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)};processProviderMetaInfoRequest=()=>{if(!this.ethereumProvider)return;const t=$(this.ethereumProvider,U),n=q(this.ethereumProvider);P.postMessageToWindow(this.iframeWidow,g.SEND_PROVIDER_META_INFO,{providerEip6963Info:t,providerWcMetadata:n})};onProviderEvent(t,n){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_RPC_RESPONSE,t)}}var D={exports:{}},b;function z(){return b||(b=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function h(c,i,s,o,f){if(typeof s!="function")throw new TypeError("The listener must be a function");var d=new p(s,o||c,f),l=n?n+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],d]:c._events[l].push(d):(c._events[l]=d,c._eventsCount++),c}function w(c,i){--c._eventsCount===0?c._events=new r:delete c._events[i]}function u(){this._events=new r,this._eventsCount=0}u.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)t.call(s,o)&&i.push(n?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},u.prototype.listeners=function(i){var s=n?n+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var f=0,d=o.length,l=new Array(d);f<d;f++)l[f]=o[f].fn;return l},u.prototype.listenerCount=function(i){var s=n?n+i:i,o=this._events[s];return o?o.fn?1:o.length:0},u.prototype.emit=function(i,s,o,f,d,l){var _=n?n+i:i;if(!this._events[_])return!1;var a=this._events[_],R=arguments.length,m,E;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),R){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,s),!0;case 3:return a.fn.call(a.context,s,o),!0;case 4:return a.fn.call(a.context,s,o,f),!0;case 5:return a.fn.call(a.context,s,o,f,d),!0;case 6:return a.fn.call(a.context,s,o,f,d,l),!0}for(E=1,m=new Array(R-1);E<R;E++)m[E-1]=arguments[E];a.fn.apply(a.context,m)}else{var Q=a.length,O;for(E=0;E<Q;E++)switch(a[E].once&&this.removeListener(i,a[E].fn,void 0,!0),R){case 1:a[E].fn.call(a[E].context);break;case 2:a[E].fn.call(a[E].context,s);break;case 3:a[E].fn.call(a[E].context,s,o);break;case 4:a[E].fn.call(a[E].context,s,o,f);break;default:if(!m)for(O=1,m=new Array(R-1);O<R;O++)m[O-1]=arguments[O];a[E].fn.apply(a[E].context,m)}}return!0},u.prototype.on=function(i,s,o){return h(this,i,s,o,!1)},u.prototype.once=function(i,s,o){return h(this,i,s,o,!0)},u.prototype.removeListener=function(i,s,o,f){var d=n?n+i:i;if(!this._events[d])return this;if(!s)return w(this,d),this;var l=this._events[d];if(l.fn)l.fn===s&&(!f||l.once)&&(!o||l.context===o)&&w(this,d);else{for(var _=0,a=[],R=l.length;_<R;_++)(l[_].fn!==s||f&&!l[_].once||o&&l[_].context!==o)&&a.push(l[_]);a.length?this._events[d]=a.length===1?a[0]:a:w(this,d)}return this},u.prototype.removeAllListeners=function(i){var s;return i?(s=n?n+i:i,this._events[s]&&w(this,s)):(this._events=new r,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=n,u.EventEmitter=u,e.exports=u}(D)),D.exports}z();class Y{subscriptions={};on(t){const{event:n,handler:r}=t;return this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(r),t}off(t){const{event:n,handler:r}=t;return this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(p=>p!==r)),t}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}var I=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(I||{}),S=(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))(S||{}),W=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(W||{});const K=["primary","background","paper","text","danger","warning","alert","info","success"],v=new F("cowSwapWidget");class X{constructor(t,n=[]){this.contentWindow=t,this.updateListeners(n),this.widgetListener=v.listenToMessageFromWindow(this.contentWindow,I.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}eventEmitter=new Y;listeners=[];widgetListener;stopListeningIframe(){v.stopListeningWindowListener(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 Z{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=r=>{ee(r.data)&&r.origin!==window.location.origin&&(te(r.data)?this.appWindow.parent.postMessage(r.data,"*"):ne(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function ee(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function te(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 ne(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function x(e){return!!(e&&typeof e=="object")}const M="_";function re(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=k(e);return t+"/#"+n+"?"+H(e)}function k(e){const{chainId:t=1,sell:n,buy:r,tradeType:p=W.SWAP}=e,h=[n?.asset||M,r?.asset||M].map(encodeURIComponent).join("/");return`/${t}/widget/${p}/${h}`}function H(e){const t=new URLSearchParams;return ie(oe(se(t,e),e),e)}function se(e,t){const{sell:n,buy:r}=t;return n?.amount&&e.append("sellAmount",n.amount),r?.amount&&e.append("buyAmount",r.amount),e}function oe(e,t){const n=t.theme;return n?(x(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):(e.append("palette","null"),e.append("theme",n)),e):(e.append("palette","null"),e)}function ie(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}const j="640px",ae="450px",ce=20;function L(e,t){const{params:n,provider:r,listeners:p}=t;let h=r,w=n;const u=ue(n);e.innerHTML="",e.appendChild(u);const{contentWindow:c}=u;if(!c)throw console.error("Iframe does not contain a window",u),new Error("Iframe does not contain a window!");const i=[];i.push(de(c,n.appCode)),i.push(...pe(u,n.height,n.maxHeight)),i.push(fe());const s=new X(window,p);let o=N(c,null,h);u.addEventListener("load",()=>V(c,w,h));const f=new Z(window,c);return{updateParams:d=>{w=d,V(c,w,h)},updateListeners:d=>s.updateListeners(d),updateProvider:d=>{h=d,o=N(c,o,d)},destroy:()=>{o.disconnect(),s.stopListeningIframe(),i.forEach(d=>window.removeEventListener("message",d)),f.stopListening(),e.removeChild(u)}}}function N(e,t,n){t&&t.disconnect();const r=t||new J(e);return n&&r.onConnect(n),r}function ue(e){const{width:t=ae,height:n=j}=e,r=document.createElement("iframe");return r.src=re(e),r.width=t,r.height=n,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function V(e,t,n){const r=!!n,p=k(t),h=H(t).toString(),{theme:w,...u}=t;v.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:p,search:h},appParams:u,hasProvider:r})}function de(e,t){return v.listenToMessageFromWindow(window,I.ACTIVATE,()=>{v.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function fe(){return v.listenToMessageFromWindow(window,I.INTERCEPT_WINDOW_OPEN,({href:e,rel:t,target:n})=>{const r=e.toString();if(!r.startsWith("http")&&r.match(/^[a-zA-Z0-9]+:\/\//)){window.open(r,n,t);return}})}function pe(e,t=j,n){return[v.listenToMessageFromWindow(window,I.UPDATE_HEIGHT,r=>{const p=r.height?r.height+ce:void 0;e.style.height=p?`${n?Math.min(p,n):p}px`:t}),v.listenToMessageFromWindow(window,I.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?t:`${n||document.body.offsetHeight}px`})]}const le=Object.values(W);function he(e,t,n){if(y(e)){const r=e[n];return C(r)?r[t]:r}if(C(e)){const r=e[t];return y(r)?r[n]:r}return e}function y(e){return typeof e!="object"?!1:Object.keys(e).every(t=>le.includes(t))}const Ee=/^\d+$/;function C(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ee.test(t))}function we(e){return y(e)?Object.values(e).flatMap(t=>C(t)?Object.values(t):[t]):C(e)?Object.values(e).flatMap(t=>y(t)?Object.values(t):[t]):[e]}function _e(e){const{params:t,provider:n,listeners:r}=e,[p,h]=T.useState(null),w=T.useRef(null),u=T.useRef(n),c=T.useRef(r),i=T.useRef(null),s=T.useRef(null),o=T.useCallback((f,d)=>{try{console.log(`[WIDGET] ${f}`),d()}catch(l){const _=`Error ${f.toLowerCase()}`;console.error(`[WIDGET] ${_}`,l),h({message:_,error:l})}},[]);return T.useEffect(()=>()=>{w.current=null,u.current=void 0,c.current=void 0;const f=s.current;f&&(o("💥 Destroy widget",()=>f.destroy()),s.current=null)},[]),T.useEffect(()=>{if(!i.current||JSON.stringify(w.current)===JSON.stringify(t))return;const f=i.current,d=s.current;w.current=t,d===null?o("Creating a new widget",()=>{s.current=L(f,{params:t,provider:u.current,listeners:r}),c.current=r}):o("Updating the widget",()=>d.updateParams(t))},[t,o]),T.useEffect(()=>{if(!s.current||u.current===n)return;u.current=n;const f=i.current;f&&o("Updating the provider",()=>{s.current?.destroy(),s.current=L(f,{params:t,provider:u.current,listeners:r})})},[n,o]),T.useEffect(()=>{if(!s.current||c.current===r)return;const f=s.current;o("Updating the listeners",()=>f.updateListeners(r))},[r,o]),p?A.jsxs("div",{style:{color:"#ff3a3a"},children:[p.message,p.error.message&&A.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:p.error.message})]}):A.jsx("div",{ref:i,style:{width:"100%"}})}exports.CowSwapWidget=_e;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=K;exports.WidgetMethodsEmit=I;exports.WidgetMethodsListen=S;exports.createCowSwapWidget=L;exports.isCowSwapWidgetPalette=x;exports.isPerNetworkConfig=C;exports.isPerTradeTypeConfig=y;exports.resolveFlexibleConfig=he;exports.resolveFlexibleConfigValues=we;exports.widgetIframeTransport=v;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),v=require("react");class F{constructor(t){this.key=t}postMessageToWindow(t,n,r){const p=typeof r=="object"?r:{},h={key:this.key,method:n,...p};t.postMessage(h,"*")}listenToMessageFromWindow(t,n,r){const p=h=>{!G(h.data)||h.data.key!==this.key||h.data.method!==n||r(h.data)};return t.addEventListener("message",p),p}stopListeningToMessageFromWindow(t,n,r){t.removeEventListener("message",r)}stopListeningWindowListener(t,n){t.removeEventListener("message",n)}}function G(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var g=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e.SEND_PROVIDER_META_INFO="SEND_PROVIDER_META_INFO",e.REQUEST_PROVIDER_META_INFO="REQUEST_PROVIDER_META_INFO",e))(g||{});const P=new F("cowSwapIframeRpcProviderTransport");function q(e){if(e.isWalletConnect)return e?.session?.peer?.metadata}function $(e,t){return t.find(n=>n.provider===e)?.info}const B=["connect","disconnect","close","chainChanged","accountsChanged"],U=[];typeof window<"u"&&window.addEventListener("eip6963:announceProvider",e=>{const t=e;U.push(t.detail)});class J{constructor(t){this.iframeWidow=t}ethereumProvider=null;requestWaitingForConnection={};disconnect(){typeof window>"u"||(this.ethereumProvider=null,P.stopListeningToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),P.stopListeningToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest))}onConnect(t){typeof window>"u"||(this.ethereumProvider?this.disconnect():P.listenToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),B.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))}),P.listenToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest))}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:p}=t;if(!this.ethereumProvider||!n)return;(p==="enable"?this.ethereumProvider.request({method:"eth_requestAccounts",id:n}):this.ethereumProvider.request({...t,id:n})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:w}}))}processRpcCallFromWindow=({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)};processProviderMetaInfoRequest=()=>{if(!this.ethereumProvider)return;const t=$(this.ethereumProvider,U),n=q(this.ethereumProvider);P.postMessageToWindow(this.iframeWidow,g.SEND_PROVIDER_META_INFO,{providerEip6963Info:t,providerWcMetadata:n})};onProviderEvent(t,n){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_RPC_RESPONSE,t)}}var D={exports:{}},b;function z(){return b||(b=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function h(c,i,s,o,f){if(typeof s!="function")throw new TypeError("The listener must be a function");var d=new p(s,o||c,f),l=n?n+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],d]:c._events[l].push(d):(c._events[l]=d,c._eventsCount++),c}function w(c,i){--c._eventsCount===0?c._events=new r:delete c._events[i]}function u(){this._events=new r,this._eventsCount=0}u.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)t.call(s,o)&&i.push(n?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},u.prototype.listeners=function(i){var s=n?n+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var f=0,d=o.length,l=new Array(d);f<d;f++)l[f]=o[f].fn;return l},u.prototype.listenerCount=function(i){var s=n?n+i:i,o=this._events[s];return o?o.fn?1:o.length:0},u.prototype.emit=function(i,s,o,f,d,l){var _=n?n+i:i;if(!this._events[_])return!1;var a=this._events[_],R=arguments.length,m,E;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),R){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,s),!0;case 3:return a.fn.call(a.context,s,o),!0;case 4:return a.fn.call(a.context,s,o,f),!0;case 5:return a.fn.call(a.context,s,o,f,d),!0;case 6:return a.fn.call(a.context,s,o,f,d,l),!0}for(E=1,m=new Array(R-1);E<R;E++)m[E-1]=arguments[E];a.fn.apply(a.context,m)}else{var Q=a.length,O;for(E=0;E<Q;E++)switch(a[E].once&&this.removeListener(i,a[E].fn,void 0,!0),R){case 1:a[E].fn.call(a[E].context);break;case 2:a[E].fn.call(a[E].context,s);break;case 3:a[E].fn.call(a[E].context,s,o);break;case 4:a[E].fn.call(a[E].context,s,o,f);break;default:if(!m)for(O=1,m=new Array(R-1);O<R;O++)m[O-1]=arguments[O];a[E].fn.apply(a[E].context,m)}}return!0},u.prototype.on=function(i,s,o){return h(this,i,s,o,!1)},u.prototype.once=function(i,s,o){return h(this,i,s,o,!0)},u.prototype.removeListener=function(i,s,o,f){var d=n?n+i:i;if(!this._events[d])return this;if(!s)return w(this,d),this;var l=this._events[d];if(l.fn)l.fn===s&&(!f||l.once)&&(!o||l.context===o)&&w(this,d);else{for(var _=0,a=[],R=l.length;_<R;_++)(l[_].fn!==s||f&&!l[_].once||o&&l[_].context!==o)&&a.push(l[_]);a.length?this._events[d]=a.length===1?a[0]:a:w(this,d)}return this},u.prototype.removeAllListeners=function(i){var s;return i?(s=n?n+i:i,this._events[s]&&w(this,s)):(this._events=new r,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=n,u.EventEmitter=u,e.exports=u}(D)),D.exports}z();class Y{subscriptions={};on(t){const{event:n,handler:r}=t;return this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(r),t}off(t){const{event:n,handler:r}=t;return this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(p=>p!==r)),t}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}var I=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(I||{}),S=(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))(S||{}),W=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(W||{});const K=["primary","background","paper","text","danger","warning","alert","info","success"],T=new F("cowSwapWidget");class X{constructor(t,n=[]){this.contentWindow=t,this.updateListeners(n),this.widgetListener=T.listenToMessageFromWindow(this.contentWindow,I.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}eventEmitter=new Y;listeners=[];widgetListener;stopListeningIframe(){T.stopListeningWindowListener(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 Z{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=r=>{ee(r.data)&&(typeof window<"u"&&r.origin===window.location.origin||(te(r.data)?this.appWindow.parent.postMessage(r.data,"*"):ne(r.data)&&this.iframeWidow.postMessage(r.data,"*")))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function ee(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function te(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 ne(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function x(e){return!!(e&&typeof e=="object")}const M="_";function re(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=k(e);return t+"/#"+n+"?"+H(e)}function k(e){const{chainId:t=1,sell:n,buy:r,tradeType:p=W.SWAP}=e,h=[n?.asset||M,r?.asset||M].map(encodeURIComponent).join("/");return`/${t}/widget/${p}/${h}`}function H(e){const t=new URLSearchParams;return ie(oe(se(t,e),e),e)}function se(e,t){const{sell:n,buy:r}=t;return n?.amount&&e.append("sellAmount",n.amount),r?.amount&&e.append("buyAmount",r.amount),e}function oe(e,t){const n=t.theme;return n?(x(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):(e.append("palette","null"),e.append("theme",n)),e):(e.append("palette","null"),e)}function ie(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}const j="640px",ae="450px",ce=20,ue={updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function L(e,t){const{params:n,provider:r,listeners:p}=t;let h=r,w=n;if(typeof window>"u")return ue;const u=de(n);e.innerHTML="",e.appendChild(u);const{contentWindow:c}=u;if(!c)throw console.error("Iframe does not contain a window",u),new Error("Iframe does not contain a window!");const i=[];i.push(fe(c,n.appCode)),i.push(...le(u,n.height,n.maxHeight)),i.push(pe());const s=new X(window,p);let o=N(c,null,h);u.addEventListener("load",()=>V(c,w,h));const f=new Z(window,c);return{updateParams:d=>{w=d,V(c,w,h)},updateListeners:d=>s.updateListeners(d),updateProvider:d=>{h=d,o=N(c,o,d)},destroy:()=>{o.disconnect(),s.stopListeningIframe(),i.forEach(d=>window.removeEventListener("message",d)),f.stopListening(),e.removeChild(u)}}}function N(e,t,n){t&&t.disconnect();const r=t||new J(e);return n&&r.onConnect(n),r}function de(e){const{width:t=ae,height:n=j}=e,r=document.createElement("iframe");return r.src=re(e),r.width=t,r.height=n,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function V(e,t,n){const r=!!n,p=k(t),h=H(t).toString(),{theme:w,...u}=t;T.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:p,search:h},appParams:u,hasProvider:r})}function fe(e,t){return T.listenToMessageFromWindow(window,I.ACTIVATE,()=>{T.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function pe(){return T.listenToMessageFromWindow(window,I.INTERCEPT_WINDOW_OPEN,({href:e,rel:t,target:n})=>{const r=e.toString();if(!r.startsWith("http")&&r.match(/^[a-zA-Z0-9]+:\/\//)){window.open(r,n,t);return}})}function le(e,t=j,n){return[T.listenToMessageFromWindow(window,I.UPDATE_HEIGHT,r=>{const p=r.height?r.height+ce:void 0;e.style.height=p?`${n?Math.min(p,n):p}px`:t}),T.listenToMessageFromWindow(window,I.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?t:`${n||document.body.offsetHeight}px`})]}const he=Object.values(W);function Ee(e,t,n){if(y(e)){const r=e[n];return C(r)?r[t]:r}if(C(e)){const r=e[t];return y(r)?r[n]:r}return e}function y(e){return typeof e!="object"?!1:Object.keys(e).every(t=>he.includes(t))}const we=/^\d+$/;function C(e){return typeof e!="object"?!1:Object.keys(e).every(t=>we.test(t))}function _e(e){return y(e)?Object.values(e).flatMap(t=>C(t)?Object.values(t):[t]):C(e)?Object.values(e).flatMap(t=>y(t)?Object.values(t):[t]):[e]}function ve(e){const{params:t,provider:n,listeners:r}=e,[p,h]=v.useState(null),w=v.useRef(null),u=v.useRef(n),c=v.useRef(r),i=v.useRef(null),s=v.useRef(null),o=v.useCallback((f,d)=>{try{console.log(`[WIDGET] ${f}`),d()}catch(l){const _=`Error ${f.toLowerCase()}`;console.error(`[WIDGET] ${_}`,l),h({message:_,error:l})}},[]);return v.useEffect(()=>()=>{w.current=null,u.current=void 0,c.current=void 0;const f=s.current;f&&(o("💥 Destroy widget",()=>f.destroy()),s.current=null)},[]),v.useEffect(()=>{if(!i.current||JSON.stringify(w.current)===JSON.stringify(t))return;const f=i.current,d=s.current;w.current=t,d===null?o("Creating a new widget",()=>{s.current=L(f,{params:t,provider:u.current,listeners:r}),c.current=r}):o("Updating the widget",()=>d.updateParams(t))},[t,o]),v.useEffect(()=>{if(!s.current||u.current===n)return;u.current=n;const f=i.current;f&&o("Updating the provider",()=>{s.current?.destroy(),s.current=L(f,{params:t,provider:u.current,listeners:r})})},[n,o]),v.useEffect(()=>{if(!s.current||c.current===r)return;const f=s.current;o("Updating the listeners",()=>f.updateListeners(r))},[r,o]),p?A.jsxs("div",{style:{color:"#ff3a3a"},children:[p.message,p.error.message&&A.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:p.error.message})]}):A.jsx("div",{ref:i,style:{width:"100%"}})}exports.CowSwapWidget=ve;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=K;exports.WidgetMethodsEmit=I;exports.WidgetMethodsListen=S;exports.createCowSwapWidget=L;exports.isCowSwapWidgetPalette=x;exports.isPerNetworkConfig=C;exports.isPerTradeTypeConfig=y;exports.resolveFlexibleConfig=Ee;exports.resolveFlexibleConfigValues=_e;exports.widgetIframeTransport=T;
|
package/index.mjs
CHANGED
|
@@ -4,8 +4,6 @@ class U {
|
|
|
4
4
|
constructor(t) {
|
|
5
5
|
this.key = t;
|
|
6
6
|
}
|
|
7
|
-
// TODO: Add proper return type annotation
|
|
8
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
9
7
|
postMessageToWindow(t, n, r) {
|
|
10
8
|
const p = typeof r == "object" ? r : {}, h = {
|
|
11
9
|
key: this.key,
|
|
@@ -24,13 +22,9 @@ class U {
|
|
|
24
22
|
};
|
|
25
23
|
return t.addEventListener("message", p), p;
|
|
26
24
|
}
|
|
27
|
-
// TODO: Add proper return type annotation
|
|
28
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
29
25
|
stopListeningToMessageFromWindow(t, n, r) {
|
|
30
26
|
t.removeEventListener("message", r);
|
|
31
27
|
}
|
|
32
|
-
// TODO: Add proper return type annotation
|
|
33
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
34
28
|
stopListeningWindowListener(t, n) {
|
|
35
29
|
t.removeEventListener("message", n);
|
|
36
30
|
}
|
|
@@ -50,7 +44,7 @@ function z(e, t) {
|
|
|
50
44
|
return t.find((n) => n.provider === e)?.info;
|
|
51
45
|
}
|
|
52
46
|
const Y = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"], x = [];
|
|
53
|
-
window.addEventListener("eip6963:announceProvider", (e) => {
|
|
47
|
+
typeof window < "u" && window.addEventListener("eip6963:announceProvider", (e) => {
|
|
54
48
|
const t = e;
|
|
55
49
|
x.push(t.detail);
|
|
56
50
|
});
|
|
@@ -73,10 +67,8 @@ class K {
|
|
|
73
67
|
/**
|
|
74
68
|
* Disconnects the JSON-RPC bridge from the Ethereum provider.
|
|
75
69
|
*/
|
|
76
|
-
// TODO: Add proper return type annotation
|
|
77
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
78
70
|
disconnect() {
|
|
79
|
-
this.ethereumProvider = null, P.stopListeningToMessageFromWindow(
|
|
71
|
+
typeof window > "u" || (this.ethereumProvider = null, P.stopListeningToMessageFromWindow(
|
|
80
72
|
window,
|
|
81
73
|
m.PROVIDER_RPC_REQUEST,
|
|
82
74
|
this.processRpcCallFromWindow
|
|
@@ -84,16 +76,14 @@ class K {
|
|
|
84
76
|
window,
|
|
85
77
|
m.REQUEST_PROVIDER_META_INFO,
|
|
86
78
|
this.processProviderMetaInfoRequest
|
|
87
|
-
);
|
|
79
|
+
));
|
|
88
80
|
}
|
|
89
81
|
/**
|
|
90
82
|
* Handles the 'connect' event and sets up event listeners for Ethereum provider events.
|
|
91
83
|
* @param newProvider - The Ethereum provider to connect.
|
|
92
84
|
*/
|
|
93
|
-
// TODO: Add proper return type annotation
|
|
94
|
-
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
95
85
|
onConnect(t) {
|
|
96
|
-
this.ethereumProvider ? this.disconnect() : P.listenToMessageFromWindow(
|
|
86
|
+
typeof window > "u" || (this.ethereumProvider ? this.disconnect() : P.listenToMessageFromWindow(
|
|
97
87
|
window,
|
|
98
88
|
m.PROVIDER_RPC_REQUEST,
|
|
99
89
|
this.processRpcCallFromWindow
|
|
@@ -103,7 +93,7 @@ class K {
|
|
|
103
93
|
window,
|
|
104
94
|
m.REQUEST_PROVIDER_META_INFO,
|
|
105
95
|
this.processProviderMetaInfoRequest
|
|
106
|
-
);
|
|
96
|
+
));
|
|
107
97
|
}
|
|
108
98
|
// TODO: Add proper return type annotation
|
|
109
99
|
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
|
|
@@ -290,7 +280,7 @@ class Z {
|
|
|
290
280
|
}
|
|
291
281
|
}
|
|
292
282
|
var g = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.INTERCEPT_WINDOW_OPEN = "INTERCEPT_WINDOW_OPEN", e))(g || {}), A = /* @__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))(A || {}), D = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(D || {});
|
|
293
|
-
const
|
|
283
|
+
const Te = [
|
|
294
284
|
"primary",
|
|
295
285
|
"background",
|
|
296
286
|
"paper",
|
|
@@ -328,7 +318,7 @@ class ee {
|
|
|
328
318
|
class te {
|
|
329
319
|
constructor(t, n) {
|
|
330
320
|
this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (r) => {
|
|
331
|
-
ne(r.data) && r.origin
|
|
321
|
+
ne(r.data) && (typeof window < "u" && r.origin === window.location.origin || (re(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : se(r.data) && this.iframeWidow.postMessage(r.data, "*")));
|
|
332
322
|
}, this.startListening();
|
|
333
323
|
}
|
|
334
324
|
forwardSdkMessage;
|
|
@@ -379,17 +369,27 @@ function ce(e, t) {
|
|
|
379
369
|
function ue(e, t) {
|
|
380
370
|
return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
|
|
381
371
|
}
|
|
382
|
-
const Q = "640px", de = "450px", fe = 20
|
|
372
|
+
const Q = "640px", de = "450px", fe = 20, pe = {
|
|
373
|
+
updateParams: () => {
|
|
374
|
+
},
|
|
375
|
+
updateListeners: () => {
|
|
376
|
+
},
|
|
377
|
+
updateProvider: () => {
|
|
378
|
+
},
|
|
379
|
+
destroy: () => {
|
|
380
|
+
}
|
|
381
|
+
};
|
|
383
382
|
function M(e, t) {
|
|
384
383
|
const { params: n, provider: r, listeners: p } = t;
|
|
385
384
|
let h = r, w = n;
|
|
386
|
-
|
|
385
|
+
if (typeof window > "u") return pe;
|
|
386
|
+
const u = le(n);
|
|
387
387
|
e.innerHTML = "", e.appendChild(u);
|
|
388
388
|
const { contentWindow: c } = u;
|
|
389
389
|
if (!c)
|
|
390
390
|
throw console.error("Iframe does not contain a window", u), new Error("Iframe does not contain a window!");
|
|
391
391
|
const i = [];
|
|
392
|
-
i.push(
|
|
392
|
+
i.push(he(c, n.appCode)), i.push(...we(u, n.height, n.maxHeight)), i.push(Ee());
|
|
393
393
|
const s = new ee(window, p);
|
|
394
394
|
let o = V(c, null, h);
|
|
395
395
|
u.addEventListener("load", () => F(c, w, h));
|
|
@@ -412,7 +412,7 @@ function V(e, t, n) {
|
|
|
412
412
|
const r = t || new K(e);
|
|
413
413
|
return n && r.onConnect(n), r;
|
|
414
414
|
}
|
|
415
|
-
function
|
|
415
|
+
function le(e) {
|
|
416
416
|
const { width: t = de, height: n = Q } = e, r = document.createElement("iframe");
|
|
417
417
|
return r.src = ie(e), r.width = t, r.height = n, r.style.border = "0", r.allow = "clipboard-read; clipboard-write", r;
|
|
418
418
|
}
|
|
@@ -427,14 +427,14 @@ function F(e, t, n) {
|
|
|
427
427
|
hasProvider: r
|
|
428
428
|
});
|
|
429
429
|
}
|
|
430
|
-
function
|
|
430
|
+
function he(e, t) {
|
|
431
431
|
return R.listenToMessageFromWindow(window, g.ACTIVATE, () => {
|
|
432
432
|
R.postMessageToWindow(e, A.UPDATE_APP_DATA, {
|
|
433
433
|
metaData: t ? { appCode: t } : void 0
|
|
434
434
|
});
|
|
435
435
|
});
|
|
436
436
|
}
|
|
437
|
-
function
|
|
437
|
+
function Ee() {
|
|
438
438
|
return R.listenToMessageFromWindow(
|
|
439
439
|
window,
|
|
440
440
|
g.INTERCEPT_WINDOW_OPEN,
|
|
@@ -447,7 +447,7 @@ function he() {
|
|
|
447
447
|
}
|
|
448
448
|
);
|
|
449
449
|
}
|
|
450
|
-
function
|
|
450
|
+
function we(e, t = Q, n) {
|
|
451
451
|
return [
|
|
452
452
|
R.listenToMessageFromWindow(window, g.UPDATE_HEIGHT, (r) => {
|
|
453
453
|
const p = r.height ? r.height + fe : void 0;
|
|
@@ -458,8 +458,8 @@ function Ee(e, t = Q, n) {
|
|
|
458
458
|
})
|
|
459
459
|
];
|
|
460
460
|
}
|
|
461
|
-
const
|
|
462
|
-
function
|
|
461
|
+
const _e = Object.values(D);
|
|
462
|
+
function Pe(e, t, n) {
|
|
463
463
|
if (C(e)) {
|
|
464
464
|
const r = e[n];
|
|
465
465
|
return S(r) ? r[t] : r;
|
|
@@ -471,16 +471,16 @@ function Te(e, t, n) {
|
|
|
471
471
|
return e;
|
|
472
472
|
}
|
|
473
473
|
function C(e) {
|
|
474
|
-
return typeof e != "object" ? !1 : Object.keys(e).every((t) =>
|
|
474
|
+
return typeof e != "object" ? !1 : Object.keys(e).every((t) => _e.includes(t));
|
|
475
475
|
}
|
|
476
|
-
const
|
|
476
|
+
const ve = /^\d+$/;
|
|
477
477
|
function S(e) {
|
|
478
|
-
return typeof e != "object" ? !1 : Object.keys(e).every((t) =>
|
|
478
|
+
return typeof e != "object" ? !1 : Object.keys(e).every((t) => ve.test(t));
|
|
479
479
|
}
|
|
480
|
-
function
|
|
480
|
+
function ge(e) {
|
|
481
481
|
return C(e) ? Object.values(e).flatMap((t) => S(t) ? Object.values(t) : [t]) : S(e) ? Object.values(e).flatMap((t) => C(t) ? Object.values(t) : [t]) : [e];
|
|
482
482
|
}
|
|
483
|
-
function
|
|
483
|
+
function Ie(e) {
|
|
484
484
|
const { params: t, provider: n, listeners: r } = e, [p, h] = q(null), w = O(null), u = O(n), c = O(r), i = O(null), s = O(null), o = $((f, d) => {
|
|
485
485
|
try {
|
|
486
486
|
console.log(`[WIDGET] ${f}`), d();
|
|
@@ -518,16 +518,16 @@ function ge(e) {
|
|
|
518
518
|
] }) : /* @__PURE__ */ L("div", { ref: i, style: { width: "100%" } });
|
|
519
519
|
}
|
|
520
520
|
export {
|
|
521
|
-
|
|
521
|
+
Ie as CowSwapWidget,
|
|
522
522
|
D as TradeType,
|
|
523
|
-
|
|
523
|
+
Te as WIDGET_PALETTE_COLORS,
|
|
524
524
|
g as WidgetMethodsEmit,
|
|
525
525
|
A as WidgetMethodsListen,
|
|
526
526
|
M as createCowSwapWidget,
|
|
527
527
|
oe as isCowSwapWidgetPalette,
|
|
528
528
|
S as isPerNetworkConfig,
|
|
529
529
|
C as isPerTradeTypeConfig,
|
|
530
|
-
|
|
531
|
-
|
|
530
|
+
Pe as resolveFlexibleConfig,
|
|
531
|
+
ge as resolveFlexibleConfigValues,
|
|
532
532
|
R as widgetIframeTransport
|
|
533
533
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cowprotocol/widget-react",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.6",
|
|
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.22.
|
|
25
|
+
"@cowprotocol/widget-lib": "^0.22.3"
|
|
26
26
|
}
|
|
27
27
|
}
|