@cowprotocol/widget-react
Version:
CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.
2 lines (1 loc) • 12.2 kB
JavaScript
var G=Object.defineProperty;var j=(e,n,t)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var _=(e,n,t)=>(j(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("react/jsx-runtime"),g=require("react");class U{constructor(n){this.key=n}postMessageToWindow(n,t,r){const p=typeof r=="object"?r:{},h={key:this.key,method:t,...p};n.postMessage(h,"*")}listenToMessageFromWindow(n,t,r){const p=h=>{!Q(h.data)||h.data.key!==this.key||h.data.method!==t||r(h.data)};return n.addEventListener("message",p),p}stopListeningToMessageFromWindow(n,t,r){n.removeEventListener("message",r)}stopListeningWindowListener(n,t){n.removeEventListener("message",t)}}function Q(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var C=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(C||{});const O=new U("cowSwapIframeRpcProviderTransport"),$=["connect","disconnect","close","chainChanged","accountsChanged"];class q{constructor(n){_(this,"ethereumProvider",null);_(this,"requestWaitingForConnection",{});_(this,"processRpcCallFromWindow",({rpcRequest:n})=>{if(!this.ethereumProvider){n.id&&(this.requestWaitingForConnection[n.id]=n);return}this.processRpcRequest(n)});this.iframeWidow=n}disconnect(){this.ethereumProvider=null,O.stopListeningToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():O.listenToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),$.forEach(t=>{n.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:r,method:p}=n;if(!this.ethereumProvider||!t)return;(p==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:w}}))}onProviderEvent(n,t){O.postMessageToWindow(this.iframeWidow,C.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){O.postMessageToWindow(this.iframeWidow,C.PROVIDER_RPC_RESPONSE,n)}}var B={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function h(c,i,s,o,d){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new p(s,o||c,d),l=t?t+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],u]:c._events[l].push(u):(c._events[l]=u,c._eventsCount++),c}function w(c,i){--c._eventsCount===0?c._events=new r:delete c._events[i]}function f(){this._events=new r,this._eventsCount=0}f.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)n.call(s,o)&&i.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},f.prototype.listeners=function(i){var s=t?t+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var d=0,u=o.length,l=new Array(u);d<u;d++)l[d]=o[d].fn;return l},f.prototype.listenerCount=function(i){var s=t?t+i:i,o=this._events[s];return o?o.fn?1:o.length:0},f.prototype.emit=function(i,s,o,d,u,l){var m=t?t+i:i;if(!this._events[m])return!1;var a=this._events[m],v=arguments.length,R,E;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),v){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,d),!0;case 5:return a.fn.call(a.context,s,o,d,u),!0;case 6:return a.fn.call(a.context,s,o,d,u,l),!0}for(E=1,R=new Array(v-1);E<v;E++)R[E-1]=arguments[E];a.fn.apply(a.context,R)}else{var H=a.length,y;for(E=0;E<H;E++)switch(a[E].once&&this.removeListener(i,a[E].fn,void 0,!0),v){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,d);break;default:if(!R)for(y=1,R=new Array(v-1);y<v;y++)R[y-1]=arguments[y];a[E].fn.apply(a[E].context,R)}}return!0},f.prototype.on=function(i,s,o){return h(this,i,s,o,!1)},f.prototype.once=function(i,s,o){return h(this,i,s,o,!0)},f.prototype.removeListener=function(i,s,o,d){var u=t?t+i:i;if(!this._events[u])return this;if(!s)return w(this,u),this;var l=this._events[u];if(l.fn)l.fn===s&&(!d||l.once)&&(!o||l.context===o)&&w(this,u);else{for(var m=0,a=[],v=l.length;m<v;m++)(l[m].fn!==s||d&&!l[m].once||o&&l[m].context!==o)&&a.push(l[m]);a.length?this._events[u]=a.length===1?a[0]:a:w(this,u)}return this},f.prototype.removeAllListeners=function(i){var s;return i?(s=t?t+i:i,this._events[s]&&w(this,s)):(this._events=new r,this._eventsCount=0),this},f.prototype.off=f.prototype.removeListener,f.prototype.addListener=f.prototype.on,f.prefixed=t,f.EventEmitter=f,e.exports=f})(B);class J{constructor(){_(this,"subscriptions",{})}on(n){const{event:t,handler:r}=n;return this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r),n}off(n){const{event:t,handler:r}=n;return this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(p=>p!==r)),n}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(r=>r(t))}}var P=(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))(P||{}),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||{}),I=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(I||{});const z=["primary","background","paper","text","danger","warning","alert","info","success"],T=new U("cowSwapWidget");class Y{constructor(n,t=[]){_(this,"eventEmitter",new J);_(this,"listeners",[]);_(this,"widgetListener");this.contentWindow=n,this.updateListeners(t),this.widgetListener=T.listenToMessageFromWindow(this.contentWindow,P.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){T.stopListeningWindowListener(this.contentWindow,this.widgetListener)}updateListeners(n){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=n||[];for(const t of this.listeners)this.eventEmitter.on(t)}}class K{constructor(n,t){_(this,"forwardSdkMessage");this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=r=>{X(r.data)&&r.origin!==window.location.origin&&(Z(r.data)?this.appWindow.parent.postMessage(r.data,"*"):ee(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function X(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function Z(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 ee(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function V(e){return!!(e&&typeof e=="object")}const b="_";function te(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=x(e);return n+"/#"+t+"?"+F(e)}function x(e){const{chainId:n=1,sell:t,buy:r,tradeType:p=I.SWAP}=e,h=[(t==null?void 0:t.asset)||b,(r==null?void 0:r.asset)||b].map(encodeURIComponent).join("/");return`/${n}/widget/${p}/${h}`}function F(e){const n=new URLSearchParams;return re(ne(n,e),e)}function ne(e,n){const{sell:t,buy:r}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),r!=null&&r.amount&&e.append("buyAmount",r.amount),e}function re(e,n){const t=n.theme;return t?(V(t)?(e.append("palette",encodeURIComponent(JSON.stringify(t))),e.append("theme",t.baseTheme)):(e.append("palette","null"),e.append("theme",t)),e):(e.append("palette","null"),e)}const k="640px",se="450px",oe=20;function L(e,n){const{params:t,provider:r,listeners:p}=n;let h=r,w=t;const f=ie(t);e.innerHTML="",e.appendChild(f);const{contentWindow:c}=f;if(!c)throw console.error("Iframe does not contain a window",f),new Error("Iframe does not contain a window!");const i=[];i.push(ae(c,t.appCode)),i.push(...ue(f,t.height,t.maxHeight)),i.push(ce());const s=new Y(window,p);let o=N(c,null,h);f.addEventListener("load",()=>M(c,w,h));const d=new K(window,c);return{updateParams:u=>{w=u,M(c,w,h)},updateListeners:u=>s.updateListeners(u),updateProvider:u=>{h=u,o=N(c,o,u)},destroy:()=>{o.disconnect(),s.stopListeningIframe(),i.forEach(u=>window.removeEventListener("message",u)),d.stopListening(),e.removeChild(f)}}}function N(e,n,t){n&&n.disconnect();const r=n||new q(e);return t&&r.onConnect(t),r}function ie(e){const{width:n=se,height:t=k}=e,r=document.createElement("iframe");return r.src=te(e),r.width=n,r.height=t,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function M(e,n,t){const r=!!t,p=x(n),h=F(n).toString(),{theme:w,...f}=n;T.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:p,search:h},appParams:f,hasProvider:r})}function ae(e,n){return T.listenToMessageFromWindow(window,P.ACTIVATE,()=>{T.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})})}function ce(){return T.listenToMessageFromWindow(window,P.INTERCEPT_WINDOW_OPEN,({href:e,rel:n,target:t})=>{const r=e.toString();if(!r.startsWith("http")&&r.match(/^[a-zA-Z0-9]+:\/\//)){window.open(r,t,n);return}})}function ue(e,n=k,t){return[T.listenToMessageFromWindow(window,P.UPDATE_HEIGHT,r=>{const p=r.height?r.height+oe:void 0;e.style.height=p?`${t?Math.min(p,t):p}px`:n}),T.listenToMessageFromWindow(window,P.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?n:`${t||document.body.offsetHeight}px`})]}const fe=Object.values(I);function de(e,n,t){if(A(e)){const r=e[t];return D(r)?r[n]:r}if(D(e)){const r=e[n];return A(r)?r[t]:r}return e}function A(e){return typeof e!="object"?!1:Object.keys(e).every(n=>fe.includes(n))}const pe=/^\d+$/;function D(e){return typeof e!="object"?!1:Object.keys(e).every(n=>typeof n=="number"||pe.test(n))}function le(e){const{params:n,provider:t,listeners:r}=e,[p,h]=g.useState(null),w=g.useRef(null),f=g.useRef(t),c=g.useRef(r),i=g.useRef(null),s=g.useRef(null),o=g.useCallback((d,u)=>{try{console.log(`[WIDGET] ${d}`),u()}catch(l){const m=`Error ${d.toLowerCase()}`;console.error(`[WIDGET] ${m}`,l),h({message:m,error:l})}},[]);return g.useEffect(()=>()=>{w.current=null,f.current=void 0,c.current=void 0;const d=s.current;d&&(o("💥 Destroy widget",()=>d.destroy()),s.current=null)},[]),g.useEffect(()=>{if(!i.current||JSON.stringify(w.current)===JSON.stringify(n))return;const d=i.current,u=s.current;w.current=n,u===null?o("Creating a new widget",()=>{s.current=L(d,{params:n,provider:f.current,listeners:r}),c.current=r}):o("Updating the widget",()=>u.updateParams(n))},[n,o]),g.useEffect(()=>{if(!s.current||f.current===t)return;f.current=t;const d=i.current;d&&o("Updating the provider",()=>{var u;(u=s.current)==null||u.destroy(),s.current=L(d,{params:n,provider:f.current,listeners:r})})},[t,o]),g.useEffect(()=>{if(!s.current||c.current===r)return;const d=s.current;o("Updating the listeners",()=>d.updateListeners(r))},[r,o]),p?W.jsxs("div",{style:{color:"#ff3a3a"},children:[p.message,p.error.message&&W.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:p.error.message})]}):W.jsx("div",{ref:i,style:{width:"100%"}})}exports.CowSwapWidget=le;exports.TradeType=I;exports.WIDGET_PALETTE_COLORS=z;exports.WidgetMethodsEmit=P;exports.WidgetMethodsListen=S;exports.createCowSwapWidget=L;exports.isCowSwapWidgetPalette=V;exports.isPerNetworkConfig=D;exports.isPerTradeTypeConfig=A;exports.resolveFlexibleConfig=de;exports.widgetIframeTransport=T;
;