@cowprotocol/widget-lib 4.4.1 → 4.4.3

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.
@@ -11,6 +11,12 @@ export declare const DEFAULT_WIDGET_PARAMS: {
11
11
  * - allow-forms: trade inputs and similar controls.
12
12
  * - allow-popups + allow-popups-to-escape-sandbox: wallet connect / WalletConnect windows.
13
13
  */
14
+ /**
15
+ * Iframe sandbox allowlist for hosts that opt out of opening widget popups.
16
+ * Omitting allow-popups makes `disableWindowOpen` browser-enforced instead of
17
+ * only disabling the parent-window relay.
18
+ */
19
+ export declare const WIDGET_IFRAME_SANDBOX_WITHOUT_POPUPS = "allow-scripts allow-same-origin allow-forms";
14
20
  export declare const WIDGET_IFRAME_SANDBOX = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox";
15
21
  /** Limits referrer leakage when the widget is embedded on third-party origins. */
16
22
  export declare const WIDGET_IFRAME_REFERRER_POLICY = "strict-origin-when-cross-origin";
@@ -1,5 +1,5 @@
1
1
  import { SupportedChainId } from '@cowprotocol/cow-sdk';
2
2
  import { FlexibleConfig, PerNetworkConfig, PerTradeTypeConfig, TradeType } from './types';
3
- export declare function resolveFlexibleConfig<T>(config: FlexibleConfig<T>, chainId: SupportedChainId, tradeType: TradeType): T | undefined;
4
3
  export declare function isPerTradeTypeConfig<T>(config: FlexibleConfig<T>): config is PerTradeTypeConfig<T>;
4
+ export declare function resolveFlexibleConfig<T>(config: FlexibleConfig<T>, chainId: SupportedChainId, tradeType: TradeType): T | undefined;
5
5
  export declare function isPerNetworkConfig<T>(config: FlexibleConfig<T>): config is PerNetworkConfig<T>;
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@cowprotocol/iframe-transport"),oe=require("@cowprotocol/events"),re=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),ie=new Set(["http:","https:"]);function se(e){try{const t=new URL(e).protocol;return ie.has(t)||re.has(t)}catch{return!1}}function ae(e,t){if(t){e.removeAttribute("style");for(const n of Object.keys(t)){const o=n,r=t[o];if(r==null||typeof r!="string"&&typeof r!="number")continue;const i=`${r}`;e.style[o]=i}}}const K="cowswap-widget-iframe",de="cowswap-widget",le={appCode:""},Y="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",Q="strict-origin-when-cross-origin",z="clipboard-read; clipboard-write";var w=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",e))(w||{}),T=(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.HOOK_RESULT="HOOK_RESULT",e))(T||{}),g=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(g||{}),L=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(L||{});const ce=["primary","background","paper","text","danger","warning","alert","info","success"],p=new D.IframeTransport("cowSwapWidget");class ue{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=p.listenToMessageFromWindow(this.contentWindow,o,w.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new oe.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){p.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 pe{constructor(t,n,o,r){this.appWindow=t,this.iframeWindow=n,this.iframeOrigin=o,this.parentOrigin=r,this.forwardSdkMessage=i=>{fe(i.data)&&(Ee(i.data)?this.forwardRequest(i,i.data):we(i.data)&&this.forwardResponse(i,i.data))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}forwardRequest(t,n){!this.parentOrigin||this.appWindow.parent===this.appWindow||t.source!==this.iframeWindow||t.origin!==this.iframeOrigin||this.appWindow.parent.postMessage(n,this.parentOrigin)}forwardResponse(t,n){this.appWindow.parent!==this.appWindow&&(t.source!==this.appWindow.parent||t.origin!==this.parentOrigin||this.iframeWindow.postMessage(n,this.iframeOrigin))}}function fe(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function Ee(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 we(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function he(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function ge(...e){process.env.NODE_ENV!=="test"&&he("Widget","#47aba8",...e)}function b(e){return!!(e&&typeof e=="object")}const X="https://swap.cow.fi",B="_",_e="CoW Swap widget: invalid baseUrl.",J=!1;function Re(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function W(e,t){const n=`${_e} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),X}function Z(e,t=J){const n=typeof e=="string"?e.trim():"";if(!n)return X;let o;try{o=new URL(n)}catch{return W(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return W("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&Re(o.hostname);if(!r&&!i)return W(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const f=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${f}`}function me(e){const t=Z(e.baseUrl),n=q(e);return t+"/#"+n+"?"+ee(e)}function q(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=L.SWAP}=e,i=[n?.asset||B,o?.asset||B].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function ee(e){const t=new URLSearchParams;return Ae(ye(Te(Se(Oe(t,e),e),e),e),e)}function Oe(e,t){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function Se(e,t){const n=t.theme;return n?(b(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 Te(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ye(e,t){return t.locale&&e.append("lng",t.locale),e}function Ae(e,t){return Le(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function Le(e){return!!e&&Object.values(e).some(Boolean)}const Ce=3e4,h="cow-widget-loading-error",k=`data-${h}`;function Ie(e,t,n,o,r){const i=t.src;let f=!1,E=null;function c(){r?.(),t.style.display="none",Pe();const l=document.createElement("div"),s=document.createElement("button"),d=document.createElement("p");s.innerText="Reload",s.addEventListener("click",()=>{e.removeChild(l),o(!0),t.src="about:blank",t.style.display="",setTimeout(()=>{t.src=i,n()},100)}),d.innerText="Couldn't load the page. Please, try again later",l.classList.add(h),l.appendChild(d),l.appendChild(s),e.appendChild(l)}return t.addEventListener("error",l=>{f||(console.error("Could not load iframe",l),c())}),E=window.setTimeout(()=>{f||c()},Ce),{onWidgetReady(){E&&clearTimeout(E);const l=document.getElementsByClassName(h)[0];l&&e.removeChild(l)},cancelWidgetLoading(){f=!0}}}let m=null;function Pe(){if(!(typeof document>"u")){if(We()){m||(m=new CSSStyleSheet,m.replaceSync(M)),document.adoptedStyleSheets.includes(m)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,m]);return}if(!document.head.querySelector(`style[${k}]`)){const e=document.createElement("style");e.setAttribute(k,""),e.textContent=M,document.head.appendChild(e)}}}function We(){return typeof document<"u"&&"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet=="function"&&typeof CSSStyleSheet.prototype.replaceSync=="function"}const M=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("@cowprotocol/iframe-transport"),se=require("@cowprotocol/events"),ae=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),de=new Set(["http:","https:"]);function le(e){try{const t=new URL(e).protocol;return de.has(t)||ae.has(t)}catch{return!1}}function ce(e,t){if(t){e.removeAttribute("style");for(const n of Object.keys(t)){const o=n,r=t[o];if(r==null||typeof r!="string"&&typeof r!="number")continue;const i=`${r}`;e.style[o]=i}}}const Y="cowswap-widget-iframe",ue="cowswap-widget",pe={appCode:""},Q="allow-scripts allow-same-origin allow-forms",z=`${Q} allow-popups allow-popups-to-escape-sandbox`,X="strict-origin-when-cross-origin",J="clipboard-read; clipboard-write";var I=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(I||{}),g=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(g||{}),w=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",e))(w||{}),T=(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.HOOK_RESULT="HOOK_RESULT",e))(T||{});const fe=["primary","background","paper","text","danger","warning","alert","info","success"],p=new v.IframeTransport("cowSwapWidget");class Ee{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=p.listenToMessageFromWindow(this.contentWindow,o,w.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new se.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){p.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 we{constructor(t,n,o,r){this.appWindow=t,this.iframeWindow=n,this.iframeOrigin=o,this.parentOrigin=r,this.forwardSdkMessage=i=>{he(i.data)&&(ge(i.data)?this.forwardRequest(i,i.data):_e(i.data)&&this.forwardResponse(i,i.data))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}forwardRequest(t,n){!this.parentOrigin||this.appWindow.parent===this.appWindow||t.source!==this.iframeWindow||t.origin!==this.iframeOrigin||this.appWindow.parent.postMessage(n,this.parentOrigin)}forwardResponse(t,n){this.appWindow.parent!==this.appWindow&&(t.source!==this.appWindow.parent||t.origin!==this.parentOrigin||this.iframeWindow.postMessage(n,this.iframeOrigin))}}function he(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function ge(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 _e(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function Oe(...e){process.env.NODE_ENV!=="test"&&Re("Widget","#47aba8",...e)}function Re(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function D(e){return!!(e&&typeof e=="object")}const Z="https://swap.cow.fi",k="_",me="CoW Swap widget: invalid baseUrl.",q=!1;function ee(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=I.SWAP}=e,i=[n?.asset||k,o?.asset||k].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function te(e){const t=oe(e.baseUrl),n=ee(e);return t+"/#"+n+"?"+ne(e)}function ne(e){const t=new URLSearchParams;return Se(Te(ye(Ae(Ie(t,e),e),e),e),e)}function oe(e,t=q){const n=typeof e=="string"?e.trim():"";if(!n)return Z;let o;try{o=new URL(n)}catch{return W(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return W("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&Ce(o.hostname);if(!r&&!i)return W(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const f=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${f}`}function Se(e,t){return Le(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function Te(e,t){return t.locale&&e.append("lng",t.locale),e}function ye(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function Ae(e,t){const n=t.theme;return n?(D(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){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function W(e,t){const n=`${me} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),Z}function Le(e){return!!e&&Object.values(e).some(Boolean)}function Ce(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}const Pe=3e4,h="cow-widget-loading-error",M=`data-${h}`;function We(e,t,n,o,r){const i=t.src;let f=!1,E=null;function d(){r?.(),t.style.display="none",be();const c=document.createElement("div"),s=document.createElement("button"),l=document.createElement("p");s.innerText="Reload",s.addEventListener("click",()=>{e.removeChild(c),o(!0),t.src="about:blank",t.style.display="",setTimeout(()=>{t.src=i,n()},100)}),l.innerText="Couldn't load the page. Please, try again later",c.classList.add(h),c.appendChild(l),c.appendChild(s),e.appendChild(c)}return t.addEventListener("error",c=>{f||(console.error("Could not load iframe",c),d())}),E=window.setTimeout(()=>{f||d()},Pe),{onWidgetReady(){E&&clearTimeout(E);const c=document.getElementsByClassName(h)[0];c&&e.removeChild(c)},cancelWidgetLoading(){f=!0}}}let R=null;function be(){if(!(typeof document>"u")){if(ve()){R||(R=new CSSStyleSheet,R.replaceSync(V)),document.adoptedStyleSheets.includes(R)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,R]);return}if(!document.head.querySelector(`style[${M}]`)){const e=document.createElement("style");e.setAttribute(M,""),e.textContent=V,document.head.appendChild(e)}}}function ve(){return typeof document<"u"&&"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet=="function"&&typeof CSSStyleSheet.prototype.replaceSync=="function"}const V=`
2
2
  .${h} {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -41,4 +41,4 @@
41
41
  .${h} button:not(:disabled):hover {
42
42
  background: #d32f2f;
43
43
  color: #fff5f5;
44
- }`,ve={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function De(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:f=!0}=t;let E=o,c=V(n),l="";if(typeof window>"u")return ve;const s=Ne(c),d=Ue(s);ge("Resolved trusted iframe origin",{iframeOrigin:d});const y=[];e.innerHTML="",e.appendChild(s),G(e,c);let a=null,C=()=>{},I=()=>{},N=()=>{},P=null,A=null,U=null,H=[],R=null;function F(){if(a=s.contentWindow,!a)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");y.push(Fe(a,d,()=>{i?.(),te()})),y.push(He(a,d,c.appCode)),H=Me(e,s,d,ne=>{l=ne});let u=null;C=()=>{a&&(u&&window.removeEventListener("message",u),!c.disableWindowOpen&&(u=xe(d,a),y.push(u)))},I=()=>{a&&(R&&window.removeEventListener("message",R),R=Ge(a,d,c.hooks))},C(),I(),P=new ue(window,d,a,r),A=$(a,d,null,E),s.addEventListener("load",()=>{a&&j(a,d,c,E)}),U=be(f,window,a,d);const _=Ie(e,s,F,x,t.onLoadingError);N=_.cancelWidgetLoading;const te=_.onWidgetReady}function x(u=!1){A?.disconnect(),P?.stopListeningIframe(),H.forEach(_=>window.removeEventListener("message",_)),y.forEach(_=>window.removeEventListener("message",_)),R&&window.removeEventListener("message",R),U?.stopListening(),!u&&s&&s.parentNode===e&&e.removeChild(s),N?.()}return F(),{iframe:s,updateParams:u=>{a&&(c=V(u),G(e,c,l),j(a,d,c,E),C(),I())},updateListeners:u=>P?.updateListeners(u),updateProvider:u=>{a&&(E=u,A=$(a,d,A,u))},destroy:x}}function be(e,t,n,o){return e?new pe(t,n,o,D.getParentOrigin()||null):null}function V(e){const t={...le,...e};if(typeof t.appCode!="string"||t.appCode.trim().length===0)throw new Error("Required param `appCode` is missing");return t}function $(e,t,n,o){n&&n.disconnect();const r=n||new D.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function Ne(e){const t=document.createElement("iframe");return t.id=K,t.src=me(e),t.setAttribute("sandbox",Y),t.referrerPolicy=Q,t.allow=z,t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",t}function G(e,t,n){ae(e,t.rootStyle),[{name:"params.width",value:t.width,replacementName:"rootStyle.width",replacementValue:t.rootStyle?.width,applyDeprecated:()=>t.width?e.style.width=t.width:void 0},{name:"params.height",value:t.height,replacementName:"rootStyle.height",replacementValue:t.rootStyle?.height,applyDeprecated:()=>t.height?e.style.height=t.height:void 0},{name:"params.maxHeight",value:t.maxHeight,replacementName:"rootStyle.maxHeight",replacementValue:t.rootStyle?.maxHeight,applyDeprecated:()=>t.maxHeight?e.style.maxHeight=`${t.maxHeight}px`:void 0},{name:"params.theme.boxShadow",value:b(t.theme)?t.theme.boxShadow:void 0,replacementName:"cardStyle.boxShadow",replacementValue:t.cardStyle?.boxShadow,applyDeprecated:()=>{}}].filter(r=>!!r.value).forEach(r=>{r.replacementValue?console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`):(console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`),r.applyDeprecated())}),n&&e.style.setProperty(v,n)}function Ue(e){return new URL(e.src).origin}function j(e,t,n,o){const r=!!o,i=q(n),f=ee(n).toString(),{theme:E,hooks:c,rootStyle:l,...s}=n;p.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:f},appParams:s,hasProvider:r},t)}function He(e,t,n){return p.listenToMessageFromWindow(window,e,w.ACTIVATE,()=>{p.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function Fe(e,t,n){let o=!1;return p.listenToMessageFromWindow(window,e,w.READY,()=>{o||(o=!0,n())},t)}function xe(e,t){return p.listenToMessageFromWindow(window,t,w.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Be(n.toString(),e);i&&se(i)&&window.open(i,r,o)},e)}function Be(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}const v="--dynamicHeight",ke=0;function Me(e,t,n,o){return t.contentWindow?[p.listenToMessageFromWindow(window,t.contentWindow,w.UPDATE_HEIGHT,r=>{const i=`${(r?.height??0)+ke}px`;e.style.setProperty(v,i),o(i)},n),p.listenToMessageFromWindow(window,t.contentWindow,w.SET_FULL_HEIGHT,()=>{e.style.setProperty(v,"100dvh"),o("100dvh")},n)]:[]}const Ve={[g.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[g.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[g.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[g.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[g.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function $e(e,t){return Ve[e.event](e.payload,t)}function Ge(e,t,n){return p.listenToMessageFromWindow(window,e,w.PROCESS_HOOK,async o=>{let r=!1;try{r=await $e(o,n)}catch{}p.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const je=Object.values(L);function Ke(e,t,n){if(O(e)){const o=e[n];return S(o)?o[t]:o}if(S(e)){const o=e[t];return O(o)?o[n]:o}return e}function O(e){return typeof e!="object"?!1:Object.keys(e).every(t=>je.includes(t))}const Ye=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ye.test(t))}function Qe(e){return O(e)?Object.values(e).flatMap(t=>S(t)?Object.values(t):[t]):S(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=J;exports.TradeType=L;exports.WIDGET_CONTAINER_ID=de;exports.WIDGET_IFRAME_ALLOW=z;exports.WIDGET_IFRAME_ID=K;exports.WIDGET_IFRAME_REFERRER_POLICY=Q;exports.WIDGET_IFRAME_SANDBOX=Y;exports.WIDGET_PALETTE_COLORS=ce;exports.WidgetHookEvents=g;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=De;exports.isCowSwapWidgetPalette=b;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=Ke;exports.resolveFlexibleConfigValues=Qe;exports.sanitizeWidgetBaseUrl=Z;exports.widgetIframeTransport=p;
44
+ }`,De={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function Ne(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:f=!0}=t;let E=o,d=G(n),c="";if(typeof window>"u")return De;const s=Ue(d),l=He(s);Oe("Resolved trusted iframe origin",{iframeOrigin:l});const y=[];e.innerHTML="",e.appendChild(s),$(e,d);let a=null,L=()=>{},C=()=>{},U=()=>{},P=null,A=null,x=null,H=[],O=null;function F(){if(a=s.contentWindow,!a)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");y.push(Be(a,l,()=>{i?.(),re()})),y.push($e(a,l,d.appCode)),H=je(e,s,l,ie=>{c=ie});let u=null;L=()=>{a&&(u&&window.removeEventListener("message",u),!d.disableWindowOpen&&(u=Fe(l,a),y.push(u)))},C=()=>{a&&(O&&window.removeEventListener("message",O),O=Qe(a,l,d.hooks))},L(),C(),P=new Ee(window,l,a,r),A=K(a,l,null,E),s.addEventListener("load",()=>{a&&j(a,l,d,E)}),x=xe(f,window,a,l);const _=We(e,s,F,B,t.onLoadingError);U=_.cancelWidgetLoading;const re=_.onWidgetReady}function B(u=!1){A?.disconnect(),P?.stopListeningIframe(),H.forEach(_=>window.removeEventListener("message",_)),y.forEach(_=>window.removeEventListener("message",_)),O&&window.removeEventListener("message",O),x?.stopListening(),!u&&s&&s.parentNode===e&&e.removeChild(s),U?.()}return F(),{iframe:s,updateParams:u=>{a&&(d=G(u),$(e,d,c),Me(s,d)?ke(s,d):j(a,l,d,E),L(),C())},updateListeners:u=>P?.updateListeners(u),updateProvider:u=>{a&&(E=u,A=K(a,l,A,u))},destroy:B}}function $(e,t,n){ce(e,t.rootStyle),[{name:"params.width",value:t.width,replacementName:"rootStyle.width",replacementValue:t.rootStyle?.width,applyDeprecated:()=>t.width?e.style.width=t.width:void 0},{name:"params.height",value:t.height,replacementName:"rootStyle.height",replacementValue:t.rootStyle?.height,applyDeprecated:()=>t.height?e.style.height=t.height:void 0},{name:"params.maxHeight",value:t.maxHeight,replacementName:"rootStyle.maxHeight",replacementValue:t.rootStyle?.maxHeight,applyDeprecated:()=>t.maxHeight?e.style.maxHeight=`${t.maxHeight}px`:void 0},{name:"params.theme.boxShadow",value:D(t.theme)?t.theme.boxShadow:void 0,replacementName:"cardStyle.boxShadow",replacementValue:t.cardStyle?.boxShadow,applyDeprecated:()=>{}}].filter(r=>!!r.value).forEach(r=>{r.replacementValue?console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`):(console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`),r.applyDeprecated())}),n&&e.style.setProperty(b,n)}function Ue(e){const t=document.createElement("iframe");return t.id=Y,t.src=te(e),t.setAttribute("sandbox",N(e)),t.referrerPolicy=X,t.allow=J,t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",t}function xe(e,t,n,o){return e?new we(t,n,o,v.getParentOrigin()||null):null}function He(e){return new URL(e.src).origin}function N(e){return e.disableWindowOpen?Q:z}function Fe(e,t){return p.listenToMessageFromWindow(window,t,w.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Ve(n.toString(),e);i&&le(i)&&window.open(i,r,o)},e)}function Be(e,t,n){let o=!1;return p.listenToMessageFromWindow(window,e,w.READY,()=>{o||(o=!0,n())},t)}function ke(e,t){const n=N(t),o=te(t);e.addEventListener("load",()=>{e.src=o},{once:!0}),e.setAttribute("sandbox",n),e.src="about:blank"}function Me(e,t){const n=N(t);return e.getAttribute("sandbox")!==n}function G(e){const t={...pe,...e};if(typeof t.appCode!="string"||t.appCode.trim().length===0)throw new Error("Required param `appCode` is missing");if(t.disableWindowOpen&&t.standaloneMode!==!1)throw new Error("`disableWindowOpen: true` requires `standaloneMode: false`");return t}function Ve(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}function $e(e,t,n){return p.listenToMessageFromWindow(window,e,w.ACTIVATE,()=>{p.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function j(e,t,n,o){const r=!!o,i=ee(n),f=ne(n).toString(),{theme:E,hooks:d,rootStyle:c,...s}=n;p.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:f},appParams:s,hasProvider:r},t)}function K(e,t,n,o){n&&n.disconnect();const r=n||new v.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}const b="--dynamicHeight",Ge=0;function je(e,t,n,o){return t.contentWindow?[p.listenToMessageFromWindow(window,t.contentWindow,w.UPDATE_HEIGHT,r=>{const i=`${(r?.height??0)+Ge}px`;e.style.setProperty(b,i),o(i)},n),p.listenToMessageFromWindow(window,t.contentWindow,w.SET_FULL_HEIGHT,()=>{e.style.setProperty(b,"100dvh"),o("100dvh")},n)]:[]}const Ke={[g.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[g.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[g.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[g.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[g.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function Ye(e,t){return Ke[e.event](e.payload,t)}function Qe(e,t,n){return p.listenToMessageFromWindow(window,e,w.PROCESS_HOOK,async o=>{let r=!1;try{r=await Ye(o,n)}catch{}p.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const ze=Object.values(I);function m(e){return typeof e!="object"?!1:Object.keys(e).every(t=>ze.includes(t))}function Xe(e,t,n){if(m(e)){const o=e[n];return S(o)?o[t]:o}if(S(e)){const o=e[t];return m(o)?o[n]:o}return e}const Je=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Je.test(t))}function Ze(e){return m(e)?Object.values(e).flatMap(t=>S(t)?Object.values(t):[t]):S(e)?Object.values(e).flatMap(t=>m(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=q;exports.TradeType=I;exports.WIDGET_CONTAINER_ID=ue;exports.WIDGET_IFRAME_ALLOW=J;exports.WIDGET_IFRAME_ID=Y;exports.WIDGET_IFRAME_REFERRER_POLICY=X;exports.WIDGET_IFRAME_SANDBOX=z;exports.WIDGET_PALETTE_COLORS=fe;exports.WidgetHookEvents=g;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=Ne;exports.isCowSwapWidgetPalette=D;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=m;exports.resolveFlexibleConfig=Xe;exports.resolveFlexibleConfigValues=Ze;exports.sanitizeWidgetBaseUrl=oe;exports.widgetIframeTransport=p;
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { IframeTransport as X, IframeRpcProviderBridge as J, getParentOrigin as Z } from "@cowprotocol/iframe-transport";
2
- import { SimpleCowEventEmitter as q } from "@cowprotocol/events";
3
- const ee = /* @__PURE__ */ new Set([
1
+ import { IframeTransport as q, IframeRpcProviderBridge as ee, getParentOrigin as te } from "@cowprotocol/iframe-transport";
2
+ import { SimpleCowEventEmitter as ne } from "@cowprotocol/events";
3
+ const oe = /* @__PURE__ */ new Set([
4
4
  "wc:",
5
5
  // default Wallet-connect protocol
6
6
  "metamask:",
@@ -27,16 +27,16 @@ const ee = /* @__PURE__ */ new Set([
27
27
  "tpoutside:",
28
28
  "bncus:",
29
29
  "bnc:"
30
- ]), te = /* @__PURE__ */ new Set(["http:", "https:"]);
31
- function ne(e) {
30
+ ]), re = /* @__PURE__ */ new Set(["http:", "https:"]);
31
+ function ie(e) {
32
32
  try {
33
33
  const t = new URL(e).protocol;
34
- return te.has(t) || ee.has(t);
34
+ return re.has(t) || oe.has(t);
35
35
  } catch {
36
36
  return !1;
37
37
  }
38
38
  }
39
- function oe(e, t) {
39
+ function se(e, t) {
40
40
  if (t) {
41
41
  e.removeAttribute("style");
42
42
  for (const n of Object.keys(t)) {
@@ -48,16 +48,16 @@ function oe(e, t) {
48
48
  }
49
49
  }
50
50
  }
51
- const re = "cowswap-widget-iframe", Qe = "cowswap-widget", ie = {
51
+ const ae = "cowswap-widget-iframe", Ze = "cowswap-widget", de = {
52
52
  appCode: ""
53
- }, se = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", ae = "strict-origin-when-cross-origin", le = "clipboard-read; clipboard-write";
54
- var w = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(w || {}), 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.HOOK_RESULT = "HOOK_RESULT", e))(A || {}), m = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(m || {}), W = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(W || {});
55
- const ze = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], p = new X("cowSwapWidget");
56
- class de {
53
+ }, j = "allow-scripts allow-same-origin allow-forms", le = `${j} allow-popups allow-popups-to-escape-sandbox`, ce = "strict-origin-when-cross-origin", ue = "clipboard-read; clipboard-write";
54
+ var W = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(W || {}), m = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(m || {}), h = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(h || {}), 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.HOOK_RESULT = "HOOK_RESULT", e))(A || {});
55
+ const qe = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], p = new q("cowSwapWidget");
56
+ class pe {
57
57
  constructor(t, n, o, r = []) {
58
- this.contentWindow = t, this.updateListeners(r), this.widgetListener = p.listenToMessageFromWindow(this.contentWindow, o, w.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
58
+ this.contentWindow = t, this.updateListeners(r), this.widgetListener = p.listenToMessageFromWindow(this.contentWindow, o, h.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
59
59
  }
60
- eventEmitter = new q();
60
+ eventEmitter = new ne();
61
61
  listeners = [];
62
62
  widgetListener;
63
63
  stopListeningIframe() {
@@ -71,10 +71,10 @@ class de {
71
71
  this.eventEmitter.on(n);
72
72
  }
73
73
  }
74
- class ce {
74
+ class fe {
75
75
  constructor(t, n, o, r) {
76
76
  this.appWindow = t, this.iframeWindow = n, this.iframeOrigin = o, this.parentOrigin = r, this.forwardSdkMessage = (i) => {
77
- ue(i.data) && (pe(i.data) ? this.forwardRequest(i, i.data) : fe(i.data) && this.forwardResponse(i, i.data));
77
+ Ee(i.data) && (we(i.data) ? this.forwardRequest(i, i.data) : he(i.data) && this.forwardResponse(i, i.data));
78
78
  }, this.startListening();
79
79
  }
80
80
  forwardSdkMessage;
@@ -91,114 +91,114 @@ class ce {
91
91
  this.appWindow.parent !== this.appWindow && (t.source !== this.appWindow.parent || t.origin !== this.parentOrigin || this.iframeWindow.postMessage(n, this.iframeOrigin));
92
92
  }
93
93
  }
94
- function ue(e) {
94
+ function Ee(e) {
95
95
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
96
96
  }
97
- function pe(e) {
97
+ function we(e) {
98
98
  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;
99
99
  }
100
- function fe(e) {
100
+ function he(e) {
101
101
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
102
102
  }
103
- function Ee(e = "Default", t = "#1c5dbf", ...n) {
104
- console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
103
+ function ge(...e) {
104
+ process.env.NODE_ENV !== "test" && me("Widget", "#47aba8", ...e);
105
105
  }
106
- function he(...e) {
107
- process.env.NODE_ENV !== "test" && Ee("Widget", "#47aba8", ...e);
106
+ function me(e = "Default", t = "#1c5dbf", ...n) {
107
+ console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
108
108
  }
109
- function G(e) {
109
+ function K(e) {
110
110
  return !!(e && typeof e == "object");
111
111
  }
112
- const j = "https://swap.cow.fi", x = "_", we = "CoW Swap widget: invalid baseUrl.", ge = !1;
113
- function me(e) {
114
- return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
112
+ const Y = "https://swap.cow.fi", B = "_", _e = "CoW Swap widget: invalid baseUrl.", Oe = !1;
113
+ function Q(e) {
114
+ const {
115
+ chainId: t = 1,
116
+ sell: n,
117
+ buy: o,
118
+ tradeType: r = W.SWAP
119
+ } = e, i = [n?.asset || B, o?.asset || B].map(encodeURIComponent).join("/");
120
+ return `/${t}/widget/${r}/${i}`;
115
121
  }
116
- function v(e, t) {
117
- const n = `${we} ${e}`;
118
- if (t)
119
- throw new Error(n);
120
- return console.error("[CoW Widget]", n), j;
122
+ function z(e) {
123
+ const t = Re(e.baseUrl), n = Q(e);
124
+ return t + "/#" + n + "?" + X(e);
125
+ }
126
+ function X(e) {
127
+ const t = new URLSearchParams();
128
+ return Se(Te(ye(Ae(Le(t, e), e), e), e), e);
121
129
  }
122
- function _e(e, t = ge) {
130
+ function Re(e, t = Oe) {
123
131
  const n = typeof e == "string" ? e.trim() : "";
124
132
  if (!n)
125
- return j;
133
+ return Y;
126
134
  let o;
127
135
  try {
128
136
  o = new URL(n);
129
137
  } catch {
130
- return v(`Not a valid URL: ${JSON.stringify(n)}`, t);
138
+ return b(`Not a valid URL: ${JSON.stringify(n)}`, t);
131
139
  }
132
140
  if (o.username || o.password)
133
- return v("Userinfo (username/password) in URL is not allowed.", t);
134
- const r = o.protocol === "https:", i = o.protocol === "http:" && me(o.hostname);
141
+ return b("Userinfo (username/password) in URL is not allowed.", t);
142
+ const r = o.protocol === "https:", i = o.protocol === "http:" && Ce(o.hostname);
135
143
  if (!r && !i)
136
- return v(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
144
+ return b(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
137
145
  const f = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
138
146
  return `${o.origin}${f}`;
139
147
  }
140
- function Oe(e) {
141
- const t = _e(e.baseUrl), n = K(e);
142
- return t + "/#" + n + "?" + Y(e);
148
+ function Se(e, t) {
149
+ return Pe(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
143
150
  }
144
- function K(e) {
145
- const {
146
- chainId: t = 1,
147
- sell: n,
148
- buy: o,
149
- tradeType: r = W.SWAP
150
- } = e, i = [n?.asset || x, o?.asset || x].map(encodeURIComponent).join("/");
151
- return `/${t}/widget/${r}/${i}`;
151
+ function Te(e, t) {
152
+ return t.locale && e.append("lng", t.locale), e;
152
153
  }
153
- function Y(e) {
154
- const t = new URLSearchParams();
155
- return Ae(Te(ye(Se(Re(t, e), e), e), e), e);
154
+ function ye(e, t) {
155
+ return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
156
+ }
157
+ function Ae(e, t) {
158
+ const n = t.theme;
159
+ return n ? (K(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);
156
160
  }
157
- function Re(e, t) {
161
+ function Le(e, t) {
158
162
  const {
159
163
  sell: n,
160
164
  buy: o
161
165
  } = t;
162
166
  return n?.amount && e.append("sellAmount", n.amount), o?.amount && e.append("buyAmount", o.amount), e;
163
167
  }
164
- function Se(e, t) {
165
- const n = t.theme;
166
- return n ? (G(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);
167
- }
168
- function ye(e, t) {
169
- return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
170
- }
171
- function Te(e, t) {
172
- return t.locale && e.append("lng", t.locale), e;
173
- }
174
- function Ae(e, t) {
175
- return Le(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
168
+ function b(e, t) {
169
+ const n = `${_e} ${e}`;
170
+ if (t)
171
+ throw new Error(n);
172
+ return console.error("[CoW Widget]", n), Y;
176
173
  }
177
- function Le(e) {
174
+ function Pe(e) {
178
175
  return !!e && Object.values(e).some(Boolean);
179
176
  }
180
- const Ce = 3e4, h = "cow-widget-loading-error", B = `data-${h}`;
181
- function Pe(e, t, n, o, r) {
177
+ function Ce(e) {
178
+ return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
179
+ }
180
+ const be = 3e4, w = "cow-widget-loading-error", k = `data-${w}`;
181
+ function Ie(e, t, n, o, r) {
182
182
  const i = t.src;
183
183
  let f = !1, E = null;
184
- function c() {
185
- r?.(), t.style.display = "none", ve();
186
- const d = document.createElement("div"), s = document.createElement("button"), l = document.createElement("p");
184
+ function d() {
185
+ r?.(), t.style.display = "none", We();
186
+ const c = document.createElement("div"), s = document.createElement("button"), l = document.createElement("p");
187
187
  s.innerText = "Reload", s.addEventListener("click", () => {
188
- e.removeChild(d), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
188
+ e.removeChild(c), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
189
189
  t.src = i, n();
190
190
  }, 100);
191
- }), l.innerText = "Couldn't load the page. Please, try again later", d.classList.add(h), d.appendChild(l), d.appendChild(s), e.appendChild(d);
191
+ }), l.innerText = "Couldn't load the page. Please, try again later", c.classList.add(w), c.appendChild(l), c.appendChild(s), e.appendChild(c);
192
192
  }
193
- return t.addEventListener("error", (d) => {
194
- f || (console.error("Could not load iframe", d), c());
193
+ return t.addEventListener("error", (c) => {
194
+ f || (console.error("Could not load iframe", c), d());
195
195
  }), E = window.setTimeout(() => {
196
- f || c();
197
- }, Ce), {
196
+ f || d();
197
+ }, be), {
198
198
  onWidgetReady() {
199
199
  E && clearTimeout(E);
200
- const d = document.getElementsByClassName(h)[0];
201
- d && e.removeChild(d);
200
+ const c = document.getElementsByClassName(w)[0];
201
+ c && e.removeChild(c);
202
202
  },
203
203
  cancelWidgetLoading() {
204
204
  f = !0;
@@ -206,23 +206,23 @@ function Pe(e, t, n, o, r) {
206
206
  };
207
207
  }
208
208
  let O = null;
209
- function ve() {
209
+ function We() {
210
210
  if (!(typeof document > "u")) {
211
- if (Ie()) {
212
- O || (O = new CSSStyleSheet(), O.replaceSync(k)), document.adoptedStyleSheets.includes(O) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, O]);
211
+ if (ve()) {
212
+ O || (O = new CSSStyleSheet(), O.replaceSync(F)), document.adoptedStyleSheets.includes(O) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, O]);
213
213
  return;
214
214
  }
215
- if (!document.head.querySelector(`style[${B}]`)) {
215
+ if (!document.head.querySelector(`style[${k}]`)) {
216
216
  const e = document.createElement("style");
217
- e.setAttribute(B, ""), e.textContent = k, document.head.appendChild(e);
217
+ e.setAttribute(k, ""), e.textContent = F, document.head.appendChild(e);
218
218
  }
219
219
  }
220
220
  }
221
- function Ie() {
221
+ function ve() {
222
222
  return typeof document < "u" && "adoptedStyleSheets" in Document.prototype && typeof CSSStyleSheet == "function" && typeof CSSStyleSheet.prototype.replaceSync == "function";
223
223
  }
224
- const k = `
225
- .${h} {
224
+ const F = `
225
+ .${w} {
226
226
  display: flex;
227
227
  flex-direction: column;
228
228
  gap: 16px;
@@ -242,11 +242,11 @@ const k = `
242
242
  font-weight: 500;
243
243
  }
244
244
 
245
- .${h} p {
245
+ .${w} p {
246
246
  margin: 0;
247
247
  }
248
248
 
249
- .${h} button {
249
+ .${w} button {
250
250
  padding: 8px 24px;
251
251
  border-radius: 8px;
252
252
  font: inherit;
@@ -256,15 +256,15 @@ const k = `
256
256
  color: #d32f2f;
257
257
  }
258
258
 
259
- .${h} button:disabled {
259
+ .${w} button:disabled {
260
260
  cursor: progress;
261
261
  opacity: 0.75;
262
262
  }
263
263
 
264
- .${h} button:not(:disabled):hover {
264
+ .${w} button:not(:disabled):hover {
265
265
  background: #d32f2f;
266
266
  color: #fff5f5;
267
- }`, We = {
267
+ }`, De = {
268
268
  iframe: null,
269
269
  updateParams: () => {
270
270
  },
@@ -275,7 +275,7 @@ const k = `
275
275
  destroy: () => {
276
276
  }
277
277
  };
278
- function Xe(e, t) {
278
+ function et(e, t) {
279
279
  const {
280
280
  params: n,
281
281
  provider: o,
@@ -283,76 +283,55 @@ function Xe(e, t) {
283
283
  onReady: i,
284
284
  enableSafeSdkBridge: f = !0
285
285
  } = t;
286
- let E = o, c = F(n), d = "";
287
- if (typeof window > "u") return We;
288
- const s = De(c), l = Ne(s);
289
- he("Resolved trusted iframe origin", {
286
+ let E = o, d = V(n), c = "";
287
+ if (typeof window > "u") return De;
288
+ const s = Ne(d), l = xe(s);
289
+ ge("Resolved trusted iframe origin", {
290
290
  iframeOrigin: l
291
291
  });
292
292
  const R = [];
293
- e.innerHTML = "", e.appendChild(s), M(e, c);
293
+ e.innerHTML = "", e.appendChild(s), M(e, d);
294
294
  let a = null, L = () => {
295
- }, C = () => {
296
- }, b = () => {
297
- }, P = null, S = null, D = null, N = [], _ = null;
298
- function U() {
295
+ }, P = () => {
296
+ }, D = () => {
297
+ }, C = null, S = null, N = null, U = [], _ = null;
298
+ function x() {
299
299
  if (a = s.contentWindow, !a)
300
300
  throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
301
- R.push(He(a, l, () => {
302
- i?.(), Q();
303
- })), R.push(Ue(a, l, c.appCode)), N = Fe(e, s, l, (z) => {
304
- d = z;
301
+ R.push(Be(a, l, () => {
302
+ i?.(), J();
303
+ })), R.push(Ve(a, l, d.appCode)), U = Ge(e, s, l, (Z) => {
304
+ c = Z;
305
305
  });
306
306
  let u = null;
307
307
  L = () => {
308
- a && (u && window.removeEventListener("message", u), !c.disableWindowOpen && (u = xe(l, a), R.push(u)));
309
- }, C = () => {
310
- a && (_ && window.removeEventListener("message", _), _ = $e(a, l, c.hooks));
311
- }, L(), C(), P = new de(window, l, a, r), S = V(a, l, null, E), s.addEventListener("load", () => {
312
- a && $(a, l, c, E);
313
- }), D = be(f, window, a, l);
314
- const g = Pe(e, s, U, H, t.onLoadingError);
315
- b = g.cancelWidgetLoading;
316
- const Q = g.onWidgetReady;
308
+ a && (u && window.removeEventListener("message", u), !d.disableWindowOpen && (u = He(l, a), R.push(u)));
309
+ }, P = () => {
310
+ a && (_ && window.removeEventListener("message", _), _ = Ye(a, l, d.hooks));
311
+ }, L(), P(), C = new pe(window, l, a, r), S = G(a, l, null, E), s.addEventListener("load", () => {
312
+ a && $(a, l, d, E);
313
+ }), N = Ue(f, window, a, l);
314
+ const g = Ie(e, s, x, H, t.onLoadingError);
315
+ D = g.cancelWidgetLoading;
316
+ const J = g.onWidgetReady;
317
317
  }
318
318
  function H(u = !1) {
319
- S?.disconnect(), P?.stopListeningIframe(), N.forEach((g) => window.removeEventListener("message", g)), R.forEach((g) => window.removeEventListener("message", g)), _ && window.removeEventListener("message", _), D?.stopListening(), !u && s && s.parentNode === e && e.removeChild(s), b?.();
319
+ S?.disconnect(), C?.stopListeningIframe(), U.forEach((g) => window.removeEventListener("message", g)), R.forEach((g) => window.removeEventListener("message", g)), _ && window.removeEventListener("message", _), N?.stopListening(), !u && s && s.parentNode === e && e.removeChild(s), D?.();
320
320
  }
321
- return U(), {
321
+ return x(), {
322
322
  iframe: s,
323
323
  updateParams: (u) => {
324
- a && (c = F(u), M(e, c, d), $(a, l, c, E), L(), C());
324
+ a && (d = V(u), M(e, d, c), Fe(s, d) ? ke(s, d) : $(a, l, d, E), L(), P());
325
325
  },
326
- updateListeners: (u) => P?.updateListeners(u),
326
+ updateListeners: (u) => C?.updateListeners(u),
327
327
  updateProvider: (u) => {
328
- a && (E = u, S = V(a, l, S, u));
328
+ a && (E = u, S = G(a, l, S, u));
329
329
  },
330
330
  destroy: H
331
331
  };
332
332
  }
333
- function be(e, t, n, o) {
334
- return e ? new ce(t, n, o, Z() || null) : null;
335
- }
336
- function F(e) {
337
- const t = {
338
- ...ie,
339
- ...e
340
- };
341
- if (typeof t.appCode != "string" || t.appCode.trim().length === 0)
342
- throw new Error("Required param `appCode` is missing");
343
- return t;
344
- }
345
- function V(e, t, n, o) {
346
- n && n.disconnect();
347
- const r = n || new J(e, t);
348
- return o && r.onConnect(o), r;
349
- }
350
- function De(e) {
351
- const t = document.createElement("iframe");
352
- return t.id = re, t.src = Oe(e), t.setAttribute("sandbox", se), t.referrerPolicy = ae, t.allow = le, t.style.width = "100%", t.style.height = "100%", t.style.border = "0", t.style.display = "block", t;
353
- }
354
333
  function M(e, t, n) {
355
- oe(e, t.rootStyle), [{
334
+ se(e, t.rootStyle), [{
356
335
  name: "params.width",
357
336
  value: t.width,
358
337
  replacementName: "rootStyle.width",
@@ -372,7 +351,7 @@ function M(e, t, n) {
372
351
  applyDeprecated: () => t.maxHeight ? e.style.maxHeight = `${t.maxHeight}px` : void 0
373
352
  }, {
374
353
  name: "params.theme.boxShadow",
375
- value: G(t.theme) ? t.theme.boxShadow : void 0,
354
+ value: K(t.theme) ? t.theme.boxShadow : void 0,
376
355
  replacementName: "cardStyle.boxShadow",
377
356
  replacementValue: t.cardStyle?.boxShadow,
378
357
  applyDeprecated: () => {
@@ -382,50 +361,58 @@ function M(e, t, n) {
382
361
  }), n && e.style.setProperty(I, n);
383
362
  }
384
363
  function Ne(e) {
385
- return new URL(e.src).origin;
364
+ const t = document.createElement("iframe");
365
+ return t.id = ae, t.src = z(e), t.setAttribute("sandbox", v(e)), t.referrerPolicy = ce, t.allow = ue, t.style.width = "100%", t.style.height = "100%", t.style.border = "0", t.style.display = "block", t;
386
366
  }
387
- function $(e, t, n, o) {
388
- const r = !!o, i = K(n), f = Y(n).toString(), {
389
- theme: E,
390
- hooks: c,
391
- rootStyle: d,
392
- ...s
393
- } = n;
394
- p.postMessageToWindow(e, A.UPDATE_PARAMS, {
395
- urlParams: {
396
- pathname: i,
397
- search: f
398
- },
399
- appParams: s,
400
- hasProvider: r
401
- }, t);
367
+ function Ue(e, t, n, o) {
368
+ return e ? new fe(t, n, o, te() || null) : null;
402
369
  }
403
- function Ue(e, t, n) {
404
- return p.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
405
- p.postMessageToWindow(e, A.UPDATE_APP_DATA, {
406
- metaData: n ? {
407
- appCode: n
408
- } : void 0
409
- }, t);
410
- }, t);
370
+ function xe(e) {
371
+ return new URL(e.src).origin;
411
372
  }
412
- function He(e, t, n) {
413
- let o = !1;
414
- return p.listenToMessageFromWindow(window, e, w.READY, () => {
415
- o || (o = !0, n());
416
- }, t);
373
+ function v(e) {
374
+ return e.disableWindowOpen ? j : le;
417
375
  }
418
- function xe(e, t) {
419
- return p.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
376
+ function He(e, t) {
377
+ return p.listenToMessageFromWindow(window, t, h.INTERCEPT_WINDOW_OPEN, ({
420
378
  href: n,
421
379
  rel: o,
422
380
  target: r
423
381
  }) => {
424
- const i = Be(n.toString(), e);
425
- i && ne(i) && window.open(i, r, o);
382
+ const i = Me(n.toString(), e);
383
+ i && ie(i) && window.open(i, r, o);
426
384
  }, e);
427
385
  }
428
- function Be(e, t) {
386
+ function Be(e, t, n) {
387
+ let o = !1;
388
+ return p.listenToMessageFromWindow(window, e, h.READY, () => {
389
+ o || (o = !0, n());
390
+ }, t);
391
+ }
392
+ function ke(e, t) {
393
+ const n = v(t), o = z(t);
394
+ e.addEventListener("load", () => {
395
+ e.src = o;
396
+ }, {
397
+ once: !0
398
+ }), e.setAttribute("sandbox", n), e.src = "about:blank";
399
+ }
400
+ function Fe(e, t) {
401
+ const n = v(t);
402
+ return e.getAttribute("sandbox") !== n;
403
+ }
404
+ function V(e) {
405
+ const t = {
406
+ ...de,
407
+ ...e
408
+ };
409
+ if (typeof t.appCode != "string" || t.appCode.trim().length === 0)
410
+ throw new Error("Required param `appCode` is missing");
411
+ if (t.disableWindowOpen && t.standaloneMode !== !1)
412
+ throw new Error("`disableWindowOpen: true` requires `standaloneMode: false`");
413
+ return t;
414
+ }
415
+ function Me(e, t) {
429
416
  const n = e.trim();
430
417
  if (!n)
431
418
  return null;
@@ -435,30 +422,60 @@ function Be(e, t) {
435
422
  return null;
436
423
  }
437
424
  }
438
- const I = "--dynamicHeight", ke = 0;
439
- function Fe(e, t, n, o) {
440
- return t.contentWindow ? [p.listenToMessageFromWindow(window, t.contentWindow, w.UPDATE_HEIGHT, (r) => {
441
- const i = `${(r?.height ?? 0) + ke}px`;
425
+ function Ve(e, t, n) {
426
+ return p.listenToMessageFromWindow(window, e, h.ACTIVATE, () => {
427
+ p.postMessageToWindow(e, A.UPDATE_APP_DATA, {
428
+ metaData: n ? {
429
+ appCode: n
430
+ } : void 0
431
+ }, t);
432
+ }, t);
433
+ }
434
+ function $(e, t, n, o) {
435
+ const r = !!o, i = Q(n), f = X(n).toString(), {
436
+ theme: E,
437
+ hooks: d,
438
+ rootStyle: c,
439
+ ...s
440
+ } = n;
441
+ p.postMessageToWindow(e, A.UPDATE_PARAMS, {
442
+ urlParams: {
443
+ pathname: i,
444
+ search: f
445
+ },
446
+ appParams: s,
447
+ hasProvider: r
448
+ }, t);
449
+ }
450
+ function G(e, t, n, o) {
451
+ n && n.disconnect();
452
+ const r = n || new ee(e, t);
453
+ return o && r.onConnect(o), r;
454
+ }
455
+ const I = "--dynamicHeight", $e = 0;
456
+ function Ge(e, t, n, o) {
457
+ return t.contentWindow ? [p.listenToMessageFromWindow(window, t.contentWindow, h.UPDATE_HEIGHT, (r) => {
458
+ const i = `${(r?.height ?? 0) + $e}px`;
442
459
  e.style.setProperty(I, i), o(i);
443
- }, n), p.listenToMessageFromWindow(window, t.contentWindow, w.SET_FULL_HEIGHT, () => {
460
+ }, n), p.listenToMessageFromWindow(window, t.contentWindow, h.SET_FULL_HEIGHT, () => {
444
461
  e.style.setProperty(I, "100dvh"), o("100dvh");
445
462
  }, n)] : [];
446
463
  }
447
- const Ve = {
464
+ const je = {
448
465
  [m.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
449
466
  [m.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
450
467
  [m.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
451
468
  [m.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
452
469
  [m.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
453
470
  };
454
- function Me(e, t) {
455
- return Ve[e.event](e.payload, t);
471
+ function Ke(e, t) {
472
+ return je[e.event](e.payload, t);
456
473
  }
457
- function $e(e, t, n) {
458
- return p.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
474
+ function Ye(e, t, n) {
475
+ return p.listenToMessageFromWindow(window, e, h.PROCESS_HOOK, async (o) => {
459
476
  let r = !1;
460
477
  try {
461
- r = await Me(o, n);
478
+ r = await Ke(o, n);
462
479
  } catch {
463
480
  }
464
481
  p.postMessageToWindow(e, A.HOOK_RESULT, {
@@ -467,46 +484,46 @@ function $e(e, t, n) {
467
484
  }, t);
468
485
  }, t);
469
486
  }
470
- const Ge = Object.values(W);
471
- function Je(e, t, n) {
472
- if (y(e)) {
487
+ const Qe = Object.values(W);
488
+ function T(e) {
489
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => Qe.includes(t));
490
+ }
491
+ function tt(e, t, n) {
492
+ if (T(e)) {
473
493
  const o = e[n];
474
- return T(o) ? o[t] : o;
494
+ return y(o) ? o[t] : o;
475
495
  }
476
- if (T(e)) {
496
+ if (y(e)) {
477
497
  const o = e[t];
478
- return y(o) ? o[n] : o;
498
+ return T(o) ? o[n] : o;
479
499
  }
480
500
  return e;
481
501
  }
502
+ const ze = /^\d+$/;
482
503
  function y(e) {
483
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => Ge.includes(t));
484
- }
485
- const je = /^\d+$/;
486
- function T(e) {
487
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => je.test(t));
504
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => ze.test(t));
488
505
  }
489
- function Ze(e) {
490
- return y(e) ? Object.values(e).flatMap((t) => T(t) ? Object.values(t) : [t]) : T(e) ? Object.values(e).flatMap((t) => y(t) ? Object.values(t) : [t]) : [e];
506
+ function nt(e) {
507
+ return T(e) ? Object.values(e).flatMap((t) => y(t) ? Object.values(t) : [t]) : y(e) ? Object.values(e).flatMap((t) => T(t) ? Object.values(t) : [t]) : [e];
491
508
  }
492
509
  export {
493
- ge as SHOULD_THROW_IF_INVALID_URL,
510
+ Oe as SHOULD_THROW_IF_INVALID_URL,
494
511
  W as TradeType,
495
- Qe as WIDGET_CONTAINER_ID,
496
- le as WIDGET_IFRAME_ALLOW,
497
- re as WIDGET_IFRAME_ID,
498
- ae as WIDGET_IFRAME_REFERRER_POLICY,
499
- se as WIDGET_IFRAME_SANDBOX,
500
- ze as WIDGET_PALETTE_COLORS,
512
+ Ze as WIDGET_CONTAINER_ID,
513
+ ue as WIDGET_IFRAME_ALLOW,
514
+ ae as WIDGET_IFRAME_ID,
515
+ ce as WIDGET_IFRAME_REFERRER_POLICY,
516
+ le as WIDGET_IFRAME_SANDBOX,
517
+ qe as WIDGET_PALETTE_COLORS,
501
518
  m as WidgetHookEvents,
502
- w as WidgetMethodsEmit,
519
+ h as WidgetMethodsEmit,
503
520
  A as WidgetMethodsListen,
504
- Xe as createCowSwapWidget,
505
- G as isCowSwapWidgetPalette,
506
- T as isPerNetworkConfig,
507
- y as isPerTradeTypeConfig,
508
- Je as resolveFlexibleConfig,
509
- Ze as resolveFlexibleConfigValues,
510
- _e as sanitizeWidgetBaseUrl,
521
+ et as createCowSwapWidget,
522
+ K as isCowSwapWidgetPalette,
523
+ y as isPerNetworkConfig,
524
+ T as isPerTradeTypeConfig,
525
+ tt as resolveFlexibleConfig,
526
+ nt as resolveFlexibleConfigValues,
527
+ Re as sanitizeWidgetBaseUrl,
511
528
  p as widgetIframeTransport
512
529
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "4.4.1",
3
+ "version": "4.4.3",
4
4
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your website.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,9 +15,9 @@
15
15
  "access": "public"
16
16
  },
17
17
  "dependencies": {
18
- "@cowprotocol/cow-sdk": "9.2.2",
19
- "@cowprotocol/events": "^4.7.1",
20
- "@cowprotocol/iframe-transport": "^2.3.2"
18
+ "@cowprotocol/cow-sdk": "9.2.5",
19
+ "@cowprotocol/events": "^4.8.1",
20
+ "@cowprotocol/iframe-transport": "^2.3.3"
21
21
  },
22
22
  "devDependencies": {
23
23
  "csstype": "3.1.3"
package/types.d.ts CHANGED
@@ -3,9 +3,69 @@ import { CowWidgetEventListeners, CowWidgetEventPayloadMap, CowWidgetEvents, OnT
3
3
  import type * as CSS from 'csstype';
4
4
  export type { SupportedChainId } from '@cowprotocol/cow-sdk';
5
5
  export type { OnTradeParamsPayload } from '@cowprotocol/events';
6
- export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
7
- export type PerNetworkConfig<T> = Partial<Record<SupportedChainId, T>>;
6
+ export type CowSwapTheme = 'dark' | 'light';
7
+ export interface CowSwapWidgetProps {
8
+ params: CowSwapWidgetParams;
9
+ provider?: EthereumProvider;
10
+ listeners?: CowWidgetEventListeners;
11
+ onReady?(): void;
12
+ onLoadingError?(): void;
13
+ enableSafeSdkBridge?: boolean;
14
+ }
15
+ export interface EthereumProvider {
16
+ /**
17
+ * Subscribes to Ethereum-related events.
18
+ * @param event - The event to subscribe to.
19
+ * @param args - Arguments for the event.
20
+ */
21
+ on(event: string, args: unknown): void;
22
+ /**
23
+ * Sends a JSON-RPC request to the Ethereum provider and returns the response.
24
+ * @param params - JSON-RPC request parameters.
25
+ * @returns A promise that resolves with the response.
26
+ */
27
+ request<T>(params: JsonRpcRequest): Promise<T>;
28
+ }
8
29
  export type FlexibleConfig<T> = T | PerNetworkConfig<T> | PerTradeTypeConfig<T> | PerTradeTypeConfig<PerNetworkConfig<T>> | PerNetworkConfig<PerTradeTypeConfig<T>>;
30
+ export type ForcedOrderDeadline = FlexibleConfig<number>;
31
+ export interface JsonRpcRequest {
32
+ id: number;
33
+ method: string;
34
+ params: unknown[];
35
+ }
36
+ export interface OnApprovalPayload {
37
+ chainId: SupportedChainId;
38
+ sellToken: TokenInfo;
39
+ sellAmount: string;
40
+ walletAddress: string;
41
+ spenderAddress: string;
42
+ }
43
+ /**
44
+ * The partner fee
45
+ */
46
+ export interface PartnerFee {
47
+ /**
48
+ * The fee in basis points (BPS). One basis point is equivalent to 0.01% (1/100th of a percent)
49
+ */
50
+ bps: FlexibleConfig<number>;
51
+ /**
52
+ * The Ethereum address of the partner to receive the fee.
53
+ */
54
+ recipient: FlexibleConfig<string>;
55
+ }
56
+ export type PerNetworkConfig<T> = Partial<Record<SupportedChainId, T>>;
57
+ export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
58
+ /**
59
+ * ERC-20 token information
60
+ */
61
+ export type TokenInfo = {
62
+ chainId: number;
63
+ address: string;
64
+ name: string;
65
+ decimals: number;
66
+ symbol: string;
67
+ logoURI?: string;
68
+ };
9
69
  /**
10
70
  * A single forbidden sell→buy token combination for the widget.
11
71
  *
@@ -39,6 +99,24 @@ export type TokenPairConstraint = {
39
99
  chainId: SupportedChainId;
40
100
  };
41
101
  };
102
+ export type WidgetHookResult = Promise<boolean> | boolean;
103
+ export declare enum TradeType {
104
+ SWAP = "swap",
105
+ LIMIT = "limit",
106
+ /**
107
+ * Currently it means only TWAP orders.
108
+ * But in the future it can be extended to support other order types.
109
+ */
110
+ ADVANCED = "advanced",
111
+ YIELD = "yield"
112
+ }
113
+ export declare enum WidgetHookEvents {
114
+ ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL",
115
+ ON_BEFORE_TRADE = "ON_BEFORE_TRADE",
116
+ ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP",
117
+ ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL",
118
+ ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL"
119
+ }
42
120
  export declare enum WidgetMethodsEmit {
43
121
  ACTIVATE = "ACTIVATE",
44
122
  READY = "READY",
@@ -56,49 +134,6 @@ export declare enum WidgetMethodsListen {
56
134
  PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT",
57
135
  HOOK_RESULT = "HOOK_RESULT"
58
136
  }
59
- export declare enum WidgetHookEvents {
60
- ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL",
61
- ON_BEFORE_TRADE = "ON_BEFORE_TRADE",
62
- ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP",
63
- ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL",
64
- ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL"
65
- }
66
- export type WidgetHookResult = Promise<boolean> | boolean;
67
- export interface OnApprovalPayload {
68
- chainId: SupportedChainId;
69
- sellToken: TokenInfo;
70
- sellAmount: string;
71
- walletAddress: string;
72
- spenderAddress: string;
73
- }
74
- export interface CowSwapWidgetProps {
75
- params: CowSwapWidgetParams;
76
- provider?: EthereumProvider;
77
- listeners?: CowWidgetEventListeners;
78
- onReady?(): void;
79
- onLoadingError?(): void;
80
- enableSafeSdkBridge?: boolean;
81
- }
82
- export interface JsonRpcRequest {
83
- id: number;
84
- method: string;
85
- params: unknown[];
86
- }
87
- export interface EthereumProvider {
88
- /**
89
- * Subscribes to Ethereum-related events.
90
- * @param event - The event to subscribe to.
91
- * @param args - Arguments for the event.
92
- */
93
- on(event: string, args: unknown): void;
94
- /**
95
- * Sends a JSON-RPC request to the Ethereum provider and returns the response.
96
- * @param params - JSON-RPC request parameters.
97
- * @returns A promise that resolves with the response.
98
- */
99
- request<T>(params: JsonRpcRequest): Promise<T>;
100
- }
101
- export type CowSwapTheme = 'dark' | 'light';
102
137
  /**
103
138
  *Trade asset parameters, for example:
104
139
  * { asset: 'WBTC', amount: 12 }
@@ -114,46 +149,23 @@ interface TradeAsset {
114
149
  */
115
150
  amount?: string;
116
151
  }
117
- export type ForcedOrderDeadline = FlexibleConfig<number>;
118
- export declare enum TradeType {
119
- SWAP = "swap",
120
- LIMIT = "limit",
121
- /**
122
- * Currently it means only TWAP orders.
123
- * But in the future it can be extended to support other order types.
124
- */
125
- ADVANCED = "advanced",
126
- YIELD = "yield"
152
+ export declare const WIDGET_PALETTE_COLORS: readonly ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"];
153
+ export interface BaseJsonRpcResponseMessage {
154
+ id: number;
155
+ jsonrpc: '2.0';
127
156
  }
128
- /**
129
- * The partner fee
130
- */
131
- export interface PartnerFee {
132
- /**
133
- * The fee in basis points (BPS). One basis point is equivalent to 0.01% (1/100th of a percent)
134
- */
135
- bps: FlexibleConfig<number>;
157
+ export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks' | 'rootStyle'>;
158
+ export interface CowSwapWidgetContent {
159
+ feeLabel?: string;
160
+ feeTooltipMarkdown?: string;
161
+ }
162
+ export interface CowSwapWidgetImages {
136
163
  /**
137
- * The Ethereum address of the partner to receive the fee.
164
+ * The image to display when the orders table is empty (no orders yet). It defaults to "Yoga CoW" image.
165
+ * Alternatively, you can use a URL to a custom image file, or set to null to disable the image.
138
166
  */
139
- recipient: FlexibleConfig<string>;
167
+ emptyOrders?: string | null;
140
168
  }
141
- /**
142
- * ERC-20 token information
143
- */
144
- export type TokenInfo = {
145
- chainId: number;
146
- address: string;
147
- name: string;
148
- decimals: number;
149
- symbol: string;
150
- logoURI?: string;
151
- };
152
- export declare const WIDGET_PALETTE_COLORS: readonly ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"];
153
- export type CowSwapWidgetPaletteColors = (typeof WIDGET_PALETTE_COLORS)[number];
154
- export type CowSwapWidgetPaletteParams = {
155
- [K in CowSwapWidgetPaletteColors]: string;
156
- };
157
169
  export type CowSwapWidgetPalette = {
158
170
  baseTheme: CowSwapTheme;
159
171
  /**
@@ -164,43 +176,10 @@ export type CowSwapWidgetPalette = {
164
176
  */
165
177
  boxShadow?: string;
166
178
  } & CowSwapWidgetPaletteParams;
167
- export interface CowSwapWidgetSounds {
168
- /**
169
- * The sound to play when the order is executed. Defaults to world wide famous CoW Swap moooooooooo!
170
- * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
171
- */
172
- postOrder?: string | null;
173
- /**
174
- * The sound to play when the order is executed. Defaults to world wide famous CoW Swap happy moooooooooo!
175
- * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
176
- */
177
- orderExecuted?: string | null;
178
- /**
179
- * The sound to play when the order is executed. Defaults to world wide famous CoW Swap unhappy moooooooooo!
180
- * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
181
- */
182
- orderError?: string | null;
183
- }
184
- export interface CowSwapWidgetImages {
185
- /**
186
- * The image to display when the orders table is empty (no orders yet). It defaults to "Yoga CoW" image.
187
- * Alternatively, you can use a URL to a custom image file, or set to null to disable the image.
188
- */
189
- emptyOrders?: string | null;
190
- }
191
- export interface CowSwapWidgetContent {
192
- feeLabel?: string;
193
- feeTooltipMarkdown?: string;
194
- }
195
- export interface SlippageConfig {
196
- /** Minimum slippage in basis points (e.g., 10 = 0.1%) */
197
- min?: number;
198
- /** Maximum slippage in basis points (e.g., 5000 = 50%) - 5000 is max value for dApp */
199
- max?: number;
200
- /** Default slippage value in basis points (e.g., 50 = 0.5%) - min <= defaultValue <= max */
201
- defaultValue?: number;
202
- }
203
- export type FlexibleSlippageConfig = FlexibleConfig<SlippageConfig>;
179
+ export type CowSwapWidgetPaletteColors = (typeof WIDGET_PALETTE_COLORS)[number];
180
+ export type CowSwapWidgetPaletteParams = {
181
+ [K in CowSwapWidgetPaletteColors]: string;
182
+ };
204
183
  export interface CowSwapWidgetParams {
205
184
  /**
206
185
  * The unique identifier of the widget consumer.
@@ -394,7 +373,9 @@ export interface CowSwapWidgetParams {
394
373
  */
395
374
  disableToastMessages?: boolean;
396
375
  /**
397
- * When `true`, the host page will not use `window.open` to open links requested by the widget.
376
+ * When `true`, the host page will not use `window.open` to open links requested by the widget,
377
+ * and the widget iframe sandbox will not allow direct popups.
378
+ * Requires `standaloneMode: false`.
398
379
  * Defaults to `false`.
399
380
  */
400
381
  disableWindowOpen?: boolean;
@@ -467,27 +448,69 @@ export interface CowSwapWidgetParams {
467
448
  onBeforeOrdersCancel(payload: EnrichedOrder[]): WidgetHookResult;
468
449
  }>;
469
450
  }
470
- export interface WidgetMethodsEmitPayloadMap {
471
- [WidgetMethodsEmit.ACTIVATE]: void;
472
- [WidgetMethodsEmit.READY]: void;
473
- [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowWidgetEvents>;
474
- [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
475
- [WidgetMethodsEmit.SET_FULL_HEIGHT]: void;
476
- [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
477
- [WidgetMethodsEmit.INTERCEPT_WINDOW_OPEN]: WindowOpenPayload;
478
- [WidgetMethodsEmit.PROCESS_HOOK]: WidgetHookPayload<WidgetHookEvents>;
451
+ export interface CowSwapWidgetSounds {
452
+ /**
453
+ * The sound to play when the order is executed. Defaults to world wide famous CoW Swap moooooooooo!
454
+ * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
455
+ */
456
+ postOrder?: string | null;
457
+ /**
458
+ * The sound to play when the order is executed. Defaults to world wide famous CoW Swap happy moooooooooo!
459
+ * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
460
+ */
461
+ orderExecuted?: string | null;
462
+ /**
463
+ * The sound to play when the order is executed. Defaults to world wide famous CoW Swap unhappy moooooooooo!
464
+ * Alternatively, you can use a URL to a custom sound file, or set to null to disable the sound.
465
+ */
466
+ orderError?: string | null;
479
467
  }
480
- export interface WidgetMethodsListenPayloadMap {
481
- [WidgetMethodsListen.UPDATE_APP_DATA]: UpdateAppDataPayload;
482
- [WidgetMethodsListen.UPDATE_PARAMS]: UpdateParamsPayload;
483
- [WidgetMethodsListen.PROVIDER_RPC_RESPONSE]: ProviderRpcResponsePayload;
484
- [WidgetMethodsListen.PROVIDER_ON_EVENT]: ProviderOnEventPayload;
485
- [WidgetMethodsListen.HOOK_RESULT]: WidgetHookResultPayload;
468
+ export interface EmitCowEventPayload<T extends CowWidgetEvents> {
469
+ event: T;
470
+ payload: CowWidgetEventPayloadMap[T];
471
+ }
472
+ export type FlexibleSlippageConfig = FlexibleConfig<SlippageConfig>;
473
+ export interface JsonRpcError<TData = unknown> {
474
+ code: number;
475
+ message: string;
476
+ data?: TData;
477
+ }
478
+ export interface JsonRpcErrorResponseMessage<TErrorData = unknown> extends BaseJsonRpcResponseMessage {
479
+ error: JsonRpcError<TErrorData>;
480
+ }
481
+ export interface JsonRpcRequestMessage {
482
+ jsonrpc: '2.0';
483
+ id?: number;
484
+ method: string;
485
+ params: unknown[];
486
+ }
487
+ export type JsonRpcResponse = JsonRpcRequestMessage | JsonRpcErrorResponseMessage | JsonRpcSucessfulResponseMessage;
488
+ export interface JsonRpcSucessfulResponseMessage<TResult = unknown> extends BaseJsonRpcResponseMessage {
489
+ result: TResult;
490
+ }
491
+ export interface ProviderOnEventPayload {
492
+ event: string;
493
+ params: unknown;
494
+ }
495
+ export interface ProviderRpcRequestPayload {
496
+ rpcRequest: JsonRpcRequestMessage;
497
+ }
498
+ export type ProviderRpcResponsePayload = {
499
+ rpcResponse: JsonRpcResponse;
500
+ };
501
+ export interface SlippageConfig {
502
+ /** Minimum slippage in basis points (e.g., 10 = 0.1%) */
503
+ min?: number;
504
+ /** Maximum slippage in basis points (e.g., 5000 = 50%) - 5000 is max value for dApp */
505
+ max?: number;
506
+ /** Default slippage value in basis points (e.g., 50 = 0.5%) - min <= defaultValue <= max */
507
+ defaultValue?: number;
508
+ }
509
+ export interface UpdateAppDataPayload {
510
+ metaData?: {
511
+ appCode: string;
512
+ };
486
513
  }
487
- export type WidgetEventsPayloadMap = WidgetMethodsEmitPayloadMap & WidgetMethodsListenPayloadMap;
488
- export type WidgetMethodsEmitPayloads = WidgetMethodsEmitPayloadMap[WidgetMethodsEmit];
489
- export type WidgetMethodsListenPayloads = WidgetMethodsListenPayloadMap[WidgetMethodsListen];
490
- export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks' | 'rootStyle'>;
491
514
  export interface UpdateParamsPayload {
492
515
  urlParams: {
493
516
  pathname: string;
@@ -496,24 +519,16 @@ export interface UpdateParamsPayload {
496
519
  appParams: CowSwapWidgetAppParams;
497
520
  hasProvider: boolean;
498
521
  }
499
- export interface UpdateAppDataPayload {
500
- metaData?: {
501
- appCode: string;
502
- };
503
- }
504
522
  export interface UpdateWidgetHeightPayload {
505
523
  height?: number;
506
524
  }
525
+ export type WidgetEventsPayloadMap = WidgetMethodsEmitPayloadMap & WidgetMethodsListenPayloadMap;
507
526
  export type WidgetHookId = string;
508
527
  export interface WidgetHookPayload<T extends WidgetHookEvents> {
509
528
  id: WidgetHookId;
510
529
  event: T;
511
530
  payload: WidgetHookPayloadMap[T];
512
531
  }
513
- export interface WidgetHookResultPayload {
514
- id: WidgetHookId;
515
- result: boolean;
516
- }
517
532
  export interface WidgetHookPayloadMap {
518
533
  [WidgetHookEvents.ON_BEFORE_APPROVAL]: OnApprovalPayload;
519
534
  [WidgetHookEvents.ON_BEFORE_TRADE]: OnTradeParamsPayload;
@@ -521,50 +536,37 @@ export interface WidgetHookPayloadMap {
521
536
  [WidgetHookEvents.ON_BEFORE_ORDER_CANCEL]: EnrichedOrder;
522
537
  [WidgetHookEvents.ON_BEFORE_ORDERS_CANCEL]: EnrichedOrder[];
523
538
  }
524
- export interface EmitCowEventPayload<T extends CowWidgetEvents> {
525
- event: T;
526
- payload: CowWidgetEventPayloadMap[T];
539
+ export interface WidgetHookResultPayload {
540
+ id: WidgetHookId;
541
+ result: boolean;
527
542
  }
543
+ export type WidgetMethodHandler<T extends WidgetMethodsEmit> = (payload: WidgetMethodsEmitPayloadMap[T]) => void;
528
544
  export type WidgetMethodsEmitListener<T extends WidgetMethodsEmit> = T extends WidgetMethodsEmit ? {
529
545
  event: T;
530
546
  handler: WidgetMethodHandler<T>;
531
547
  } : never;
532
- export type WidgetMethodHandler<T extends WidgetMethodsEmit> = (payload: WidgetMethodsEmitPayloadMap[T]) => void;
533
- export interface ProviderRpcRequestPayload {
534
- rpcRequest: JsonRpcRequestMessage;
548
+ export interface WidgetMethodsEmitPayloadMap {
549
+ [WidgetMethodsEmit.ACTIVATE]: void;
550
+ [WidgetMethodsEmit.READY]: void;
551
+ [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowWidgetEvents>;
552
+ [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
553
+ [WidgetMethodsEmit.SET_FULL_HEIGHT]: void;
554
+ [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
555
+ [WidgetMethodsEmit.INTERCEPT_WINDOW_OPEN]: WindowOpenPayload;
556
+ [WidgetMethodsEmit.PROCESS_HOOK]: WidgetHookPayload<WidgetHookEvents>;
535
557
  }
558
+ export type WidgetMethodsEmitPayloads = WidgetMethodsEmitPayloadMap[WidgetMethodsEmit];
559
+ export interface WidgetMethodsListenPayloadMap {
560
+ [WidgetMethodsListen.UPDATE_APP_DATA]: UpdateAppDataPayload;
561
+ [WidgetMethodsListen.UPDATE_PARAMS]: UpdateParamsPayload;
562
+ [WidgetMethodsListen.PROVIDER_RPC_RESPONSE]: ProviderRpcResponsePayload;
563
+ [WidgetMethodsListen.PROVIDER_ON_EVENT]: ProviderOnEventPayload;
564
+ [WidgetMethodsListen.HOOK_RESULT]: WidgetHookResultPayload;
565
+ }
566
+ export type WidgetMethodsListenPayloads = WidgetMethodsListenPayloadMap[WidgetMethodsListen];
567
+ export type WindowListener = (event: MessageEvent<unknown>) => void;
536
568
  export interface WindowOpenPayload {
537
569
  href: string | URL;
538
570
  target: string;
539
571
  rel: string;
540
572
  }
541
- export interface JsonRpcRequestMessage {
542
- jsonrpc: '2.0';
543
- id?: number;
544
- method: string;
545
- params: unknown[];
546
- }
547
- export interface BaseJsonRpcResponseMessage {
548
- id: number;
549
- jsonrpc: '2.0';
550
- }
551
- export interface JsonRpcSucessfulResponseMessage<TResult = unknown> extends BaseJsonRpcResponseMessage {
552
- result: TResult;
553
- }
554
- export interface JsonRpcError<TData = unknown> {
555
- code: number;
556
- message: string;
557
- data?: TData;
558
- }
559
- export interface JsonRpcErrorResponseMessage<TErrorData = unknown> extends BaseJsonRpcResponseMessage {
560
- error: JsonRpcError<TErrorData>;
561
- }
562
- export type ProviderRpcResponsePayload = {
563
- rpcResponse: JsonRpcResponse;
564
- };
565
- export type JsonRpcResponse = JsonRpcRequestMessage | JsonRpcErrorResponseMessage | JsonRpcSucessfulResponseMessage;
566
- export interface ProviderOnEventPayload {
567
- event: string;
568
- params: unknown;
569
- }
570
- export type WindowListener = (event: MessageEvent<unknown>) => void;
package/urlUtils.d.ts CHANGED
@@ -4,6 +4,9 @@ import { CowSwapWidgetParams } from './types';
4
4
  * When `false`, invalid values are reported with `console.error` and the iframe falls back to the production host.
5
5
  */
6
6
  export declare const SHOULD_THROW_IF_INVALID_URL = false;
7
+ export declare function buildWidgetPath(params: Partial<CowSwapWidgetParams>): string;
8
+ export declare function buildWidgetUrl(params: Partial<CowSwapWidgetParams>): string;
9
+ export declare function buildWidgetUrlQuery(params: Partial<CowSwapWidgetParams>): URLSearchParams;
7
10
  /**
8
11
  * Normalizes `baseUrl` for the widget iframe `src` and rejects unsafe values.
9
12
  * - Omits or blank `baseUrl` → production default (https://swap.cow.fi).
@@ -13,6 +16,3 @@ export declare const SHOULD_THROW_IF_INVALID_URL = false;
13
16
  * @throws {Error} When validation fails and `throwIfInvalid` is true (see {@link SHOULD_THROW_IF_INVALID_URL}).
14
17
  */
15
18
  export declare function sanitizeWidgetBaseUrl(baseUrl: string | undefined, throwIfInvalid?: boolean): string;
16
- export declare function buildWidgetUrl(params: Partial<CowSwapWidgetParams>): string;
17
- export declare function buildWidgetPath(params: Partial<CowSwapWidgetParams>): string;
18
- export declare function buildWidgetUrlQuery(params: Partial<CowSwapWidgetParams>): URLSearchParams;