@imtbl/sdk 1.46.9 → 1.46.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/blockchain_data.js +2 -2
  2. package/dist/browser/checkout/{BridgeWidget-D7dpUxo2.js → BridgeWidget-DIW_vLRY.js} +1 -1
  3. package/dist/browser/checkout/{CheckoutWidget-E3RR6VfY.js → CheckoutWidget-DdTKHYXH.js} +1 -1
  4. package/dist/browser/checkout/{OnRampWidget-CerZQH2n.js → OnRampWidget-Db_xi_3K.js} +2 -2
  5. package/dist/browser/checkout/SaleWidget-2I8K308o.js +1 -0
  6. package/dist/browser/checkout/{SpendingCapHero-A_5Bob8g.js → SpendingCapHero-BS31EBOB.js} +1 -1
  7. package/dist/browser/checkout/SwapWidget-DSR67jm4.js +1 -0
  8. package/dist/browser/checkout/TopUpView-Dj1Nel9E.js +1 -0
  9. package/dist/browser/checkout/WalletWidget-BujJRw0E.js +1 -0
  10. package/dist/browser/checkout/{auto-track-DvVPdNci.js → auto-track-AYNcFmSy.js} +1 -1
  11. package/dist/browser/checkout/balance-BJfSSMBq.js +1 -0
  12. package/dist/browser/checkout/{index-DfxkQlZi.js → index-BEeO7J55.js} +1 -1
  13. package/dist/browser/checkout/{index-D_ciolhG.js → index-Bz2frPdM.js} +1 -1
  14. package/dist/browser/checkout/{index-BS9il7eh.js → index-CA8ZBHRb.js} +2 -2
  15. package/dist/browser/checkout/index-CTYTnSCr.js +1 -0
  16. package/dist/browser/checkout/{index-B5VDF_xo.js → index-CVJEvOay.js} +1 -1
  17. package/dist/browser/checkout/{index-CwPkiCBS.js → index-DMhvD0dn.js} +1 -1
  18. package/dist/browser/checkout/{index-Cc4FTzVC.js → index-DqmCLC0x.js} +1 -1
  19. package/dist/browser/checkout/{index-DfWmQES2.js → index-fkmlapIn.js} +1 -1
  20. package/dist/browser/checkout/{index.umd-B-vLc2Nx.js → index.umd-DwrOuGmI.js} +1 -1
  21. package/dist/browser/checkout/{retry-V19x49_Z.js → retry-BAll91VH.js} +1 -1
  22. package/dist/browser/checkout/sdk.js +4 -4
  23. package/dist/browser/checkout/widgets-esm.js +1 -1
  24. package/dist/browser/checkout/widgets.js +1 -1
  25. package/dist/checkout.js +4 -4
  26. package/dist/config.js +1 -1
  27. package/dist/index.browser.js +4 -4
  28. package/dist/index.browser.js.map +1 -1
  29. package/dist/index.cjs +7 -7
  30. package/dist/index.js +7 -7
  31. package/dist/minting_backend.js +2 -2
  32. package/dist/orderbook.js +1 -1
  33. package/dist/passport.js +4 -4
  34. package/dist/webhook.js +1 -1
  35. package/dist/x.js +3 -3
  36. package/package.json +1 -1
  37. package/dist/browser/checkout/SaleWidget-CQtcTHB5.js +0 -1
  38. package/dist/browser/checkout/SwapWidget-66EIB3f0.js +0 -1
  39. package/dist/browser/checkout/TopUpView-DDi51gWy.js +0 -1
  40. package/dist/browser/checkout/WalletWidget-Ccaiv336.js +0 -1
  41. package/dist/browser/checkout/balance-DjY7Ic2J.js +0 -1
  42. package/dist/browser/checkout/index-Cltm2W6N.js +0 -1
package/dist/index.cjs CHANGED
@@ -216,7 +216,7 @@ const flattenProperties$1 = (properties) => {
216
216
  };
217
217
 
218
218
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
219
- const SDK_VERSION$1 = '1.46.9';
219
+ const SDK_VERSION$1 = '1.46.10';
220
220
  const getFrameParentDomain$1 = () => {
221
221
  if (isNode$1()) {
222
222
  return '';
@@ -14501,7 +14501,7 @@ class MultiRollupApiClients {
14501
14501
  }
14502
14502
 
14503
14503
  // eslint-disable-next-line @typescript-eslint/naming-convention
14504
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
14504
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
14505
14505
  const createConfig$1 = ({ basePath, headers, }) => {
14506
14506
  if (!basePath.trim()) {
14507
14507
  throw Error('basePath can not be empty');
@@ -14573,7 +14573,7 @@ class APIError extends Error {
14573
14573
 
14574
14574
  /* eslint-disable implicit-arrow-linebreak */
14575
14575
  const defaultHeaders$1 = {
14576
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.9',
14576
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.10',
14577
14577
  };
14578
14578
  /**
14579
14579
  * createAPIConfiguration to create a custom Configuration
@@ -15047,7 +15047,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
15047
15047
  /* eslint-disable @typescript-eslint/naming-convention */
15048
15048
  class ApiConfiguration extends index$2.Configuration {
15049
15049
  }
15050
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
15050
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
15051
15051
  /**
15052
15052
  * @dev use createImmutableXConfiguration instead
15053
15053
  */
@@ -15088,7 +15088,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
15088
15088
  coreContractAddress,
15089
15089
  registrationContractAddress,
15090
15090
  registrationV4ContractAddress,
15091
- sdkVersion: 'ts-immutable-sdk-1.46.9',
15091
+ sdkVersion: 'ts-immutable-sdk-1.46.10',
15092
15092
  baseConfig,
15093
15093
  });
15094
15094
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -52887,7 +52887,7 @@ const flattenProperties = (properties) => {
52887
52887
  };
52888
52888
 
52889
52889
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
52890
- const SDK_VERSION = '1.46.9';
52890
+ const SDK_VERSION = '1.46.10';
52891
52891
  const getFrameParentDomain = () => {
52892
52892
  if (isNode()) {
52893
52893
  return '';
@@ -58232,7 +58232,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
58232
58232
  maxPriorityFeePerGas: ethers.BigNumber.from(10e9),
58233
58233
  };
58234
58234
 
58235
- const SDK_VERSION_MARKER = '1.46.9';
58235
+ const SDK_VERSION_MARKER = '1.46.10';
58236
58236
  // This SDK version is replaced by the `yarn build` command ran on the root level
58237
58237
  const globalPackageVersion = () => SDK_VERSION_MARKER;
58238
58238
 
package/dist/index.js CHANGED
@@ -193,7 +193,7 @@ const flattenProperties$1 = (properties) => {
193
193
  };
194
194
 
195
195
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
196
- const SDK_VERSION$1 = '1.46.9';
196
+ const SDK_VERSION$1 = '1.46.10';
197
197
  const getFrameParentDomain$1 = () => {
198
198
  if (isNode$1()) {
199
199
  return '';
@@ -14478,7 +14478,7 @@ class MultiRollupApiClients {
14478
14478
  }
14479
14479
 
14480
14480
  // eslint-disable-next-line @typescript-eslint/naming-convention
14481
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
14481
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
14482
14482
  const createConfig$1 = ({ basePath, headers, }) => {
14483
14483
  if (!basePath.trim()) {
14484
14484
  throw Error('basePath can not be empty');
@@ -14550,7 +14550,7 @@ class APIError extends Error {
14550
14550
 
14551
14551
  /* eslint-disable implicit-arrow-linebreak */
14552
14552
  const defaultHeaders$1 = {
14553
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.9',
14553
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.10',
14554
14554
  };
14555
14555
  /**
14556
14556
  * createAPIConfiguration to create a custom Configuration
@@ -15024,7 +15024,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
15024
15024
  /* eslint-disable @typescript-eslint/naming-convention */
15025
15025
  class ApiConfiguration extends index$2.Configuration {
15026
15026
  }
15027
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
15027
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
15028
15028
  /**
15029
15029
  * @dev use createImmutableXConfiguration instead
15030
15030
  */
@@ -15065,7 +15065,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
15065
15065
  coreContractAddress,
15066
15066
  registrationContractAddress,
15067
15067
  registrationV4ContractAddress,
15068
- sdkVersion: 'ts-immutable-sdk-1.46.9',
15068
+ sdkVersion: 'ts-immutable-sdk-1.46.10',
15069
15069
  baseConfig,
15070
15070
  });
15071
15071
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -52864,7 +52864,7 @@ const flattenProperties = (properties) => {
52864
52864
  };
52865
52865
 
52866
52866
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
52867
- const SDK_VERSION = '1.46.9';
52867
+ const SDK_VERSION = '1.46.10';
52868
52868
  const getFrameParentDomain = () => {
52869
52869
  if (isNode()) {
52870
52870
  return '';
@@ -58209,7 +58209,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
58209
58209
  maxPriorityFeePerGas: BigNumber$1.from(10e9),
58210
58210
  };
58211
58211
 
58212
- const SDK_VERSION_MARKER = '1.46.9';
58212
+ const SDK_VERSION_MARKER = '1.46.10';
58213
58213
  // This SDK version is replaced by the `yarn build` command ran on the root level
58214
58214
  const globalPackageVersion = () => SDK_VERSION_MARKER;
58215
58215
 
@@ -5522,7 +5522,7 @@ const flattenProperties = (properties) => {
5522
5522
  };
5523
5523
 
5524
5524
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
5525
- const SDK_VERSION = '1.46.9';
5525
+ const SDK_VERSION = '1.46.10';
5526
5526
  const getFrameParentDomain = () => {
5527
5527
  if (isNode()) {
5528
5528
  return '';
@@ -5793,7 +5793,7 @@ class APIError extends Error {
5793
5793
 
5794
5794
  /* eslint-disable implicit-arrow-linebreak */
5795
5795
  const defaultHeaders = {
5796
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.9',
5796
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.46.10',
5797
5797
  };
5798
5798
  /**
5799
5799
  * createAPIConfiguration to create a custom Configuration
package/dist/orderbook.js CHANGED
@@ -149,7 +149,7 @@ const flattenProperties = (properties) => {
149
149
  };
150
150
 
151
151
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
152
- const SDK_VERSION = '1.46.9';
152
+ const SDK_VERSION = '1.46.10';
153
153
  const getFrameParentDomain = () => {
154
154
  if (isNode()) {
155
155
  return '';
package/dist/passport.js CHANGED
@@ -180,7 +180,7 @@ const flattenProperties = (properties) => {
180
180
  };
181
181
 
182
182
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
183
- const SDK_VERSION = '1.46.9';
183
+ const SDK_VERSION = '1.46.10';
184
184
  const getFrameParentDomain = () => {
185
185
  if (isNode()) {
186
186
  return '';
@@ -12059,7 +12059,7 @@ class MultiRollupApiClients {
12059
12059
  }
12060
12060
 
12061
12061
  // eslint-disable-next-line @typescript-eslint/naming-convention
12062
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
12062
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
12063
12063
  const createConfig$1 = ({ basePath, headers, }) => {
12064
12064
  if (!basePath.trim()) {
12065
12065
  throw Error('basePath can not be empty');
@@ -12160,7 +12160,7 @@ const addKeysToHeadersOverride = (baseConfig, overrides) => {
12160
12160
  /* eslint-disable @typescript-eslint/naming-convention */
12161
12161
  class ApiConfiguration extends index$2.Configuration {
12162
12162
  }
12163
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
12163
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
12164
12164
  /**
12165
12165
  * @dev use createImmutableXConfiguration instead
12166
12166
  */
@@ -12201,7 +12201,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
12201
12201
  coreContractAddress,
12202
12202
  registrationContractAddress,
12203
12203
  registrationV4ContractAddress,
12204
- sdkVersion: 'ts-immutable-sdk-1.46.9',
12204
+ sdkVersion: 'ts-immutable-sdk-1.46.10',
12205
12205
  baseConfig,
12206
12206
  });
12207
12207
  const production = ({ baseConfig }) => createImmutableXConfiguration({
package/dist/webhook.js CHANGED
@@ -145,7 +145,7 @@ const flattenProperties = (properties) => {
145
145
  };
146
146
 
147
147
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
148
- const SDK_VERSION = '1.46.9';
148
+ const SDK_VERSION = '1.46.10';
149
149
  const getFrameParentDomain = () => {
150
150
  if (isNode()) {
151
151
  return '';
package/dist/x.js CHANGED
@@ -9019,7 +9019,7 @@ const flattenProperties = (properties) => {
9019
9019
  };
9020
9020
 
9021
9021
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
9022
- const SDK_VERSION = '1.46.9';
9022
+ const SDK_VERSION = '1.46.10';
9023
9023
  const getFrameParentDomain = () => {
9024
9024
  if (isNode()) {
9025
9025
  return '';
@@ -9288,7 +9288,7 @@ const addKeysToHeadersOverride = (baseConfig, overrides) => {
9288
9288
  /* eslint-disable @typescript-eslint/naming-convention */
9289
9289
  class ApiConfiguration extends index$2.Configuration {
9290
9290
  }
9291
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.9' };
9291
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.46.10' };
9292
9292
  /**
9293
9293
  * @dev use createImmutableXConfiguration instead
9294
9294
  */
@@ -9329,7 +9329,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
9329
9329
  coreContractAddress,
9330
9330
  registrationContractAddress,
9331
9331
  registrationV4ContractAddress,
9332
- sdkVersion: 'ts-immutable-sdk-1.46.9',
9332
+ sdkVersion: 'ts-immutable-sdk-1.46.10',
9333
9333
  baseConfig,
9334
9334
  });
9335
9335
  const production = ({ baseConfig }) => createImmutableXConfiguration({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@imtbl/sdk",
3
3
  "description": "Immutable Typescript SDK",
4
- "version": "1.46.9",
4
+ "version": "1.46.10",
5
5
  "author": "Immutable",
6
6
  "browser": "./dist/index.browser.js",
7
7
  "bugs": "https://github.com/immutable/ts-immutable-sdk/issues",
@@ -1 +0,0 @@
1
- import{j as e,_ as t,u as n,r as a,m as r,al as o,am as s,an as i,ao as c,ap as d,k as l,aq as u,a as p,z as E,ar as m,as as T,at as f,V as y,p as C,au as h,U as A,l as g,Y as I,t as v,E as R,av as S,aw as O,ax as b,ay as _,az as w,aA as D,$ as P,n as k,aB as x,aC as N,a3 as M,aD as L,aE as F,aF as U,H as W,aG as B,o as V,d as Y,w as H,M as G,aH as j,aI as $,aJ as X,L as K,a2 as z,aK as q,aL as Z,A as J,aM as Q,aN as ee,a6 as te,a7 as ne,aO as ae,aP as re,aQ as oe,aR as se,aS as ie,aT as ce,G as de,X as le,aU as ue,q as pe,aV as Ee,aW as me,y as Te,x as fe,I as ye,aX as Ce,aj as he,aY as Ae,aZ as ge,a_ as Ie,a$ as ve,b0 as Re,b1 as Se,b2 as Oe,b3 as be,B as _e,b4 as we,ah as De,ai as Pe,b5 as ke}from"./index-BS9il7eh.js";import{u as xe,O as Ne}from"./OnRampWidget-CerZQH2n.js";import{f as Me,u as Le,C as Fe,a as Ue,T as We,b as Be}from"./TopUpView-DDi51gWy.js";import{T as Ve}from"./retry-V19x49_Z.js";import{F as Ye}from"./balance-DjY7Ic2J.js";import He from"./BridgeWidget-D7dpUxo2.js";import Ge from"./SwapWidget-66EIB3f0.js";import"./SpendingCapHero-A_5Bob8g.js";var je=["size","weight","rc","sx","testId","children","domRef","className"];function $e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function Xe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?$e(Object(n),!0).forEach((function(t){l(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$e(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Ke="base.color.text.caption.primary",ze="medium";function qe(l){var u=l.size,p=void 0===u?ze:u,E=l.weight,m=void 0===E?"regular":E,T=l.rc,f=void 0===T?e("span",{}):T,y=l.sx,C=void 0===y?{}:y,h=l.testId,A=l.children,g=l.domRef,I=l.className,v=t(l,je),R=n(),S=a.useMemo((function(){var e,t;return r(s,{c:Ke},o({themeProps:R,size:p,weight:m}),null!==(e=null===(t=R.components)||void 0===t||null===(t=t.Caption)||void 0===t?void 0:t.sxOverride)&&void 0!==e?e:{},C)}),[C,R,p,m]),O=i(S),b=c(p,ze,Object.keys(R.base.text.caption));return d(f,Xe(Xe(Xe(Xe({},v),h?{"data-testid":h}:{}),g?{ref:g}:{}),{},{css:O,children:A,className:"".concat(null!=I?I:""," Caption Caption--").concat(b)}))}qe.displayName="Caption";var Ze,Je,Qe,et,tt,nt,at=["sx","radius"];function rt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function ot(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?rt(Object(n),!0).forEach((function(t){l(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function st(n){var a=n.sx,o=void 0===a?{}:a,s=n.radius,i=void 0===s?"50px":s,c=t(n,at);return e(p,ot(ot({},c),{},{sx:r(u,{brad:"50%",w:i,h:i},o)}))}!function(e){e.PAYMENT_METHODS="PAYMENT_METHODS",e.PAY_WITH_COINS="PAY_WITH_COINS",e.PAY_WITH_CARD="PAY_WITH_CARD",e.ORDER_SUMMARY="ORDER_SUMMARY",e.SALE_SUCCESS="SALE_SUCCESS",e.SALE_FAIL="SALE_FAIL"}(Ze||(Ze={})),function(e){e.INIT="INIT",e.REVIEW_ORDER="REVIEW_ORDER",e.EXECUTE_FUNDING_ROUTE="EXECUTE_FUNDING_ROUTE"}(Je||(Je={})),function(e){e.DEFAULT="DEFAULT_ERROR",e.INVALID_PARAMETERS="INVALID_PARAMETERS",e.TRANSACTION_FAILED="TRANSACTION_FAILED",e.SERVICE_BREAKDOWN="SERVICE_BREAKDOWN",e.PRODUCT_NOT_FOUND="PRODUCT_NOT_FOUND",e.INSUFFICIENT_STOCK="INSUFFICIENT_STOCK",e.TRANSAK_FAILED="TRANSAK_FAILED",e.WALLET_FAILED="WALLET_FAILED",e.WALLET_REJECTED="WALLET_REJECTED",e.WALLET_REJECTED_NO_FUNDS="WALLET_REJECTED_NO_FUNDS",e.WALLET_POPUP_BLOCKED="WALLET_POPUP_BLOCKED",e.FUNDING_ROUTE_EXECUTE_ERROR="FUNDING_ROUTE_EXECUTE_ERROR"}(Qe||(Qe={})),function(e){e.CRYPTO="crypto",e.FIAT="fiat"}(et||(et={})),function(e){e.SUFFICIENT="SUFFICIENT"}(tt||(tt={})),function(e){e.BEFORE="before",e.PENDING="pending",e.AFTER="after"}(nt||(nt={}));const it={[E.SANDBOX]:"https://api.sandbox.immutable.com/v1/primary-sales",[E.PRODUCTION]:"https://api.immutable.com/v1/primary-sales"},ct=e=>e.map((({method:e,hash:t})=>`${e}: ${t}`)).join(" | "),dt=e=>e.split(/[_\s-]+/).map((e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),lt=e=>e.replace(/[^\u0000-\u00FF]/g,""),ut=e=>{if(!e)return"";let t=e.trim().toLowerCase();if(t.startsWith("0x")&&(t=t.slice(2)),!/^[0-9a-f]+$/i.test(t))throw new Error("Invalid hexadecimal input");let n="";for(let e=0;e<t.length;e+=2){const a=parseInt(t.substr(e,2),16);n+=String.fromCharCode(a)}return n},pt=async(e,t)=>{try{const n=t.getSigner(),a=await n.getAddress(),r=e.find((e=>e.methodCall.startsWith("approve")));if(!r||!n||!a)return e;const o=new m(r.tokenAddress,["function allowance(address,address) view returns (uint256)"],n),s=await(n?.call({to:r.tokenAddress,data:o.interface.encodeFunctionData("allowance",[a,r.params.spender])})),i=T.from(s),c=r.params.amount?T.from(r.params.amount):T.from(0);if(i.gte(T.from("0"))&&i.gte(c))return e.filter((e=>e.methodCall!==r.methodCall))}catch{}return e};var Et;!function(e){e.CONTRACT_ADDRESS="contract_address",e.CURRENCY_SYMBOL="currency_symbol"}(Et||(Et={}));const mt=e=>{const{provider:t,items:n,environment:r,environmentId:o,waitFulfillmentSettlements:s}=e,[i,c]=a.useState(void 0),[d,l]=a.useState(void 0),[u,p]=a.useState({done:!1,transactions:[]}),[E,m]=a.useState([]),[T,f]=a.useState(0),[y,C]=a.useState([]),h=()=>p((e=>({...e,done:!0}))),A=()=>p({done:!1,transactions:[]}),g=a.useCallback((async(e,n,a)=>{try{const r=t?.getSigner(),o=await(t?.getGasPrice()),i=await(r?.sendTransaction({to:e,data:n,gasPrice:o,gasLimit:a}));s&&await(i?.wait());const c=i?.hash;if(!c)throw new Error("Transaction hash is undefined");return[c,void 0]}catch(e){const t=`${e?.reason||e?.message||""}`.toLowerCase();let n=Qe.WALLET_FAILED;t.includes("failed")&&t.includes("open confirmation")&&(n=Qe.WALLET_POPUP_BLOCKED),t.includes("rejected")&&t.includes("user")&&(n=Qe.WALLET_REJECTED),t.includes("failed to submit")&&t.includes("highest gas limit")&&(n=Qe.WALLET_REJECTED_NO_FUNDS),(t.includes("status failed")||t.includes("transaction failed"))&&(n=Qe.TRANSACTION_FAILED);const a={type:n,data:{error:e}};return c(a),[void 0,a]}}),[t,s]),I=a.useCallback((async(e,a)=>{try{const s=t?.getSigner(),i={recipient_address:await(s?.getAddress())||"",payment_type:e,currency_filter:Et.CONTRACT_ADDRESS,currency_value:a,products:n.map((e=>({product_id:e.productId,quantity:e.qty})))},d=`${it[r]}/${o}/order/sign`,u=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),{ok:p,status:E}=u;if(!p){const{code:e}=await u.json();let t;switch(E){case 400:t=Qe.SERVICE_BREAKDOWN;break;case 404:t="insufficient_stock"===e?Qe.INSUFFICIENT_STOCK:Qe.PRODUCT_NOT_FOUND;break;case 429:case 500:t=Qe.DEFAULT;break;default:throw new Error("Unknown error")}return void c({type:t})}const T=await u.json(),f=T.order.products.map((e=>e.detail.map((({token_id:e})=>e)))).flat(),y=((e,t)=>{const{order:n,transactions:a}=e;return{order:{currency:{name:n.currency.name,erc20Address:n.currency.erc20_address},products:n.products.map((e=>((e,t,n)=>({productId:e.product_id,image:n?.image||"",qty:n?.qty||1,name:n?.name||"",description:n?.description||"",currency:t,contractType:e.contract_type,collectionAddress:e.collection_address,amount:e.detail.map((({amount:e})=>e)),tokenId:e.detail.map((({token_id:e})=>e))}))(e,n.currency.name,t.find((t=>t.productId===e.product_id))))).reduce(((e,t)=>{const n=e.findIndex((e=>e.name===t.name));return-1===n&&e.push({...t}),n>-1&&(e[n].amount=[...e[n].amount,...t.amount],e[n].tokenId=[...e[n].tokenId,...t.tokenId]),e}),[]),totalAmount:Number(n.total_amount)},transactions:a.map((e=>({tokenAddress:e.contract_address,gasEstimate:e.gas_estimate,methodCall:e.method_call,params:{reference:e.params.reference||"",amount:e.params.amount||0,spender:e.params.spender||""},rawData:e.raw_data}))),transactionId:ut(a.find((e=>e.method_call.startsWith("execute")))?.params.reference||"")}})(T,n);if(m(f),l(y),t){const e=await pt(y.transactions,t);C(e)}return y}catch(e){c({type:Qe.DEFAULT,data:{error:e}})}}),[n,o,r,t]),v=async(e,t,n)=>{if(!e)return!1;const{tokenAddress:a,rawData:r,methodCall:o,gasEstimate:s}=e,[i,c]=await g(a,r,s);if(c||!i)return n(c,u.transactions),!1;const d={method:o,hash:i};return(e=>{p((t=>({...t,transactions:[...t.transactions,e]})))})(d),t(d),!0},R=a.useCallback((async(e,n,a,r)=>{if(!e||!t)return c({type:Qe.DEFAULT,data:{reason:"No sign data"}}),[];const o=await pt(e.transactions,t);let s=!0;for(const e of o){r&&r(e.methodCall,nt.BEFORE);if(!await v(e,n,a)){s=!1;break}r&&r(e.methodCall,nt.AFTER)}return(s?h:A)(),u.transactions}),[t,v,h,A,pt,g]),S=a.useCallback((async(e,n,a)=>{if(!y||u.done||!t)return!1;const r=y[T];a&&a(r.methodCall,nt.BEFORE);const o=await v(r,e,n);return o&&(f((e=>e+1)),T===y.length-1&&h(),a&&a(r.methodCall,nt.AFTER)),o}),[T,t,y]);return{sign:I,signResponse:d,signError:i,filteredTransactions:y,currentTransactionIndex:T,executeAll:R,executeResponse:u,tokenIds:E,executeNextTransaction:S}},Tt=(e,t)=>{const n=-1===e.findIndex((({name:e})=>f(e,t||"")));return t&&n&&console.warn(`[IMTBL]: invalid "preferredCurrency=${t}" widget input`),t&&!n?e.filter((({name:e})=>f(e,t))).map((({erc20_address:e,exchange_id:t,...n})=>({...n,base:!0,address:e,exchangeId:t}))):e.map((({erc20_address:e,exchange_id:t,...n})=>({...n,address:e,exchangeId:t})))},ft={config:{contractId:""},currencies:[],products:{},totalAmount:{}},yt=({items:e,environment:t,environmentId:n,provider:r,preferredCurrency:o})=>{const[s,i]=a.useState(),c=a.useRef(!1),[d,l]=a.useState(""),[u,p]=a.useState(ft),[E,m]=a.useState(void 0),T=e=>{m({type:Qe.SERVICE_BREAKDOWN,data:{reason:"Error fetching settlement currencies",error:e}})};return a.useEffect((()=>{e?.length&&r&&(async()=>{try{const t=new URLSearchParams,n=e.map((({productId:e,qty:t})=>({id:e,qty:t})));t.append("products",btoa(JSON.stringify(n)));const a=r.getSigner(),o=await a.getAddress();t.append("wallet_address",o),l(t.toString())}catch(e){T(e)}})()}),[e,r]),a.useEffect((()=>{t&&n&&d&&(async()=>{if(!c.current)try{c.current=!0;const e=`${it[t]}/${n}/order/quote?${d}`,a=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`${a.status} - ${a.statusText}`);const r=(({config:e,currencies:t,products:n,total_amount:a},r)=>({config:{contractId:e.contract_id},currencies:Tt(t,r),products:Object.entries(n).reduce(((e,[t,{product_id:n,...a}])=>({...e,[t]:{productId:t,...a}})),{}),totalAmount:a}))(await a.json(),o);p(r)}catch(e){T(e)}finally{c.current=!1}})()}),[t,n,d]),a.useEffect((()=>{if(0===u.currencies.length)return;const e=(o?u.currencies.find((e=>f(e.name,o))):void 0)||u.currencies.find((e=>e.base))||u.currencies?.[0];i(e)}),[u]),{orderQuote:u,selectedCurrency:s,orderQuoteError:E}},Ct=a.createContext({items:[],collectionName:"",provider:void 0,checkout:void 0,environmentId:"",environment:E.SANDBOX,recipientAddress:"",recipientEmail:"",sign:()=>Promise.resolve(void 0),executeAll:()=>Promise.resolve([]),executeNextTransaction:()=>Promise.resolve(!1),signResponse:void 0,signError:void 0,filteredTransactions:[],currentTransactionIndex:0,executeResponse:void 0,passport:void 0,isPassportWallet:!1,showCreditCardWarning:!1,setShowCreditCardWarning:()=>{},paymentMethod:void 0,setPaymentMethod:()=>{},goBackToPaymentMethods:()=>{},goToErrorView:()=>{},goToSuccessView:()=>{},config:{},fundingRoutes:[],disabledPaymentTypes:[],invalidParameters:!1,fromTokenAddress:"",orderQuote:ft,signTokenIds:[],excludePaymentTypes:[],preferredCurrency:void 0,selectedCurrency:void 0,waitFulfillmentSettlements:!0,hideExcludedPaymentTypes:!1});Ct.displayName="SaleSaleContext";const ht=1;function At(t){const{children:n,value:{config:r,environment:o,environmentId:s,items:i,provider:c,checkout:d,passport:l,collectionName:u,excludePaymentTypes:p,excludeFiatCurrencies:E,preferredCurrency:m,waitFulfillmentSettlements:T,hideExcludedPaymentTypes:f}}=t,A=a.useRef(0),{viewDispatch:g}=a.useContext(y),[{recipientEmail:I,recipientAddress:v},R]=a.useState({recipientEmail:"",recipientAddress:""}),[S,O]=a.useState(!1),[b,_]=a.useState(void 0),w=e=>{if(e===h.CREDIT&&!S)return _(void 0),void O(!0);_(e),O(!1)},[D]=a.useState([]),[P,k]=a.useState([]),[x,N]=a.useState(!1),{selectedCurrency:M,orderQuote:L,orderQuoteError:F}=yt({items:i,provider:c,environmentId:s,environment:r.environment,preferredCurrency:m}),U=M?.address||"",W=a.useCallback(((e,t)=>{w(e),g({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAYMENT_METHODS,data:t}}})}),[]);a.useEffect((()=>{(async()=>{const e=c?.getSigner(),t=await(e?.getAddress())||"",n=(await(l?.getUserInfo()))?.email||"";R({recipientEmail:n,recipientAddress:t})})()}),[c]);const{sign:B,executeAll:V,executeNextTransaction:Y,signResponse:H,signError:G,filteredTransactions:j,currentTransactionIndex:$,executeResponse:X,tokenIds:K}=mt({items:i,provider:c,fromTokenAddress:U,recipientAddress:v,environmentId:s,environment:o,waitFulfillmentSettlements:T}),z=a.useCallback((async(e,t,n)=>{const a=t||U;if(!a||!a.startsWith("0x"))return void N(!0);const r=await B(e,a);return r?(n?.(r),r):void 0}),[B,U]),q=a.useCallback(((e,t={})=>{A.current+=1,A.current>ht&&(A.current=0,w(void 0)),g({payload:{type:C.UPDATE_VIEW,view:{type:Ze.SALE_FAIL,data:{...t,errorType:e,paymentMethod:b,transactions:X.transactions}}}})}),[b,w,X]),Z=a.useCallback((e=>{g({payload:{type:C.UPDATE_VIEW,view:{type:Ze.SALE_SUCCESS,data:{paymentMethod:b,transactions:X.transactions,tokenIds:K,...e}}}})}),[[b,X,K]]);a.useEffect((()=>{G&&q(G.type,G.data)}),[G]),a.useEffect((()=>{F&&q(F.type,F.data)}),[F]),a.useEffect((()=>{!(!i||0===i.length)&&u&&s||N(!0)}),[i,u,s]),a.useEffect((()=>{p?.length<=0||k(p)}),[p]);const J=a.useMemo((()=>({config:r,items:i,fromTokenAddress:U,sign:z,signResponse:H,signError:G,filteredTransactions:j,currentTransactionIndex:$,executeAll:V,executeNextTransaction:Y,executeResponse:X,environmentId:s,collectionName:u,environment:o,provider:c,checkout:d,recipientAddress:v,recipientEmail:I,showCreditCardWarning:S,setShowCreditCardWarning:O,paymentMethod:b,setPaymentMethod:w,goBackToPaymentMethods:W,goToErrorView:q,goToSuccessView:Z,isPassportWallet:!!c?.provider?.isPassport,fundingRoutes:D,disabledPaymentTypes:P,invalidParameters:x,orderQuote:L,signTokenIds:K,excludePaymentTypes:p,excludeFiatCurrencies:E,selectedCurrency:M,waitFulfillmentSettlements:T,hideExcludedPaymentTypes:f})),[r,o,s,i,U,u,c,d,v,I,H,G,j,$,X,S,O,b,W,q,Z,z,D,P,x,L,K,p,E,M,T,f]);return e(Ct.Provider,{value:J,children:n})}function gt(){return a.useContext(Ct)}const It={[E.SANDBOX]:"https://global-stg.transak.com",[E.PRODUCTION]:"https://global.transak.com/"},vt={[E.SANDBOX]:"https://api-stg.transak.com",[E.PRODUCTION]:"https://api.transak.com"},Rt={[E.SANDBOX]:"STAGING",[E.PRODUCTION]:"PRODUCTION"},St={[E.SANDBOX]:"d14b44fb-0f84-4db5-affb-e044040d724b",[E.PRODUCTION]:"ad1bca70-d917-4628-bb0f-5609537498bc"},Ot=e=>{const{contractId:t,environment:n,transakParams:r,onError:o}=e,[s,i]=a.useState(""),c=a.useCallback((async()=>{try{const{calldata:e,nftData:a,estimatedGasLimit:o,cryptoCurrencyCode:s,excludeFiatCurrencies:i,...c}=r,d=a?.slice(0,1).map((e=>({...e,imageURL:lt(e.imageURL),nftName:lt(e.nftName)}))),l={contractId:t,cryptoCurrencyCode:s,calldata:e,nftData:d,estimatedGasLimit:(o>0?o:"30000000").toString()},u=`${vt[n]}/cryptocoverage/api/v1/public/one-click-protocol/nft-transaction-id`,p=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok)throw new Error("Failed to get NFT transaction ID");const{id:E}=await p.json(),m=`${It[n]}?`,T=new URLSearchParams({apiKey:St[n],environment:Rt[n],isNFT:"true",nftTransactionId:E,themeColor:"0D0D0D",...c});return i&&T.append("excludeFiatCurrencies",i.join(",")),`${m}${T.toString()}`}catch{o?.()}return""}),[t,n,r,o]);return a.useEffect((()=>{(async()=>{const e=await c();i(e)})()}),[]),{iframeSrc:s}};function bt(t){const{id:n,type:r,email:o,walletAddress:s,isPassportWallet:i,nftData:c,calldata:d,cryptoCurrencyCode:l,estimatedGasLimit:u,exchangeScreenTitle:p,partnerOrderId:E,excludeFiatCurrencies:m,onOpen:T,onInit:f,onOrderCreated:y,onOrderProcessing:C,onOrderCompleted:h,onOrderFailed:g,onFailedToLoad:I,failedToLoadTimeoutInMs:v,environment:R,contractId:S}=t,O=a.useRef(null),{onLoad:b,initialised:_}=xe({userJourney:A.SALE,ref:O,walletAddress:s,isPassportWallet:i,onOpen:T,onOrderCreated:y,onOrderProcessing:C,onOrderCompleted:h,onOrderFailed:g,onInit:f,failedToLoadTimeoutInMs:v,onFailedToLoad:I}),{iframeSrc:w}=Ot({type:r,contractId:S,environment:R,transakParams:{nftData:c,calldata:d,cryptoCurrencyCode:l,estimatedGasLimit:u,exchangeScreenTitle:p,email:o,walletAddress:s,partnerOrderId:E,excludeFiatCurrencies:m},onError:I});return e("iframe",{id:n,ref:O,src:w,title:"Transak-Iframe",allow:"camera;microphone;fullscreen;payment",style:{height:"100%",width:"100%",border:"none",position:"absolute",top:0,left:0,opacity:_?1:0,transition:"opacity 0.5s ease-out"},onLoad:b,onError:()=>I?.()})}function _t(t){const{t:n}=g(),{onInit:r,onOpen:o,onOrderCreated:s,onOrderProcessing:i,onOrderCompleted:c,onOrderFailed:d}=t,{recipientEmail:l,recipientAddress:u,isPassportWallet:p,signResponse:E,goToErrorView:m,environment:T,orderQuote:f,excludeFiatCurrencies:y}=gt(),C=E?.transactions.find((e=>e.methodCall.startsWith("execute")));if(!E||!C)return null;const h=a.useMemo((()=>E.order.products.map((e=>({collectionAddress:e.collectionAddress,imageURL:e.image,nftName:e.name,price:e.amount,quantity:e.qty,tokenID:e.tokenId,nftType:e.contractType||"ERC721"})))),[E]);return e(bt,{id:"transak-iframe",type:"nft-checkout",email:l,walletAddress:u,isPassportWallet:p,exchangeScreenTitle:n("views.PAY_WITH_CARD.screenTitle"),nftData:h,calldata:C.rawData,cryptoCurrencyCode:E.order.currency.name,estimatedGasLimit:C.gasEstimate,partnerOrderId:C.params.reference,excludeFiatCurrencies:y,onInit:r,onOpen:o,onOrderCreated:s,onOrderProcessing:i,onOrderCompleted:c,onOrderFailed:d,onFailedToLoad:()=>{m(Qe.TRANSAK_FAILED)},environment:T,contractId:f.config.contractId})}const wt=(e,t)=>{const{fundingItem:n}=e;return{settlementType:`${e.type}`,type:n.type,token:n.token,amount:n.fundsRequired.formattedAmount,balance:n.userBalance.formattedBalance,fiat:{symbol:"USD",balance:I(n.userBalance.formattedBalance,n.token.symbol,t),amount:I(n.fundsRequired.formattedAmount,n.token.symbol,t)}}},Dt=()=>{const{track:e,page:t}=v(),{recipientAddress:n,signResponse:r,paymentMethod:o}=gt(),{eventTargetState:{eventTarget:s}}=a.useContext(R),i=Ze.PAYMENT_METHODS,c={location:"web",userJourney:A.SALE},d={userId:n,paymentMethod:o},l={amount:r?.order.totalAmount,currency:r?.order.currency.name};return{track:e,page:t,sendPageView:(e,n)=>{t({...c,screen:dt(e),action:"Viewed",extras:{...n}})},sendCloseEvent:(t=i,n="Button",a="Pressed")=>{e({...c,screen:dt(t),control:"Close",controlType:n,action:a,extras:{...d}}),S(s)},sendSuccessEvent:(t=i,n=[],a=[],r={})=>{e({...c,screen:dt(t),control:"Success",controlType:"Event",action:"Succeeded",extras:{...r,...d,transactions:ct(n),...l,paymentMethod:o,tokenIds:a}}),O(s,o,n,a,r.transactionId)},sendFailedEvent:(t,n,a=[],r=i,u={})=>{e({...c,screen:dt(r||i),control:"Fail",controlType:"Event",action:"Failed",extras:{...u,transactions:ct(a),...n,...l,...d,paymentMethod:o,reason:t}}),b(s,t,n,o,a,u.transactionId)},sendTransactionSuccessEvent:e=>{_(s,o,[e])},sendOrderCreated:(t,n)=>{e({...c,screen:dt(t),control:"OrderCreated",controlType:"Event",extras:{...n}})},sendSelectedPaymentMethod:(t,n)=>{e({...c,screen:dt(n),control:"Select",controlType:"MenuItem",extras:{paymentMethod:t}}),w(s,t)},sendSelectedPaymentToken:(t,n,a)=>{const r=wt(n,a);e({...c,screen:dt(t),control:"Select",controlType:"MenuItem",extras:{...r}}),D(s,r)},sendProceedToPay:(t,n,a,r="Button",o="Pressed")=>{e({...c,screen:dt(t),control:"ProceedToPay",controlType:r,action:o,extras:{...d,...wt(n,a)}})},sendViewFeesEvent:(t,n="Button",a="Pressed")=>{e({...c,screen:dt(t),control:"ViewFees",controlType:n,action:a,extras:{...d}})}}};function Pt(){const{sendPageView:t}=Dt(),[n,r]=a.useState(!1),{goBackToPaymentMethods:o,goToErrorView:s,signResponse:i,signTokenIds:c}=gt(),{sendOrderCreated:d,sendCloseEvent:l,sendSuccessEvent:u}=Dt(),{t:E}=g(),m=(e={})=>{const{id:t,status:n,cryptoAmount:a,cryptoCurrency:r,fiatAmount:o,fiatAmountInUsd:s,amountPaid:d,totalFeeInFiat:p,paymentOptionId:E,userId:m,userKycType:T,walletAddress:f,nftAssetInfo:y}=e,{nftDataBase64:C,quantity:h}=y||{},A={orderId:t,orderStatus:n,cryptoAmount:a,cryptoCurrency:r,fiatAmount:o,fiatAmountInUsd:s,amountPaid:d,totalFeeInFiat:p,paymentOption:E,userId:m,userKycType:T,walletAddress:f,nftDataBase64:C,quantity:h,signData:i,transactionId:i?.transactionId};u(Ze.SALE_SUCCESS,[],c,A),l(Ze.SALE_SUCCESS)};return a.useEffect((()=>t(Ze.PAY_WITH_CARD)),[]),e(M,{header:n&&e(P,{onCloseButtonClick:()=>o()}),children:k(N,{children:[e(x,{visible:!n,children:e(x.Content,{children:e(x.Content.LoopingText,{text:[E("views.PAY_WITH_CARD.loading")]})})}),e(p,{style:{display:"block",position:"relative",maxWidth:"420px",height:"565px",borderRadius:"1%",overflow:"hidden",margin:"0 auto",width:"100%"},children:e(_t,{onInit:()=>r(!0),onOrderFailed:()=>{s(Qe.TRANSAK_FAILED)},onOrderCompleted:m,onOrderCreated:(e={})=>{const{id:t,status:n,cryptoAmount:a,cryptoCurrency:r,fiatAmount:o,fiatAmountInUsd:s,amountPaid:c,totalFeeInFiat:l,paymentOptionId:u,userId:p,userKycType:E,walletAddress:m,nftAssetInfo:T}=e,{nftDataBase64:f,quantity:y}=T||{};d(Ze.PAY_WITH_CARD,{orderId:t,orderStatus:n,cryptoAmount:a,cryptoCurrency:r,fiatAmount:o,fiatAmountInUsd:s,amountPaid:c,totalFeeInFiat:l,paymentOption:u,userId:p,userKycType:E,walletAddress:m,nftDataBase64:f,quantity:y,signData:i,transactionId:i?.transactionId})},onOrderProcessing:m})})]})})}var kt;!function(e){e.APPROVE="approve(address spender,uint256 amount)",e.EXECUTE="execute(address multicallSigner, bytes32 reference, address[] targets, bytes[] data, uint256 deadline, bytes signature)"}(kt||(kt={}));const xt=e=>{switch(e){case kt.APPROVE:return"/access_coins.riv";case kt.EXECUTE:return"/purchasing_items.riv";default:return""}};var Nt;!function(e){e[e.START=0]="START",e[e.WAITING=1]="WAITING",e[e.PROCESSING=2]="PROCESSING",e[e.COMPLETED=3]="COMPLETED",e[e.ERROR=4]="ERROR"}(Nt||(Nt={}));const Mt={[kt.APPROVE]:{url:xt(kt.APPROVE),stateMachine:"State",input:"mode",inputValues:{start:Nt.START,waiting:Nt.WAITING,processing:Nt.PROCESSING,completed:Nt.COMPLETED,error:Nt.ERROR}},[kt.EXECUTE]:{url:xt(kt.EXECUTE),stateMachine:"State",input:"mode",inputValues:{start:Nt.START,waiting:Nt.WAITING,processing:Nt.PROCESSING,completed:Nt.COMPLETED,error:Nt.ERROR}}};function Lt(t){const{t:n}=g(),{addHandover:r}=L({id:F.GLOBAL});return{onTxnStepExecuteNextTransaction:a.useCallback(((a,o)=>{switch(`${a}-${o}`){case`${kt.APPROVE}-${nt.BEFORE}`:r({animationUrl:U(t,xt(kt.APPROVE)),inputValue:Mt[kt.APPROVE].inputValues.processing,children:e(W,{children:n("views.PAYMENT_METHODS.handover.approve.pending")})});break;case`${kt.APPROVE}-${nt.AFTER}`:r({duration:B.MEDIUM,animationUrl:U(t,xt(kt.APPROVE)),inputValue:Mt[kt.APPROVE].inputValues.completed,children:e(W,{children:n("views.PAYMENT_METHODS.handover.approve.after")})});break;case`${kt.EXECUTE}-${nt.BEFORE}`:r({animationUrl:U(t,xt(kt.EXECUTE)),inputValue:Mt[kt.EXECUTE].inputValues.waiting,children:e(W,{children:n("views.PAYMENT_METHODS.handover.execute.pending")})});break;case`${kt.EXECUTE}-${nt.AFTER}`:r({animationUrl:U(t,xt(kt.EXECUTE)),inputValue:Mt[kt.EXECUTE].inputValues.processing,children:e(W,{children:n("views.PAYMENT_METHODS.handover.execute.after")})})}}),[t,r,n]),onTxnStepExecuteAll:a.useCallback(((a,o)=>{switch(`${a}-${o}`){case`${kt.APPROVE}-${nt.BEFORE}`:r({animationUrl:U(t,xt(kt.APPROVE)),inputValue:Mt[kt.APPROVE].inputValues.waiting,children:e(W,{children:n("views.PAYMENT_METHODS.handover.approve.before")})});break;case`${kt.APPROVE}-${nt.AFTER}`:r({animationUrl:U(t,xt(kt.APPROVE)),inputValue:Mt[kt.APPROVE].inputValues.completed,children:e(W,{children:n("views.PAYMENT_METHODS.handover.approve.after")})});break;case`${kt.EXECUTE}-${nt.BEFORE}`:r({animationUrl:U(t,xt(kt.EXECUTE)),inputValue:Mt[kt.EXECUTE].inputValues.waiting,children:e(W,{children:n("views.PAYMENT_METHODS.handover.execute.before")})});break;case`${kt.EXECUTE}-${nt.AFTER}`:r({duration:B.MEDIUM,animationUrl:U(t,xt(kt.EXECUTE)),inputValue:Mt[kt.EXECUTE].inputValues.processing,children:e(W,{children:n("views.PAYMENT_METHODS.handover.execute.after")})})}}),[t,r,n])}}function Ft({headingText:t,subheadingText:n,primaryButtonText:a,onPrimaryButtonClick:r,secondaryButtonText:o,onSecondaryButtonClick:s}){return k(p,{sx:{height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[k(p,{children:[e(W,{sx:{paddingBottom:"base.spacing.x4"},children:t}),e(V,{size:"small",sx:{textAlign:"center",color:"base.color.text.body.secondary"},children:n})]}),k(p,{children:[a&&r&&e(p,{sx:{paddingBottom:"base.spacing.x2"},children:e(Y,{sx:{width:"100%"},variant:"primary",size:"large",testId:"handover-primary-button",onClick:r,children:a})}),o&&s&&e(p,{sx:{paddingBottom:"base.spacing.x4"},children:e(Y,{sx:{width:"100%"},variant:"tertiary",size:"large",testId:"handover-secondary-button",onClick:s,children:o})})]})]})}const Ut={[kt.APPROVE]:{headingTextKey:"views.PAYMENT_METHODS.handover.approve.beforeWithCta.heading",ctaButtonTextKey:"views.PAYMENT_METHODS.handover.approve.beforeWithCta.ctaButton",animationUrl:xt(kt.APPROVE),inputValue:Nt.WAITING},[kt.EXECUTE]:{headingTextKey:"views.PAYMENT_METHODS.handover.execute.beforeWithCta.heading",ctaButtonTextKey:"views.PAYMENT_METHODS.handover.execute.beforeWithCta.ctaButton",animationUrl:xt(kt.EXECUTE),inputValue:Nt.START}};function Wt(){const t=a.useRef(!1),n=a.useRef(null),{t:r}=g(),{sendPageView:o,sendTransactionSuccessEvent:s,sendFailedEvent:i,sendCloseEvent:c,sendSuccessEvent:d}=Dt(),{executeAll:l,executeNextTransaction:u,signResponse:p,filteredTransactions:E,currentTransactionIndex:m,executeResponse:T,signTokenIds:f,environment:y,provider:C,goToErrorView:h}=gt(),{onTxnStepExecuteNextTransaction:A,onTxnStepExecuteAll:I}=Lt(y),{addHandover:v}=L({id:F.GLOBAL}),R=a.useCallback((async()=>{l(p,(e=>{s(e)}),((e,t)=>{const n={transactionId:p?.transactionId};i(e.toString(),e,t,void 0,n),h(e.type,e.data)}),I)}),[p,y]),S=a.useCallback((()=>{const t=E[m],n=Ut[t.methodCall],a=r(n.headingTextKey)||"",o=r(n.ctaButtonTextKey)||"";v({animationUrl:U(y,n.animationUrl),inputValue:n.inputValue,children:e(Ft,{headingText:a,primaryButtonText:o,onPrimaryButtonClick:()=>{try{u((e=>{s(e)}),((e,t)=>{const n={transactionId:p?.transactionId};i(e.toString(),e,t,void 0,n),h(e.type,e.data)}),A)}catch(e){h(Qe.SERVICE_BREAKDOWN,{error:e})}}})})}),[E,m,p,y]);return a.useEffect((()=>o(Ze.PAY_WITH_COINS)),[]),a.useEffect((()=>{if(!C||0===E.length)return;const e=m<E.length&&n.current!==m;H(C)&&e&&(n.current=m,S())}),[E,m,C]),a.useEffect((()=>{p&&C&&!t.current&&(H(C)||(t.current=!0,R()))}),[p,C]),a.useEffect((()=>{if(T?.done){const t={transactionId:p?.transactionId};v({duration:B.MEDIUM,animationUrl:U(y,xt(kt.EXECUTE)),inputValue:Nt.COMPLETED,children:e(W,{sx:{px:"base.spacing.x6"},children:r("views.PAYMENT_METHODS.handover.success")}),onClose:()=>{d(Ze.SALE_SUCCESS,T?.transactions,f,t),c(Ze.SALE_SUCCESS)}})}}),[T]),null}function Bt({type:t,onClick:n,disabled:a=!1,caption:r,size:o,rc:s=e("span",{})}){const{t:i}=g(),c={[h.CRYPTO]:"Coins",[h.DEBIT]:"BankCard",[h.CREDIT]:"BankCard"};return k(G,{rc:s,size:o||"medium",sx:{marginBottom:"base.spacing.x1",userSelect:"none",...a&&{filter:"opacity(0.5)",cursor:"not-allowed !important"}},...{disabled:a,emphasized:!0,onClick:a?void 0:()=>n(t)},children:[e(G.FramedIcon,{icon:c[t]}),e(G.Label,{size:"medium",children:i(`views.PAYMENT_METHODS.options.${t}.heading`)}),!a&&e(G.IntentIcon,{}),e(G.Caption,{children:r||i(`views.PAYMENT_METHODS.options.${t}.${a?"disabledCaption":"caption"}`)})]})}const Vt=[h.CRYPTO,h.DEBIT,h.CREDIT];function Yt(t){const{disabledOptions:n=[],paymentOptions:r,onClick:o,captions:s,size:i,hideDisabledOptions:c}=t,d=a.useMemo((()=>(r||Vt).filter((e=>!c||!n.includes(e)))),[r,n,c]);return a.useEffect((()=>{1===d.length&&o(d[0])}),[d,o]),e(p,{testId:"payment-options-list",sx:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start"},rc:e(j.div,{variants:$,initial:"hidden",animate:"show"}),children:d.map(((t,a)=>e(Bt,{type:t,size:i,onClick:o,disabled:n.includes(t),caption:s?.[t],rc:e(j.div,{custom:a,variants:X})},`payment-type-${t}`)))})}function Ht(){const{t:t}=g(),{viewDispatch:n}=a.useContext(y),{sign:r,goToErrorView:o,paymentMethod:s,setPaymentMethod:i,invalidParameters:c,disabledPaymentTypes:d,hideExcludedPaymentTypes:l}=gt(),{sendPageView:u,sendCloseEvent:E,sendSelectedPaymentMethod:m}=Dt();return a.useEffect((()=>{s&&m(s,Ze.PAYMENT_METHODS),s&&[h.DEBIT,h.CREDIT].includes(s)&&(r(et.FIAT,void 0,(()=>{n({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAY_WITH_CARD}}})})),n({payload:{type:C.UPDATE_VIEW,view:{type:K.LOADING_VIEW,data:{loadingText:t("views.PAYMENT_METHODS.loading.ready1")}}}})),s&&s===h.CRYPTO&&n({payload:{type:C.UPDATE_VIEW,view:{type:Ze.ORDER_SUMMARY,subView:Je.INIT}}})}),[s]),a.useEffect((()=>u(Ze.PAYMENT_METHODS)),[]),a.useEffect((()=>{c&&o(Qe.INVALID_PARAMETERS)}),[c]),e(M,{testId:"payment-methods",header:e(P,{onCloseButtonClick:()=>E(Ze.PAYMENT_METHODS)}),footer:e(z,{}),children:k(p,{sx:{display:"flex",flexDirection:"column",paddingX:"base.spacing.x2",paddingY:"base.spacing.x8",rowGap:"base.spacing.x4"},children:[e(W,{size:"small",sx:{paddingX:"base.spacing.x4"},children:t("views.PAYMENT_METHODS.header.heading")}),e(p,{sx:{paddingX:"base.spacing.x2"},children:e(Yt,{hideDisabledOptions:l,disabledOptions:d,onClick:e=>{i(e)}})})]})})}function Gt({biomeTheme:t,transactionHash:n,blockExplorerLink:r,errorType:o}){const{t:s}=g(),{goBackToPaymentMethods:i,executeNextTransaction:c,signResponse:d,environment:l,provider:u}=gt(),{sendTransactionSuccessEvent:p,sendFailedEvent:E}=Dt(),{viewDispatch:m}=a.useContext(y),{eventTargetState:{eventTarget:T}}=a.useContext(R),{addHandover:f,closeHandover:h}=L({id:F.GLOBAL}),{onTxnStepExecuteNextTransaction:A}=Lt(l),[I,v]=a.useState(o),O=()=>{S(T)},b=()=>{try{c((e=>{p(e),m({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAY_WITH_COINS}}})}),((e,t)=>{const n={transactionId:d?.transactionId};E(e.toString(),e,t,void 0,n),v(Qe.TRANSACTION_FAILED)}),A)}catch(e){v(Qe.SERVICE_BREAKDOWN)}},_={[Qe.TRANSACTION_FAILED]:{onActionClick:()=>{h(),i()},onSecondaryActionClick:n?()=>{window.open(r)}:O,statusType:q.FAILURE,statusIconStyles:{fill:t.color.status.fatal.dim}},[Qe.SERVICE_BREAKDOWN]:{onSecondaryActionClick:O,statusType:q.INFORMATION,statusIconStyles:{fill:t.color.status.fatal.dim}},[Qe.PRODUCT_NOT_FOUND]:{onSecondaryActionClick:O,statusType:q.INFORMATION,statusIconStyles:{fill:t.color.status.fatal.dim}},[Qe.INSUFFICIENT_STOCK]:{onSecondaryActionClick:O,statusType:q.INFORMATION,statusIconStyles:{fill:t.color.status.fatal.dim}},[Qe.TRANSAK_FAILED]:{onActionClick:()=>{h(),i()},onSecondaryActionClick:O,statusType:q.INFORMATION},[Qe.WALLET_FAILED]:{onActionClick:()=>{H(u)?b():(h(),i())},onSecondaryActionClick:O,statusType:q.INFORMATION,statusIconStyles:{fill:t.color.status.fatal.dim}},[Qe.WALLET_REJECTED_NO_FUNDS]:{onActionClick:()=>{h(),i()},onSecondaryActionClick:O,statusType:q.INFORMATION},[Qe.WALLET_REJECTED]:{onActionClick:()=>{H(u)?b():(h(),i())},onSecondaryActionClick:O,statusType:q.INFORMATION},[Qe.WALLET_POPUP_BLOCKED]:{onActionClick:()=>{H(u)?b():(h(),i())},onSecondaryActionClick:O,statusType:q.INFORMATION},[Qe.FUNDING_ROUTE_EXECUTE_ERROR]:{onActionClick:()=>{h(),i()},onSecondaryActionClick:O,statusType:q.INFORMATION},[Qe.INVALID_PARAMETERS]:{onSecondaryActionClick:O,statusType:q.ALERT,statusIconStyles:{fill:t.color.status.attention.dim,transform:"none"}},[Qe.DEFAULT]:{onActionClick:()=>{h(),i()},onSecondaryActionClick:O,statusType:q.INFORMATION}},w=()=>{const e=_[I||Qe.DEFAULT]||{},t=I===Qe.TRANSACTION_FAILED&&n?s(`views.SALE_FAIL.errors.${I}.secondaryAction`):s(`views.SALE_FAIL.errors.${Qe.DEFAULT}.secondaryAction`);return{headingText:s("views.PAYMENT_METHODS.handover.error.heading"),subheadingText:s(`views.SALE_FAIL.errors.${I}.description`),primaryButtonText:s(`views.SALE_FAIL.errors.${I}.primaryAction`),onPrimaryButtonClick:e?.onActionClick,secondaryButtonText:t,onSecondaryButtonClick:e?.onSecondaryActionClick}};return a.useEffect((()=>{l&&I&&f({animationUrl:U(l,xt(kt.APPROVE)),inputValue:Nt.ERROR,children:e(Ft,{...w()})})}),[I,l]),null}function jt({balance:t,conversions:n,canOpen:a,onClick:r,onProceed:o,loading:s,priceDisplay:i}){const{t:c}=g(),{environment:d,config:{theme:l}}=gt(),{token:u,userBalance:p,fundsRequired:E}=t.fundingItem,m=I(E.formattedAmount,u.symbol,n,""),T=I(p.formattedBalance,u.symbol,n,"");return k(Q,{sx:{w:"100%",bradtl:"base.borderRadius.x6",bradtr:"base.borderRadius.x6",px:"base.spacing.x4",pb:"base.spacing.x6",bg:"base.color.neutral.800",border:"0px solid transparent",borderTopWidth:"base.border.size.100",borderTopColor:"base.color.translucent.emphasis.400"},children:[k(G,{size:"medium",children:[e(G.FramedImage,{circularFrame:!0,use:e(Ve,{environment:d,theme:l,name:u.name,src:u.icon})}),e(G.Label,{children:c(`views.ORDER_SUMMARY.orderReview.payWith.${t.type}`,{symbol:u.symbol})}),e(G.Caption,{rc:e(W,{size:"xSmall"}),children:`${c("views.ORDER_SUMMARY.orderReview.balance",{amount:Z(J(p.formattedBalance))})} ${T?c("views.ORDER_SUMMARY.currency.fiat",{amount:Z(J(T))}):""}`}),i&&e(G.PriceDisplay,{use:e(W,{size:"xSmall"}),fiatAmount:m?c("views.ORDER_SUMMARY.currency.fiat",{amount:m}):void 0,price:J(E.formattedAmount)}),a&&e(G.StatefulButtCon,{icon:"ChevronExpand",onClick:r}),!a&&s&&e(st,{radius:"base.icon.size.400"})]}),e(Y,{size:"large",onClick:()=>o(t),children:c("views.ORDER_SUMMARY.orderReview.continue")})]})}const $t=(e,t)=>e.filter((e=>e.amount.gt(0)&&e.token)).reduce(((e,n)=>{if(!n.token)return e;const a={...n.token,address:n.token.address||"",symbol:n.token.symbol||t?.symbol||""},r=te(a.address,"...").toLowerCase(),o=a.symbol||r;if(!o)return e;if(e[o]){const t=e[o].amount.add(n.amount);return{...e,[o]:{...e[o],amount:t,formattedAmount:Me(t,a.decimals)}}}return o?{...e,[o]:{...n,token:a,formattedAmount:Me(n.amount,a.decimals)}}:e}),{}),Xt=e=>{if(e.type!==ee.SWAP)return{};const t=[e.fees.approvalGasFee,e.fees.swapGasFee,...e.fees.swapFees];return $t(t,e.fundingItem.token)},Kt=(e,t,n)=>{const a=[];if(e.type!==ee.SWAP)return[];const r=(e,r,o="~ ")=>{if(e.amount.gt(0)){const s=Me(e.amount,e?.token?.decimals);a.push({label:r,fiatAmount:`≈ ${n("drawers.feesBreakdown.fees.fiatPricePrefix")}${I(s,e.token?.symbol||"",t,"-.--",4)}`,amount:`${J(s)}`,prefix:o,token:e?.token})}};r(e.fees.swapGasFee,n("drawers.feesBreakdown.fees.swapGasFee.label")),r(e.fees.approvalGasFee,n("drawers.feesBreakdown.fees.approvalFee.label"));return Object.entries($t(e.fees.swapFees,e.fundingItem.token)).forEach((([,e])=>{const t=e?.basisPoints??0;r(e,n("drawers.feesBreakdown.fees.swapSecondaryFee.label",{amount:t?t/100+"%":""}),"")})),a};function zt({rc:t=e("span",{}),balance:n,conversions:a,selected:r,onClick:o,size:s,environment:i,theme:c}){const{t:d}=g(),{token:l,userBalance:u}=n.fundingItem,E=I(u.formattedBalance,l.symbol,a,""),m=Object.entries(Xt(n));return k(G,{rc:t,sx:{mb:"base.spacing.x1"},size:s,emphasized:!0,...{onClick:o,selected:r},children:[e(G.FramedImage,{circularFrame:!0,alt:l.name,use:e(Ve,{environment:i,theme:c,name:l.name,src:l.icon})}),e(G.PriceDisplay,{use:e(W,{size:"xSmall"}),fiatAmount:E?d("views.ORDER_SUMMARY.currency.fiat",{amount:E}):void 0,price:J(u.formattedBalance)}),e(G.Label,{sx:{display:"flex",wordBreak:"default"},children:l.symbol}),e(G.Caption,{children:m.length>0&&m.map((([t,{token:n,formattedAmount:a}])=>e(p,{rc:e("span",{}),sx:{d:"block"},children:d("views.ORDER_SUMMARY.coinsDrawer.fee",{symbol:n?.symbol||t,amount:Z(J(a))})},t)))})]})}function qt({conversions:t,balances:n,selectedIndex:a,visible:r,loading:o,transactionRequirement:s,onClose:i,onSelect:c,onPayWithCard:d,disabledPaymentTypes:l,theme:u,environment:E}){const{t:m}=g();let T="medium";n.length>3&&(T="small");const f=[h.DEBIT,h.CREDIT],y=!f.every((e=>l?.includes(e)));return e(ne,{size:"full",visible:r,showHeaderBar:!0,onCloseDrawer:i,headerBarTitle:m("views.ORDER_SUMMARY.coinsDrawer.header"),children:e(ne.Content,{rc:e(j.div,{variants:$,initial:"hidden",animate:"show"}),children:k(p,{sx:{height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",px:"base.spacing.x4"},children:[k(p,{children:[k(p,{sx:{display:"flex",justifyContent:"space-between",mb:"base.spacing.x2"},children:[e(qe,{size:"small",children:m("views.ORDER_SUMMARY.coinsDrawer.caption1")}),e(qe,{size:"small",children:m("views.ORDER_SUMMARY.coinsDrawer.caption2")})]}),n?.map(((n,r)=>{return e(zt,{onClick:(o=r,()=>{c(o),i()}),balance:n,selected:a===r,conversions:t,transactionRequirement:s,size:T,theme:u,environment:E,rc:e(j.div,{variants:X,custom:r})},`${n.fundingItem.token.symbol}-${n.type}`);var o})),o&&e(j.div,{variants:X,custom:n.length,children:e(G,{shimmer:!0,emphasized:!0,size:T,testId:"funding-balance-item-shimmer"})},"funding-balance-item-shimmer")]}),d&&k(p,{sx:{pb:"base.spacing.x4"},rc:e(j.div,{variants:X,custom:n.length+(o?1:0)}),children:[y&&e(ae,{size:"small",rc:e(qe,{}),sx:{my:"base.spacing.x4"},children:m("views.ORDER_SUMMARY.coinsDrawer.divider")}),e(Yt,{onClick:d,size:T,hideDisabledOptions:!0,paymentOptions:f,disabledOptions:l,captions:{[h.DEBIT]:m("views.PAYMENT_METHODS.options.debit.caption"),[h.CREDIT]:m("views.PAYMENT_METHODS.options.credit.caption")}})]})]})})})}function Zt({item:t,balance:n,pricing:a,conversions:r,size:o,sx:s,rc:i=e("span",{})}){const{t:c}=g(),{token:d}=n.fundingItem,l=a?.amount||0,u=I(l.toString(),d.symbol,r);return k(G,{rc:i,emphasized:!0,size:o||"medium",sx:{pointerEvents:"none",mb:"base.spacing.x1",...s},children:[e(G.FramedImage,{use:e(Ve,{src:t.image,name:t.name,defaultImage:t.image})}),e(G.Label,{children:t.name}),e(G.Caption,{children:c("views.ORDER_SUMMARY.orderItem.quantity",{qty:t.qty})}),l>0&&e(G.PriceDisplay,{use:e(W,{size:"xSmall"}),price:c("views.ORDER_SUMMARY.currency.price",{symbol:d.symbol,amount:J(l)}),fiatAmount:c("views.ORDER_SUMMARY.currency.fiat",{amount:u})})]},t.name)}const Jt=(e,t,n)=>{if(!t)return;const a=e.toLowerCase(),r=re[a]?.toLowerCase(),o=Object.values(t).find((e=>[a,r].includes(e.currency.toLowerCase())));if(o)return o;const s=n.get(a)||n.get(r);return s&&t.USDC?{currency:e,type:t.USDC.type,amount:t.USDC.amount/s}:void 0},Qt={mb:"0",bradbl:"0",bradbr:"0"};function en({items:t,balance:n,pricing:a,conversions:r,children:o}){return k(p,{rc:e(j.div,{variants:$,initial:"hidden",animate:"show"}),children:[t.map(((s,i)=>e(Zt,{item:s,balance:n,conversions:r,size:t.length>=3?"small":"medium",pricing:Jt(n.fundingItem.token.symbol,a?.[s.productId]?.pricing,r),sx:i===t.length-1&&o?Qt:void 0,rc:e(j.div,{variants:X,custom:i})},s.name))),o]})}function tn({sx:t,swapFees:n,onFeesClick:a}){return e(Ye,{gasFeeFiatValue:n.fiatAmount,gasFeeToken:n.token,gasFeeValue:n.amount,fees:n.formattedFees,onFeesClick:a,sx:t,loading:!1})}function nn({fundingBalances:t,conversions:n,collectionName:r,loadingBalances:o,transactionRequirement:s,onBackButtonClick:i,onPayWithCard:c,onProceedToBuy:d}){const{eventTargetState:{eventTarget:l}}=a.useContext(R),{t:u}=g(),{provider:E,items:m,orderQuote:T,disabledPaymentTypes:f,config:{theme:y,environment:C}}=gt(),{sendSelectedPaymentToken:h,sendViewFeesEvent:A,sendPageView:v}=Dt(),[O,b]=a.useState(!1),[_,w]=a.useState(0),[D,x]=a.useState({token:void 0,amount:"",fiatAmount:"",formattedFees:[]}),N=a.useMemo((()=>t[_]),[t,_,E]);a.useEffect((()=>{if(!n?.size||!E)return;if(N.type!==ee.SWAP)return;const[[,e]]=Object.entries(Xt(N));e&&e.token&&x({token:e.token,amount:e.formattedAmount,fiatAmount:I(e.formattedAmount,e.token.symbol,n),formattedFees:Kt(N,n,u)})}),[N,n,E]),Le((()=>{const e=t.map((e=>wt(e,n)));v(Ze.ORDER_SUMMARY,{subView:Je.REVIEW_ORDER,tokens:e,items:m,collectionName:r})}),(()=>Boolean(m.length&&t.length&&!o&&n.size)),[m,t,o,n]);const L=m.length>1,F=!o&&N.type===ee.SWAP;return k(M,{testId:"order-review",header:e(P,{showBack:!0,onCloseButtonClick:()=>S(l),onBackButtonClick:i,title:r}),bodyStyleOverrides:{display:"flex",flexDirection:"column",justifyContent:"space-between",height:"0"},children:[e(W,{size:"small",sx:{px:"base.spacing.x4",pb:"base.spacing.x4"},children:u("views.ORDER_SUMMARY.orderReview.heading")}),e(p,{sx:{display:"flex",flexDirection:"column",px:"base.spacing.x2",pb:"base.spacing.x8",flex:1,maxh:F?"45%":"60%",overflowY:"scroll",scrollbarWidth:"none",rowGap:"base.spacing.x4"},children:e(p,{sx:{px:"base.spacing.x2"},children:e(en,{items:m,balance:N,pricing:T.products,conversions:n,children:!L&&F&&e(tn,{swapFees:D,sx:{bradtl:"0",bradtr:"0",brad:"base.borderRadius.x6",border:"0px solid transparent",borderTopWidth:"base.border.size.200",borderTopColor:"base.color.translucent.inverse.1000"},onFeesClick:()=>A(Ze.ORDER_SUMMARY)})})})}),L&&F&&e(tn,{swapFees:D,sx:{mb:"-12px",bradtl:"base.borderRadius.x6",bradtr:"base.borderRadius.x6",border:"0px solid transparent",borderTopWidth:"base.border.size.100",borderTopColor:"base.color.translucent.emphasis.400"},onFeesClick:()=>A(Ze.ORDER_SUMMARY)}),e(jt,{onClick:()=>{b(!0)},onProceed:d,balance:N,conversions:n,canOpen:t.length>1,loading:o,priceDisplay:m.length>1}),e(qt,{conversions:n,balances:t,onSelect:e=>{w(e),h(Je.REVIEW_ORDER,t[e],n)},onClose:()=>{b(!1)},selectedIndex:_,visible:O,loading:o,onPayWithCard:c,transactionRequirement:s,disabledPaymentTypes:f,theme:y,environment:C})]})}const an=(e,t)=>{const n=de(e.address)?e.symbol:e.address??"";return{...e,icon:le(t,n)}},rn=(e,t)=>{return{type:tt.SUFFICIENT,fundingItem:{type:oe.ERC20,token:an((n=e,n.current.type!==oe.ERC721&&n.current.token),t),fundsRequired:{amount:e.required.balance,formattedAmount:e.required.formattedBalance},userBalance:{balance:e.current.balance,formattedBalance:e.current.formattedBalance}}};var n},on=(e,t)=>{if(0===e.length)return[];const n=e.filter((e=>1===e.steps.length)),a=[oe.ERC20,oe.NATIVE];return n.flatMap((e=>e.steps.filter((e=>a.includes(e.fundingItem.type))))).map((e=>({...e,fundingItem:{...e.fundingItem,token:an(e.fundingItem.token,t)}})))},sn=e=>{let t=[];const n=(a=e.name,(e,t)=>{const n=e.fundingItem&&e.fundingItem.token&&e.fundingItem.token.symbol===a?-1:0,r=t.fundingItem&&t.fundingItem.token&&t.fundingItem.token.symbol===a?-1:0;return n!==r?n-r:e.type===tt.SUFFICIENT&&t.type===tt.SUFFICIENT?0:e.type===tt.SUFFICIENT?-1:t.type===tt.SUFFICIENT?1:0});var a;return e=>(0===e.length||(t=Array.from(new Set([...t,...e])).sort(n)),t)},cn=e=>({...e,amount:T.from(0),formattedAmount:"0"}),dn=(e,t)=>e.map((e=>((e,t)=>{if(e.type!==ee.SWAP)return e;if(!ue(t))return e;const n={...e.fees,approvalGasFee:cn(e.fees.approvalGasFee),swapGasFee:cn(e.fees.swapGasFee)};return{...e,fees:n}})(e,t))),ln=async e=>{const{provider:t,checkout:n,currencies:a,baseCurrency:r,onFundingBalance:o,getAmountByCurrency:s,getIsGasless:i,onComplete:c,onFundingRequirement:d}=e,l=t?.getSigner(),u=await(l?.getAddress())||"",p=n.config.environment,E=sn(r),m=e=>{Array.isArray(e)&&e.length>0&&o(E(dn(e,t)))},y=e=>f(e,r.name),C=a.map((async e=>{const a=s(e);if(!a)return null;const r=((e,t,n)=>[{type:oe.ERC20,tokenAddress:n,spenderAddress:t,amount:e}])(a,u,e.address),o=i()?void 0:{type:se.GAS,gasToken:{type:ie.NATIVE,limit:T.from("30000000")}};return{currency:e,smartCheckoutResult:await n.smartCheckout({provider:t,itemRequirements:r,transactionOrGasAmount:o,routingOptions:{bridge:!1,onRamp:!1,swap:!0},fundingRouteFullAmount:!0,onComplete:y(e.name)?()=>{c?.(E([]))}:void 0,onFundingRoute:y(e.name)?e=>{m(on([e],p))}:void 0})}})).filter(Boolean),h=await(async(e,t)=>{const n=e.map((async e=>{const n=await e;return t(n),n}));return await Promise.all(n)})(C,(({currency:e,smartCheckoutResult:t})=>{if(y(e.name)){const e=t.transactionRequirements[0];d(e)}t.sufficient&&m(((e,t)=>{if(!0===e.sufficient){const n=e.transactionRequirements.find((e=>e.type===oe.ERC20));if(n&&n.type===oe.ERC20)return[rn(n,t)]}return!1===e.sufficient&&e?.router?.routingOutcome.type===ce.ROUTES_FOUND?on(e.router.routingOutcome.fundingRoutes,t):null})(t,p))}));return h},un=()=>{const e=a.useRef(!1),{fromTokenAddress:t,orderQuote:n,provider:r,checkout:o,selectedCurrency:s}=gt(),{cryptoFiatState:i}=a.useContext(Fe),[c,d]=a.useState(),[l,u]=a.useState([]),[p,E]=a.useState([]),[m,T]=a.useState(!1);return{fundingBalances:l,loadingBalances:m,fundingBalancesResult:p,transactionRequirement:c,queryFundingBalances:()=>{t&&r&&o&&n&&s&&(e.current||m||(async()=>{e.current=!0,T(!0);try{const e=await ln({provider:r,checkout:o,currencies:n.currencies,routingOptions:{bridge:!1,onRamp:!1,swap:!0},baseCurrency:s,getAmountByCurrency:e=>{const t=Jt(e.name,n.totalAmount,i.conversions);return t?t.amount.toString():""},getIsGasless:()=>r.provider?.isPassport||!1,onFundingBalance:e=>{u([...e])},onComplete:()=>{T(!1)},onFundingRequirement:e=>{d(e)}});E(e)}catch{T(!1)}finally{e.current=!1}})())}}},pn=e=>{if(e&&e.current.type!==oe.ERC721)return e.current.token},En=e=>{const t=e.find((({type:e})=>e===oe.NATIVE)),n=e.find((({type:e})=>e===oe.ERC20)),a={erc20:{value:n?.delta.formattedBalance,symbol:pn(n)?.symbol},native:{value:t?.delta.formattedBalance,symbol:pn(t)?.symbol}};let r=["views.PAYMENT_METHODS.topUp.subheading.erc20",a],o=n?.delta.formattedBalance||"0",s=pn(n)?.address;return t&&n&&!t.sufficient&&!n.sufficient&&(r=["views.PAYMENT_METHODS.topUp.subheading.both",a]),t&&n&&!t.sufficient&&n.sufficient&&(o=t?.delta.formattedBalance||"0",s=pn(t)?.address,r=["views.PAYMENT_METHODS.topUp.subheading.native",a]),{heading:["views.PAYMENT_METHODS.topUp.heading"],subheading:r,amount:o,tokenAddress:s}};var mn;function Tn({fundingRouteStep:t,onFundingRouteExecuted:n}){const{t:r}=g(),{config:o,provider:s,checkout:i,fromTokenAddress:c}=gt(),{viewDispatch:d}=a.useContext(y),{connectLoaderDispatch:l}=a.useContext(pe),[u,p]=a.useState(void 0),[E,m]=a.useState(void 0),[T,f]=a.useState(void 0),[h,A]=a.useState(mn.LOADING),I=a.useRef(!1),v=a.useRef(void 0),S=a.useRef(void 0),[O,b]=a.useReducer(Ee,me),_=a.useMemo((()=>({eventTargetState:O,eventTargetDispatch:b})),[O,b]),w=new EventTarget,D=e=>{d({payload:{type:C.UPDATE_VIEW,view:{type:Ze.SALE_FAIL,data:{errorType:Qe.FUNDING_ROUTE_EXECUTE_ERROR,errorData:e}}}})},P=a.useCallback((async e=>{if(!i||!s)throw new Error("checkout or provider not available.");const t=await i.getNetworkInfo({provider:s});if(e.type===ee.BRIDGE){if(m({tokenAddress:e.fundingItem.token.address,amount:e.fundingItem.fundsRequired.formattedAmount}),t.chainId===Te(i.config))return void A(mn.EXECUTE_BRIDGE);I.current=mn.EXECUTE_BRIDGE,A(mn.SWITCH_NETWORK_ETH)}if(e.type===ee.SWAP){if(p({amount:e.fundingItem.fundsRequired.formattedAmount,fromTokenAddress:e.fundingItem.token.address,toTokenAddress:c}),t.chainId===fe(i.config))return void A(mn.EXECUTE_SWAP);I.current=mn.EXECUTE_SWAP,A(mn.SWITCH_NETWORK_ZKEVM)}e.type===ee.ONRAMP&&(f({amount:e.fundingItem.fundsRequired.formattedAmount,tokenAddress:e.fundingItem.token.address}),A(mn.EXECUTE_ON_RAMP))}),[s,i]);a.useEffect((()=>{if(t)try{P(t)}catch(e){D(e)}}),[t]);const x=()=>{v.current?(v.current=void 0,S.current=void 0,n()):D(S.current)},N=e=>{switch(e.detail.type){case ve.SUCCESS:{const t=e.detail.data;v.current=t,x();break}case Se.TRANSACTION_SENT:case Re.SUCCESS:{const t=e.detail.data;v.current=t;break}case Se.FAILURE:case ve.FAILURE:case Re.FAILURE:{const t=e.detail.data;S.current=t;break}case Se.CLOSE_WIDGET:case ve.CLOSE_WIDGET:case Re.CLOSE_WIDGET:x();case ve.REJECTED:}},M=e=>{switch(e.detail.type){case Oe.SUCCESS:{const t=e.detail.data;l({payload:{type:be.SET_PROVIDER,provider:t.provider}}),!1!==I.current&&(A(I.current),I.current=!1);break}case Oe.FAILURE:case Oe.CLOSE_WIDGET:default:x()}};return a.useEffect((()=>(w.addEventListener(ye.IMTBL_CONNECT_WIDGET_EVENT,M),w.addEventListener(ye.IMTBL_BRIDGE_WIDGET_EVENT,N),w.addEventListener(ye.IMTBL_SWAP_WIDGET_EVENT,N),()=>{w.removeEventListener(ye.IMTBL_CONNECT_WIDGET_EVENT,M),w.removeEventListener(ye.IMTBL_BRIDGE_WIDGET_EVENT,N),w.removeEventListener(ye.IMTBL_SWAP_WIDGET_EVENT,N)})),[]),a.useEffect((()=>{b({payload:{type:Ce.SET_EVENT_TARGET,eventTarget:w}})}),[i]),k(R.Provider,{value:_,children:[h===mn.LOADING&&e(he,{loadingText:r("views.ORDER_SUMMARY.loading.balances")}),h===mn.EXECUTE_BRIDGE&&e(He,{...E,config:o,checkout:i}),h===mn.EXECUTE_SWAP&&e(Ge,{...u,config:o}),h===mn.EXECUTE_ON_RAMP&&e(Ne,{config:o,...T}),h===mn.SWITCH_NETWORK_ETH&&e(Ie,{config:o,targetChainId:i.config.isProduction?Ae.ETHEREUM:Ae.SEPOLIA,web3Provider:s,checkout:i,deepLink:ge.SWITCH_NETWORK}),h===mn.SWITCH_NETWORK_ZKEVM&&e(Ie,{config:o,targetChainId:i.config.isProduction?Ae.IMTBL_ZKEVM_MAINNET:Ae.IMTBL_ZKEVM_TESTNET,web3Provider:s,checkout:i,deepLink:ge.SWITCH_NETWORK})]})}function fn({text:t,duration:n,animationUrl:a,inputValue:r=0}){const{addHandover:o}=L({id:F.GLOBAL});return Le((()=>{o({duration:n,animationUrl:a,inputValue:r,children:e(W,{sx:{px:"base.spacing.x6"},children:t})})})),null}function yn({subView:t}){const{t:n}=g(),{sendProceedToPay:r}=Dt(),{fromTokenAddress:o,collectionName:s,goToErrorView:i,goBackToPaymentMethods:c,sign:d,selectedCurrency:l,setPaymentMethod:u,environment:E}=gt(),{viewDispatch:m,viewState:T}=a.useContext(y),{cryptoFiatDispatch:f,cryptoFiatState:h}=a.useContext(Fe),{addHandover:A,closeHandover:I}=L({id:F.GLOBAL}),v=t=>{A({animationUrl:U(E,xt(kt.APPROVE)),inputValue:Mt[kt.APPROVE].inputValues.start,children:e(W,{sx:{px:"base.spacing.x6"},children:n("views.PAYMENT_METHODS.handover.initial")})}),d(et.CRYPTO,t),m({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAY_WITH_COINS}}})},R=()=>{v(l?.address)},{fundingBalances:S,loadingBalances:O,fundingBalancesResult:b,transactionRequirement:_,queryFundingBalances:w}=un();return a.useEffect((()=>{t===Je.INIT&&o&&w()}),[t,o]),a.useEffect((()=>{0!==S.length&&(I(),m({payload:{type:C.UPDATE_VIEW,view:{type:Ze.ORDER_SUMMARY,subView:Je.REVIEW_ORDER}}}))}),[S]),a.useEffect((()=>{if(!O&&b.length&&!(S.length>0))try{const e=b.find((e=>e.currency.base))?.smartCheckoutResult,t=En(e.transactionRequirements);u(void 0),I(),m({payload:{type:C.UPDATE_VIEW,view:{type:K.TOP_UP_VIEW,data:t}}})}catch(e){i(Qe.SERVICE_BREAKDOWN,e)}}),[S,O,b]),a.useEffect((()=>{if(!f||0===S.length||O)return;const e=S.map((({fundingItem:e})=>e.token.symbol));f({payload:{type:Ue.SET_TOKEN_SYMBOLS,tokenSymbols:e}})}),[f,S,O]),k(p,{children:[t===Je.INIT&&e(fn,{text:n("views.ORDER_SUMMARY.loading.balances"),animationUrl:U(E,"/preparing_order.riv"),inputValue:0}),t===Je.REVIEW_ORDER&&e(nn,{fundingBalances:S,conversions:h.conversions,collectionName:s,loadingBalances:O,onBackButtonClick:c,onProceedToBuy:e=>{const{type:t,fundingItem:n}=e;r(Ze.ORDER_SUMMARY,e,h.conversions),t!==tt.SUFFICIENT?(I(),m({payload:{type:C.UPDATE_VIEW,view:{type:Ze.ORDER_SUMMARY,subView:Je.EXECUTE_FUNDING_ROUTE,data:{fundingBalance:e,onFundingRouteExecuted:R}}}})):v(n.token.address)},transactionRequirement:_,onPayWithCard:e=>c(e)}),t===Je.EXECUTE_FUNDING_ROUTE&&e(Tn,{fundingRouteStep:T.view.data.fundingBalance,onFundingRouteExecuted:R})]})}function Cn(){return e(p,{testId:"credit-card-warning-hero",children:e(p,{children:k("svg",{width:"430",height:"161",viewBox:"0 0 430 161",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M172.973 133.128C171.472 132.262 170.399 130.653 170.399 128.67V91.134C170.399 87.4566 171.381 83.9165 173.158 80.8356C174.934 77.7546 177.509 75.137 180.697 73.2962L199.556 62.4057L231.623 44.1673C233.339 43.1761 235.27 43.3005 236.772 44.1673L229.34 39.8763C227.838 39.0095 225.907 38.8851 224.191 39.8763L192.124 58.1147L173.265 69.0052C170.077 70.8461 166.889 72.6253 165.112 75.7062C163.336 78.7872 162.967 83.1656 162.967 86.843V124.379C162.967 126.361 164.04 127.971 165.541 128.837L172.973 133.128Z",fill:"#F3F3F3",stroke:"#131313",strokeWidth:"1.64647",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M239.133 48.6725V85.9384C239.133 96.0882 236.344 99.3065 228.835 103.776L178.124 133.123C174.691 135.105 170.4 132.629 170.4 128.665V91.3985C170.4 82.7861 172.193 78.066 180.698 73.5609L231.409 44.2142C234.842 42.2317 239.133 44.7076 239.133 48.6725Z",fill:"#F3F3F3",stroke:"#131313",strokeWidth:"1.64647",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M172.973 133.127C171.472 132.26 170.399 130.651 170.399 128.668V91.3681C170.399 87.6907 170.631 83.7216 172.407 80.6406L164.975 76.3496C163.198 79.4306 162.967 83.3997 162.967 87.0771L162.967 124.377C162.967 126.36 164.04 127.969 165.541 128.836L172.973 133.127Z",fill:"#131313",stroke:"#131313",strokeWidth:"1.64647",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M170.261 125.267V114.74L239.346 75.0625V85.3194L170.261 125.267Z",fill:"#0D0D0D",stroke:"black",strokeWidth:"0.823233"}),k("g",{clipPath:"url(#clip0_1548_70742)",children:[e("path",{d:"M228.362 71.9146C219.392 76.9925 219.392 93.5869 228.362 108.975C237.331 124.363 251.872 132.721 260.842 127.643L249.638 134.081C240.669 139.159 226.128 130.802 217.158 115.414C208.189 100.026 208.189 83.4311 217.158 78.3532L228.362 71.9146Z",fill:"black",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M228.361 71.9146C219.392 76.9925 219.392 93.5869 228.361 108.975C237.331 124.363 251.872 132.721 260.841 127.643C269.811 122.565 269.811 105.97 260.841 90.5822C251.872 75.194 237.331 66.8367 228.361 71.9146ZM234.856 83.0619C239.099 80.6582 245.416 83.268 250.539 89.0026L232.165 99.4117C229.72 92.1618 230.612 85.4657 234.856 83.0619ZM254.343 116.5C250.1 118.904 243.782 116.294 238.659 110.559L257.034 100.15C259.479 107.4 258.586 114.096 254.343 116.5Z",fill:"#FAFD7E",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M234.856 83.0618C239.099 80.658 245.417 83.2678 250.54 89.0024L232.165 99.4115C229.72 92.1617 230.613 85.4655 234.856 83.0618Z",fill:"#FAFD7E",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M254.347 116.5C250.104 118.903 243.787 116.294 238.664 110.559L257.038 100.15C259.483 107.4 258.591 114.096 254.347 116.5Z",fill:"#FAFD7E",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M232.165 99.4115C230.94 95.7844 230.552 92.299 231.001 89.4188C231.449 86.5386 232.734 84.2636 234.856 83.0618C236.977 81.8599 239.617 81.9114 242.368 82.9802L232.165 99.4115Z",fill:"black",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M246.835 116.581C244.084 115.513 241.225 113.426 238.664 110.559L247.853 105.357L257.042 100.154L246.84 116.586L246.835 116.581Z",fill:"black",stroke:"black",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e("defs",{children:e("clipPath",{id:"clip0_1548_70742",children:e("rect",{width:"58",height:"66",fill:"white",transform:"translate(210 70)"})})})]})})})}function hn(){const{t:t}=g(),{showCreditCardWarning:n,setShowCreditCardWarning:a,setPaymentMethod:r}=gt();return e(ne,{size:"threeQuarter",visible:n,showHeaderBar:!1,children:k(ne.Content,{children:[e(_e,{icon:"Close",variant:"tertiary",sx:{pos:"absolute",top:"base.spacing.x5",left:"base.spacing.x5",backdropFilter:"blur(30px)"},onClick:()=>a(!1)}),e(Cn,{}),k(p,{sx:{px:"base.spacing.x12"},children:[e(W,{sx:{marginTop:"base.spacing.x6",marginBottom:"base.spacing.x2",textAlign:"center"},children:t("views.PAYMENT_METHODS.creditCardWarningDrawer.heading")}),e(V,{size:"medium",sx:{display:"block",textAlign:"center",color:"base.color.text.body.secondary",marginBottom:"base.spacing.x13"},children:t("views.PAYMENT_METHODS.creditCardWarningDrawer.body")}),e(Y,{sx:{width:"100%"},testId:"credit-card-button",variant:"primary",size:"large",onClick:()=>{r(h.CREDIT)},children:t("views.PAYMENT_METHODS.creditCardWarningDrawer.ctaButton")})]})]})})}function An(t){const{t:n}=g(),{config:r,items:o,environmentId:s,collectionName:i,excludePaymentTypes:c,excludeFiatCurrencies:d,preferredCurrency:l,hideExcludedPaymentTypes:u,waitFulfillmentSettlements:p=!0}=t,{connectLoaderState:E}=a.useContext(pe),{checkout:m,provider:T}=E,f=a.useRef(),{eventTargetState:{eventTarget:h}}=a.useContext(R),{theme:I}=r,v=a.useMemo((()=>we(I)),[I]),[O,b]=a.useReducer(De,Pe),_=a.useMemo((()=>({viewState:O,viewDispatch:b})),[O,b]),w=O.view.data?.loadingText||n("views.LOADING_VIEW.text");a.useEffect((()=>{m&&T&&(async()=>{const e=await m.getNetworkInfo({provider:T});f.current=e.chainId})()}),[m,T]);const D=a.useRef(!1),P=a.useCallback((()=>{m&&T&&(D.current||(D.current=!0,b({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAYMENT_METHODS}}})))}),[m,T]);return a.useEffect((()=>{m&&T&&P()}),[m,T]),e(y.Provider,{value:_,children:e(At,{value:{config:r,items:o,environment:r.environment,environmentId:s,provider:T,checkout:m,passport:m?.passport,collectionName:i,excludePaymentTypes:c,excludeFiatCurrencies:d,preferredCurrency:l,waitFulfillmentSettlements:p,hideExcludedPaymentTypes:u},children:k(Be,{environment:r.environment,children:[O.view.type===K.LOADING_VIEW&&e(he,{loadingText:w}),O.view.type===Ze.PAYMENT_METHODS&&e(Ht,{}),O.view.type===Ze.PAY_WITH_CARD&&e(Pt,{}),O.view.type===Ze.PAY_WITH_COINS&&e(Wt,{}),O.view.type===Ze.SALE_FAIL&&e(Gt,{biomeTheme:v,errorType:O.view.data?.errorType,transactionHash:O.view.data?.transactionHash,blockExplorerLink:ke.getTransactionLink(f.current,O.view.data?.transactionHash)}),O.view.type===Ze.ORDER_SUMMARY&&e(yn,{subView:O.view.subView}),O.view.type===K.TOP_UP_VIEW&&e(We,{analytics:{userJourney:A.SALE},widgetEvent:ye.IMTBL_SALE_WIDGET_EVENT,checkout:m,provider:T,showOnrampOption:r.isOnRampEnabled,showSwapOption:!1,showBridgeOption:r.isBridgeEnabled,onCloseButtonClick:()=>S(h),onBackButtonClick:()=>{b({payload:{type:C.UPDATE_VIEW,view:{type:Ze.PAYMENT_METHODS}}})},amount:O.view.data?.amount,tokenAddress:O.view.data?.tokenAddress,heading:O.view.data?.heading,subheading:O.view.data?.subheading}),e(hn,{})]})})})}!function(e){e.LOADING="LOADING",e.EXECUTE_SWAP="EXECUTE_SWAP",e.EXECUTE_BRIDGE="EXECUTE_BRIDGE",e.EXECUTE_ON_RAMP="EXECUTE_ON_RAMP",e.SWITCH_NETWORK_ETH="SWITCH_NETWORK_ETH",e.SWITCH_NETWORK_ZKEVM="SWITCH_NETWORK_ZKEVM"}(mn||(mn={}));export{An as default};
@@ -1 +0,0 @@
1
- import{l as e,b6 as t,b7 as o,n as a,b8 as n,a as s,b9 as r,j as i,o as d,ba as l,r as c,as as p,V as u,q as m,t as w,d as f,U as y,x as T,p as E,w as g,K as v,L as A,bb as S,a7 as x,bc as h,H as b,bd as I,be as k,Y as C,A as P,aU as R,v as _,bf as F,G as W,bg as O,bh as D,bi as N,bj as L,z as V,aC as B,bk as U,bl as M,bm as q,E as j,$ as G,bn as z,a3 as H,bo as $,aj as J,ae as K,bp as X,ah as Q,ai as Y,T as Z,R as ee,bq as te,br as oe,bs as ae,bt as ne,aK as se,bu as re,bv as ie,ak as de,I as le}from"./index-BS9il7eh.js";import{S as ce,T as pe,a as ue,F as me,N as we,W as fe,g as ye}from"./balance-DjY7Ic2J.js";import{p as Te,S as Ee,f as ge,C as ve,a as Ae,c as Se,T as xe,b as he}from"./TopUpView-DDi51gWy.js";import{u as be}from"./retry-V19x49_Z.js";import{S as Ie}from"./SpendingCapHero-A_5Bob8g.js";function ke({theme:c,environment:p}){const{t:u}=e(),m=c===t.DARK?o(p,"/quickswapdark.webp"):o(p,"/quickswaplight.webp");return a(s,{testId:"quickswap-footer-container",sx:n,children:[a(s,{testId:"quickswap-logo",sx:r,children:[i(d,{size:"xSmall",sx:{paddingRight:"base.spacing.x1"},children:"By"}),i("img",{style:{height:"26px"},alt:"Quickswap logo",src:m})]}),i(d,{testId:"quickswap-footer-disclaimer-text",size:"xSmall",sx:l,children:u("footers.quickswapFooter.disclaimerText")})]})}const Ce={exchange:null,walletProviderName:null,network:null,tokenBalances:[],supportedTopUps:null,allowedTokens:[]};var Pe;!function(e){e.SET_EXCHANGE="SET_EXCHANGE",e.SET_WALLET_PROVIDER_NAME="SET_WALLET_PROVIDER_NAME",e.SET_NETWORK="SET_NETWORK",e.SET_SUPPORTED_TOP_UPS="SET_SUPPORTED_TOP_UPS",e.SET_TOKEN_BALANCES="SET_TOKEN_BALANCES",e.SET_ALLOWED_TOKENS="SET_ALLOWED_TOKENS"}(Pe||(Pe={}));const Re=c.createContext({swapState:Ce,swapDispatch:()=>{}});Re.displayName="SwapContext";const _e=(e,t)=>{switch(t.payload.type){case Pe.SET_EXCHANGE:return{...e,exchange:t.payload.exchange};case Pe.SET_WALLET_PROVIDER_NAME:return{...e,walletProviderName:t.payload.walletProviderName};case Pe.SET_NETWORK:return{...e,network:t.payload.network};case Pe.SET_SUPPORTED_TOP_UPS:return{...e,supportedTopUps:{isSwapEnabled:t.payload.supportedTopUps.isSwapEnabled??!0,isOnRampEnabled:t.payload.supportedTopUps.isOnRampEnabled??!0,isBridgeEnabled:t.payload.supportedTopUps.isBridgeEnabled??!0}};case Pe.SET_TOKEN_BALANCES:return{...e,tokenBalances:t.payload.tokenBalances};case Pe.SET_ALLOWED_TOKENS:return{...e,allowedTokens:t.payload.allowedTokens};default:return e}},Fe={fromAmountIn:async(e,t,o,a,n)=>{const s=await t.getSigner().getAddress();return e.getUnsignedSwapTxFromAmountIn(s,o.address,n.address,p.from(Te(a,o.decimals)))},fromAmountOut:async(e,t,o,a,n)=>{const s=await t.getSigner().getAddress();return e.getUnsignedSwapTxFromAmountOut(s,n.address,o.address,p.from(Te(a,o.decimals)))}},We={display:"flex",flexDirection:"row",justifyContent:"space-between",columnGap:"base.spacing.x1"},Oe={flex:1},De={flex:2};function Ne({testId:e,options:t,textInputValue:o,textInputPlaceholder:n,textInputValidator:r,textInputType:d,onTextInputChange:l,onTextInputBlur:c,onTextInputFocus:p,textInputTextAlign:u,textInputSubtext:m,textInputErrorMessage:w,testInputMode:f,selectTextAlign:y,selectSubtext:T,selectErrorMessage:E,textInputMaxButtonClick:g,onSelectChange:v,textInputDisabled:A,selectInputDisabled:S,selectedOption:x,coinSelectorHeading:h,defaultTokenImage:b,environment:I,theme:k}){return a(s,{sx:We,children:[i(s,{sx:Oe,children:i(ce,{testId:`${e}-select-form`,options:t,subtext:T,textAlign:y,errorMessage:E,onSelectChange:v,disabled:S,selectedOption:x,coinSelectorHeading:h,defaultTokenImage:b,environment:I,theme:k})}),i(s,{sx:De,children:i(pe,{type:d,testId:`${e}-text-form`,value:o,placeholder:n,subtext:m,textAlign:u,errorMessage:w,validator:r,onTextInputChange:l,onTextInputBlur:c,onTextInputFocus:p,maxButtonClick:g,disabled:A,inputMode:f})})]})}const Le={display:"flex",flexDirection:"column",paddingY:"base.spacing.x6",paddingX:"base.spacing.x4"},Ve={width:"base.icon.size.400"};function Be({loading:t,updateLoading:o,validator:n,transaction:r,data:d,insufficientFundsForGas:l,openNotEnoughImxDrawer:S,openNetworkSwitchDrawer:x}){const{t:h}=e(),[b,I]=c.useState(!1),{viewDispatch:k}=c.useContext(u),{connectLoaderState:C}=c.useContext(m),{checkout:P,provider:R}=C,{track:_}=w(),F=async()=>{const e=n();if(_({userJourney:y.SWAP,screen:"SwapCoins",control:"Swap",controlType:"Button",extras:{swapFromAddress:d?.fromTokenAddress,swapFromAmount:d?.fromAmount,swapFromTokenSymbol:d?.fromTokenSymbol,swapToAddress:d?.toTokenAddress,swapToAmount:d?.toAmount,swapToTokenSymbol:d?.toTokenSymbol,isSwapFormValid:e,hasFundsForGas:!l}}),e&&P&&R&&r)if(l)S();else{try{const e=await R.provider.request({method:"eth_chainId",params:[]});if(parseInt(e.toString())!==T(P.config))return void x()}catch(e){console.error("Current network check failed",e)}if(r)try{o(!0);const e={fromAmount:d?.fromAmount||"",fromTokenAddress:d?.fromTokenAddress||"",toTokenAddress:d?.toTokenAddress||"",toAmount:d?.toAmount||""};if(r.approval)return void k({payload:{type:E.UPDATE_VIEW,view:{type:Ee.APPROVE_ERC20,data:{approveTransaction:r.approval.transaction,transaction:r.swap.transaction,info:r.quote,swapFormInfo:e}}}});const t=await P.sendTransaction({provider:R,transaction:{...r.swap.transaction,gasPrice:g(R)?p.from(0):void 0}});k({payload:{type:E.UPDATE_VIEW,view:{type:Ee.IN_PROGRESS,data:{transactionResponse:t.transactionResponse,swapForm:e}}}})}catch(e){if(console.error(e),o(!1),e.type===v.USER_REJECTED_REQUEST_ERROR)return void I(!0);if(e.type===v.UNPREDICTABLE_GAS_LIMIT)return void k({payload:{type:E.UPDATE_VIEW,view:{type:Ee.PRICE_SURGE,data:d}}});if(e.type===v.TRANSACTION_FAILED||e.type===v.INSUFFICIENT_FUNDS||e.receipt&&0===e.receipt.status)return void k({payload:{type:E.UPDATE_VIEW,view:{type:Ee.FAIL,reason:"Transaction failed",data:d}}});k({payload:{type:E.UPDATE_VIEW,view:{type:A.ERROR_VIEW,error:e}}})}}};return a(s,{sx:Le,children:[i(f,{testId:"swap-button",disabled:t,variant:"primary",onClick:F,size:"large",children:t?i(f.Icon,{icon:"Loading",sx:Ve}):h("views.SWAP.swapForm.buttonText")}),i(ue,{visible:b,showHeaderBar:!1,onCloseDrawer:()=>I(!1),onRetry:()=>{F(),I(!1)}})]})}const Ue={display:"flex",flexDirection:"column",alignItems:"center",paddingTop:"base.spacing.x6",paddingBottom:"base.spacing.x1",height:"100%"},Me={color:"base.color.text.body.secondary",fontFamily:"base.font.family.heading.secondary",textAlign:"center",marginTop:"base.spacing.x4"},qe={display:"flex",flexDirection:"column",justifyContent:"center",gap:"base.spacing.x2",height:"100%",width:"100%"},je={width:"100%",height:"base.spacing.x16"},Ge={display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",paddingTop:"base.spacing.x6"};function ze({environment:t,visible:o,showAdjustAmount:n,hasZeroImx:r,onCloseDrawer:l,onAddCoinsClick:c}){const{t:p}=e(),u=S(t);return i(x,{size:"full",onCloseDrawer:l,visible:o,showHeaderBar:!1,children:i(x.Content,{children:a(s,{testId:"not-enough-gas-bottom-sheet",sx:Ue,children:[i(h,{sx:{w:"base.icon.size.600",h:"base.icon.size.600"},use:i("img",{src:u,alt:p(`drawers.notEnoughImx.content.${r?"noImx":"insufficientImx"}.heading`)})}),i(b,{size:"small",sx:Me,testId:"not-enough-gas-heading",children:p(`drawers.notEnoughImx.content.${r?"noImx":"insufficientImx"}.heading`)}),i(d,{sx:Me,children:p(`drawers.notEnoughImx.content.${r?"noImx":"insufficientImx"}.body`)}),a(s,{sx:qe,children:[n&&i(f,{testId:"not-enough-gas-adjust-amount-button",sx:je,variant:"tertiary",onClick:l,children:p("drawers.notEnoughImx.buttons.adjustAmount")}),i(f,{testId:"not-enough-gas-add-imx-button",sx:je,variant:"tertiary",onClick:c,children:p("drawers.notEnoughImx.buttons.addMoreImx")}),i(f,{sx:je,variant:"tertiary",onClick:l,testId:"not-enough-gas-cancel-button",children:p("drawers.notEnoughImx.buttons.cancel")})]}),i(s,{sx:Ge,children:i(I,{testId:"footer-logo-image",logo:"ImmutableHorizontalLockup",sx:{width:"base.spacing.x25"}})})]})})})}const He={display:"flex",flexDirection:"column",alignItems:"center",paddingTop:"base.spacing.x6",paddingBottom:"base.spacing.x4",paddingX:"base.spacing.x4",height:"100%"},$e={color:"base.color.text.body.secondary",fontFamily:"base.font.family.heading.secondary",textAlign:"center",marginTop:"base.spacing.x4"},Je={display:"flex",flexDirection:"column",justifyContent:"flex-end",alignItems:"center",gap:"base.spacing.x2",height:"100%",width:"100%"},Ke={width:"100%",height:"base.spacing.x16",marginBottom:"base.spacing.x16"},Xe={display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",paddingTop:"base.spacing.x6"},Qe={width:"base.icon.size.600",fill:"base.color.status.fatal.bright"};function Ye({visible:t,onCloseDrawer:o}){const{t:n}=e();return i(x,{size:"full",onCloseDrawer:o,visible:t,showHeaderBar:!1,children:i(x.Content,{children:a(s,{testId:"unable-to-swap-bottom-sheet",sx:He,children:[i(k,{icon:"Alert",testId:"unable-to-swap-icon",variant:"bold",sx:Qe}),i(b,{size:"small",sx:$e,testId:"unable-to-swap-heading",children:n("drawers.unableToSwap.heading")}),i(d,{sx:$e,children:n("drawers.unableToSwap.body")}),i(s,{sx:Je,children:i(f,{sx:Ke,variant:"tertiary",onClick:o,testId:"unable-to-swap-cancel-button",children:n("drawers.unableToSwap.buttons.cancel")})}),i(s,{sx:Xe,children:i(I,{testId:"footer-logo-image",logo:"ImmutableHorizontalLockup",sx:{width:"base.spacing.x25"}})})]})})})}const Ze=(e,t=500)=>{const[o,a]=c.useState(e);return c.useEffect((()=>{const o=setTimeout((()=>{a(e)}),t);return()=>{clearTimeout(o)}}),[e,t]),o};class et{static id=0;promiseId=0;promise;isCancelled=!1;onCancel=null;rejectPromise=()=>{};constructor(e){et.id+=1,this.promiseId=et.id,this.promise=new Promise(((t,o)=>{this.rejectPromise=o,e((e=>{this.isCancelled?o({cancelled:!0}):t(e)}),(e=>{this.isCancelled?o({cancelled:!0}):o(e)}))}))}static all(e){return new et(((t,o)=>{Promise.all(e.map((e=>e instanceof et?e.promise:e))).then(t,o)}))}then(e,t){return new et(((o,a)=>{this.promise.then((t=>o(e?e(t):t)),(e=>t?o(t(e)):a(e)))}))}catch(e){return this.then(void 0,e)}finally(e){return new et(((t,o)=>{this.promise.then(t,o).finally((()=>{e&&e()}))}))}cancel(){this.isCancelled||(this.isCancelled=!0,this.onCancel&&this.onCancel(),this.rejectPromise({cancelled:!0}))}onCancelled(e){this.onCancel=e}get cancelled(){return this.isCancelled}}const tt=(e,t,o)=>{const a=[];if(!e.swap)return a;const n=(e,n,s="≈ ")=>{const r=p.from(e?.value??0);if(e&&r.gt(0)){const i=ge(r,e.token.decimals);a.push({label:n,fiatAmount:`≈ ${o("drawers.feesBreakdown.fees.fiatPricePrefix")}${C(i,e.token.symbol||"",t.conversions)}`,amount:`${P(i)}`,prefix:s,token:e.token})}};return e.swap&&e.swap.gasFeeEstimate&&n(e.swap.gasFeeEstimate,o("drawers.feesBreakdown.fees.swapGasFee.label")),e.approval&&e.approval.gasFeeEstimate&&n(e.approval.gasFeeEstimate,o("drawers.feesBreakdown.fees.approvalFee.label")),e.quote?.fees?.forEach((e=>{n(e.amount,o("drawers.feesBreakdown.fees.swapSecondaryFee.label",{amount:e.basisPoints/100+"%"}),"")})),a},ot=(e,t)=>{if(!R(e))return t;const o={...t};return o.swap?.gasFeeEstimate&&(o.swap.gasFeeEstimate.value=p.from(0)),o.approval?.gasFeeEstimate&&(o.approval.gasFeeEstimate.value=p.from(0)),o},at=(e,t)=>{if(!t.quote.fees)return t;const o=t.quote.fees.map((t=>t.amount.token.symbol?t:{...t,amount:{...t.amount,token:{...t.amount.token,symbol:e.address===t.amount.token.address?e.symbol:t.amount.token.symbol}}}));return{...t,quote:{...t.quote,fees:o}}},nt=(e,t)=>{if(!t.quote.amount&&!t.quote.amountWithMaxSlippage)return t;const o={...t.quote.amount,token:{...t.quote.amount.token,symbol:e.address===t.quote.amount.token.address?e.symbol:t.quote.amount.token.symbol}},a={...t.quote.amountWithMaxSlippage,token:{...t.quote.amountWithMaxSlippage.token,symbol:e.address===t.quote.amountWithMaxSlippage.token.address?e.symbol:t.quote.amountWithMaxSlippage.token.symbol}};return{...t,quote:{...t.quote,amount:o,amountWithMaxSlippage:a}}},st=(e,t,o,a,n)=>{const s=o.quote.fees[0],r=t,i=o.quote.amount.token,d=parseFloat(e),l=Te(d.toString(),r.decimals),c=p.from(o.quote.amount.value),u=r.decimals,m=o.quote.amount.token.decimals,w=Math.max(u,m),f=p.from("10").pow(w-u),y=p.from("10").pow(w-m),T=l.mul(f),E=c.mul(y),g=E.div(T),v=E.mod(T),A=p.from("10").pow(w),S=v.mul(A).div(T),x=g.mul(A).add(S),h=_(P(ge(x,w)),!0);return n(a,{fromSymbol:r.symbol,toSymbol:i.symbol,rate:h,fee:(s?.basisPoints??0)/100})};var rt;!function(e){e.FROM="FROM",e.TO="TO"}(rt||(rt={}));const it=(e,t)=>void 0!==e&&(""!==e&&t!==e);let dt;function lt({data:t,theme:o}){const{t:n}=e(),{swapState:{allowedTokens:r,exchange:d,tokenBalances:l,network:f}}=c.useContext(Re),{connectLoaderState:v}=c.useContext(m),{checkout:S,provider:x}=v,h=F(S?.config.environment,o),I=c.useCallback(((e,t)=>W(t)?O:`${e.toLowerCase()}-${t.toLowerCase()}`),[]),{cryptoFiatState:R,cryptoFiatDispatch:j}=c.useContext(ve),{viewDispatch:G}=c.useContext(u),[z,H]=c.useState(rt.FROM),[$,J]=c.useState(!1),{track:K}=w(),[X,Q]=c.useState(t?.fromAmount||""),[Y,Z]=c.useState(""),ee=Ze(X,U),[te,oe]=c.useState(),[ae,ne]=c.useState(""),[se,re]=c.useState(""),[ie,de]=c.useState(0),[le,ce]=c.useState(t?.toAmount||""),[pe,ue]=c.useState(""),fe=Ze(le,U),[ye,Ee]=c.useState(),[xe,he]=c.useState(""),[Ie,ke]=c.useState(""),[Ce,Pe]=c.useState(null),[_e,We]=c.useState(""),[Oe,De]=c.useState(void 0),[Le,Ve]=c.useState(""),[Ue,Me]=c.useState([]),qe=c.useMemo((()=>Ce?tt(Ce,R,n):[]),[Ce,R,n]),[je,Ge]=c.useState(null),[He,$e]=c.useState(""),Je=c.useMemo((()=>Ce&&He&&je?st(He,je,Ce,"views.SWAP.swapForm.conversionRate",n):""),[He,je,Ce,n]),[Ke,Xe]=c.useState(!1),[Qe,lt]=c.useState(!1),[ct,pt]=c.useState(!1);c.useEffect((()=>{if(0===l.length)return;if(!f)return;const e=l.filter((e=>e.balance.gt(0))).map((e=>({id:I(e.token.symbol,e.token.address),name:e.token.name,symbol:e.token.symbol,icon:e.token.icon,balance:{formattedAmount:P(e.formattedBalance),formattedFiatAmount:0===R.conversions.size?_(""):C(e.formattedBalance,e.token.symbol||"",R.conversions)}})));Me(e),t?.fromTokenAddress&&!te&&(oe(r.find((e=>W(e.address)&&t?.fromTokenAddress?.toLowerCase()===O||e.address?.toLowerCase()===t?.fromTokenAddress?.toLowerCase()))),ne(l.find((e=>W(e.token.address)&&t?.fromTokenAddress?.toLowerCase()===O||e.token.address?.toLowerCase()===t?.fromTokenAddress?.toLowerCase()))?.formattedBalance??"")),it(t?.toTokenAddress,t?.fromTokenAddress)&&!ye&&Ee(r.find((e=>W(e.address)&&t?.toTokenAddress?.toLowerCase()===O||e.address?.toLowerCase()===t?.toTokenAddress?.toLowerCase())))}),[l,r,R.conversions,t?.fromTokenAddress,t?.toTokenAddress,oe,ne,Ee,Me,I,_,f]);const ut=c.useMemo((()=>r.map((e=>({id:I(e.symbol,e.address),name:e.name,symbol:e.symbol,icon:e.icon})))),[r,te]);c.useEffect((()=>{j({payload:{type:Ae.SET_TOKEN_SYMBOLS,tokenSymbols:r.map((e=>e.symbol))}})}),[j,r]);const mt=()=>{Z(""),re(""),ue(""),he("")},wt=()=>{dt&&dt.cancel(),$e(""),Ge(null),Ve(""),Pe(null)},ft=(e,t)=>!Number.isNaN(parseFloat(e))&&(!(parseFloat(e)<=0)&&(!!te&&(!!ye&&(!t||!$)))),yt=async(e=!1)=>{ft(X,e)&&(dt&&dt.cancel(),e||J(!0),await(async(e=!1)=>{if(x&&d&&te&&ye){try{const e=Fe.fromAmountIn(d,x,te,X,ye),t=et.all([e]);dt=t;const o=await t;let a=ot(x,o[0]);a=at(te,a),a=nt(ye,a);const n=a.swap.gasFeeEstimate;let s=p.from(n?.value||0);a.approval?.gasFeeEstimate&&(s=s.add(a.approval.gasFeeEstimate.value));const i=ge(s,q),l=n?.token,c=r.find((e=>e.address?.toLocaleLowerCase()===l?.address?.toLocaleLowerCase()));Ge(te),$e(X),Pe(a),We(i),De({name:c?.name||"",symbol:c?.symbol||"",decimals:c?.decimals||0,address:c?.address,icon:c?.icon}),Ve(C(i,c?.symbol||"",R.conversions)),ce(_(P(ge(a.quote.amount.value,a.quote.amount.token.decimals),a.quote.amount.token.decimals))),mt()}catch(e){e.cancelled||(console.error("Error fetching quote.",e),wt(),Xe(!1),lt(!0))}e||J(!1)}})(e))},Tt=(e,t)=>!Number.isNaN(parseFloat(e))&&(!(parseFloat(e)<=0)&&(!!te&&(!!ye&&(!t||!$)))),Et=async(e=!1)=>{Tt(le,e)&&(dt&&dt.cancel(),e||J(!0),await(async(e=!1)=>{if(x&&d&&te&&ye){try{const e=Fe.fromAmountOut(d,x,ye,le,te),t=et.all([e]);dt=t;const o=await t;let a=ot(x,o[0]);a=at(te,a);const n=a.swap.gasFeeEstimate;let s=p.from(n?.value||0);a.approval?.gasFeeEstimate&&(s=s.add(a.approval.gasFeeEstimate.value));const i=ge(s,q),l=n?.token,c=r.find((e=>e.symbol===l?.symbol));Ge(ye),$e(le),Pe(a),We(i),De({name:c?.name||"",symbol:c?.symbol||"",decimals:c?.decimals||0,address:c?.address,icon:c?.icon}),Ve(C(i,c?.symbol||"",R.conversions)),Q(_(P(ge(a.quote.amount.value,a.quote.amount.token.decimals)))),mt()}catch(e){e.cancelled||(wt(),Xe(!1),lt(!0))}e||J(!1)}})(e))},gt=async(e=!1)=>{z===rt.FROM?await yt(e):await Et(e)};be((()=>gt(!0)),D),c.useEffect((()=>{if(z===rt.FROM){if(ee<=0)return J(!1),void wt();(async()=>{await gt()})()}}),[ee,te,ye,ie]),c.useEffect((()=>{if(z===rt.TO){if(fe<=0)return J(!1),void wt();(async()=>{await gt()})()}}),[fe,ye,te]);const vt=c.useMemo((()=>{if(!x)return!0;if(g(x))return!1;const e=l.find((e=>e.token.address?.toLowerCase()===O));if(!e)return!0;const t=te?.address?.toLowerCase()===O,o=Se(0!==_e.length?_e:"0"),a=t&&!Number.isNaN(parseFloat(X))?Te(X,te?.decimals||18):p.from("0");return o.add(a).gt(e.balance)}),[_e,l,te,X,x]);c.useEffect((()=>{X&&te&&ke(C(X,te.symbol,R.conversions))}),[X,te,R.conversions]);const At=c.useCallback((e=>{const t=l.find((t=>e===I(t.token.symbol,t.token.address)));t&&(ye&&e===I(ye.symbol,ye?.address)&&Ee(void 0),oe(t.token),ne(t.formattedBalance),re(""))}),[ye]),St=c.useCallback((e=>{const t=r.find((t=>e===I(t.symbol,t.address)));t&&(te&&e===I(te.symbol,te?.address)&&oe(void 0),Ee(t),he(""))}),[te]);return a(B,{children:[a(s,{sx:{paddingX:"base.spacing.x4",marginBottom:"base.spacing.x2"},children:[i(b,{size:"small",weight:"regular",sx:{paddingBottom:"base.spacing.x4"},children:n("views.SWAP.content.title")}),a(s,{sx:{display:"flex",flexDirection:"column",rowGap:"base.spacing.x6",paddingBottom:"base.spacing.x2"},children:[a(s,{children:[i(b,{size:"xSmall",sx:{display:"flex",justifyContent:"space-between",paddingBottom:"base.spacing.x1"},children:n("views.SWAP.swapForm.from.label")}),i(Ne,{testId:"fromTokenInputs",options:Ue,selectSubtext:te?`${n("views.SWAP.content.availableBalancePrefix")} ${P(ae)}`:"",selectTextAlign:"left",textInputType:"number",testInputMode:"decimal",textInputValue:X,textInputPlaceholder:n("views.SWAP.swapForm.from.inputPlaceholder"),textInputSubtext:`${n("views.SWAP.content.fiatPricePrefix")} \n $${_(Ie,!0)}`,textInputTextAlign:"right",textInputValidator:N,onTextInputChange:e=>{var t;(t=e)!==X&&(mt(),wt(),ce(""),ft(t,!1)&&J(!0),Q(t))},onTextInputFocus:()=>{H(rt.FROM)},textInputMaxButtonClick:()=>{if(!ae)return;const e=ae.slice(0,ae.indexOf(".")+M+1);mt(),wt(),H(rt.FROM),ce(""),ft(e,!1)&&J(!0),X===e?de(ie+1):Q(e),K({userJourney:y.SWAP,screen:"SwapCoins",control:"MaxFrom",controlType:"Button",extras:{fromBalance:ae,fromBalanceTruncated:e}})},onSelectChange:At,textInputErrorMessage:n(Y),selectErrorMessage:n(se),selectedOption:te?I(te.symbol,te.address):void 0,coinSelectorHeading:n("views.SWAP.swapForm.from.selectorTitle"),defaultTokenImage:h,environment:S?.config.environment,theme:o})]}),a(s,{children:[a(s,{sx:{display:"flex",justifyContent:"space-between",paddingBottom:"base.spacing.x1"},children:[i(b,{size:"xSmall",children:n("views.SWAP.swapForm.to.label")}),Je?.length>0&&a(L,{children:[i(L.Target,{children:i(k,{icon:"InformationCircle",sx:{w:"base.icon.size.300"}})}),i(L.Content,{children:Je})]})]}),i(Ne,{testId:"toTokenInputs",options:ut,selectTextAlign:"left",textInputType:"number",testInputMode:"decimal",textInputValue:le,textInputPlaceholder:n("views.SWAP.swapForm.to.inputPlaceholder"),textInputTextAlign:"right",textInputValidator:N,onTextInputChange:e=>{var t;(t=e)!==le&&(mt(),wt(),ke(""),Q(""),Tt(t,!1)&&J(!0),ce(t))},onTextInputFocus:()=>{H(rt.TO)},onSelectChange:St,textInputErrorMessage:n(pe),selectErrorMessage:n(xe),selectedOption:ye?I(ye.symbol,ye.address):void 0,coinSelectorHeading:n("views.SWAP.swapForm.to.selectorTitle"),defaultTokenImage:h,environment:S?.config.environment,theme:o})]})]}),!g(x)&&i(me,{gasFeeFiatValue:Le,gasFeeToken:Oe,gasFeeValue:_e,fees:qe,onFeesClick:()=>{K({userJourney:y.SWAP,screen:"SwapCoins",control:"ViewFees",controlType:"Button"})},sx:{paddingBottom:"0"},loading:$})]}),i(Be,{validator:()=>{const e=function(e){return e?"":"views.SWAP.validation.noFromTokenSelected"}(te),t=(a=ae,(o=X)&&0!==parseFloat(o)?a&&Number(o)>Number(a)?"views.SWAP.validation.insufficientBalance":"":"views.SWAP.validation.noAmountInputted");var o,a;const n=function(e){return e?"":"views.SWAP.validation.noToTokenSelected"}(ye),s=function(e){return e&&0!==parseFloat(e)?"":"views.SWAP.validation.noAmountInputted"}(le);z===rt.FROM?(ue(""),t&&Z(t)):z===rt.TO&&(Z(""),s&&ue(s)),e&&re(e),n&&he(n);let r=!0;return(e||n||t&&z===rt.FROM||s&&z===rt.TO)&&(r=!1),K({userJourney:y.SWAP,screen:"SwapCoins",control:"FormValid",controlType:"Button",extras:{isSwapFormValid:r,swapFromAddress:te?.address,swapFromAmount:X,swapFromTokenSymbol:te?.symbol,swapToAddress:ye?.address,swapToAmount:le,swapToTokenSymbol:ye?.symbol}}),r},updateLoading:e=>{J(e)},loading:$,transaction:Ce,data:{fromAmount:X,toAmount:le,fromTokenSymbol:te?.symbol,fromTokenAddress:te?.address,toTokenSymbol:ye?.symbol,toTokenAddress:ye?.address},insufficientFundsForGas:vt,openNotEnoughImxDrawer:()=>{lt(!1),Xe(!0)},openNetworkSwitchDrawer:()=>pt(!0)}),i(ze,{environment:S?.config.environment??V.PRODUCTION,visible:Ke,showAdjustAmount:te?.address===O,hasZeroImx:!1,onAddCoinsClick:()=>{G({payload:{type:E.UPDATE_VIEW,view:{type:A.TOP_UP_VIEW},currentViewData:{fromTokenAddress:te?.address??"",fromAmount:X,toTokenAddress:ye?.address??""}}})},onCloseDrawer:()=>Xe(!1)}),i(Ye,{visible:Qe,onCloseDrawer:()=>{lt(!1),oe(void 0),Q(""),Ee(void 0),ce("")}}),i(we,{visible:ct,targetChainId:T(S?.config),provider:x,checkout:S,onCloseDrawer:()=>pt(!1)})]})}const ct=(e,t)=>{if(0===e.length)return!0;let o=!1;return e.forEach((e=>{e.token.symbol===t&&e.balance.eq(0)&&(o=!0)})),o};function pt({theme:t,fromAmount:o,toAmount:n,fromTokenAddress:r,toTokenAddress:d}){const{t:l}=e(),{viewDispatch:p}=c.useContext(u),{eventTargetState:{eventTarget:f}}=c.useContext(j),{swapState:{tokenBalances:T}}=c.useContext(Re),{connectLoaderState:{checkout:v,provider:S}}=c.useContext(m),[x,h]=c.useState(!1),{page:b}=w();return c.useEffect((()=>{b({userJourney:y.SWAP,screen:"SwapCoins",extras:{fromAmount:o,toAmount:n,fromTokenAddress:r,toTokenAddress:d}})}),[]),c.useEffect((()=>{ct(T,$)&&!g(S)&&h(!0)}),[T]),i(H,{header:i(G,{title:l("views.SWAP.header.title"),onCloseButtonClick:()=>z(f)}),footer:i(ke,{environment:v?.config.environment,theme:t}),children:a(s,{sx:{height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[i(lt,{data:{fromAmount:o,toAmount:n,fromTokenAddress:r,toTokenAddress:d},theme:t}),i(ze,{environment:v?.config.environment??V.PRODUCTION,visible:x,showAdjustAmount:!1,hasZeroImx:!0,onAddCoinsClick:()=>{p({payload:{type:E.UPDATE_VIEW,view:{type:A.TOP_UP_VIEW}}})},onCloseDrawer:()=>{h(!1)}})]})})}function ut({transactionResponse:t,swapForm:o}){const{t:a}=e(),{viewDispatch:n}=c.useContext(u),{page:s}=w();return c.useEffect((()=>{s({userJourney:y.SWAP,screen:"SwapInProgress",extras:{swapFormInfo:o}})}),[]),c.useEffect((()=>{(async()=>{try{const e=await t.wait();if(1===e.status)return void n({payload:{type:E.UPDATE_VIEW,view:{type:Ee.SUCCESS,data:{fromTokenAddress:o.fromTokenAddress,fromAmount:o.fromAmount,toTokenAddress:o.toTokenAddress,toAmount:o.toAmount||"",transactionHash:e.transactionHash}}}});n({payload:{type:E.UPDATE_VIEW,view:{type:Ee.FAIL,data:o,reason:"Transaction failed"}}})}catch{n({payload:{type:E.UPDATE_VIEW,view:{type:Ee.FAIL,data:o,reason:"Transaction failed"}}})}})()}),[t]),i(J,{loadingText:a("views.SWAP.IN_PROGRESS.loading.text")})}function mt({data:t}){const{t:o}=e(),{swapState:{allowedTokens:n}}=c.useContext(Re),{connectLoaderState:r}=c.useContext(m),{checkout:d,provider:l}=r,{viewDispatch:f}=c.useContext(u),{eventTargetState:{eventTarget:T}}=c.useContext(j),S=g(l),[x,h]=c.useState(!1),[b,I]=c.useState(!1),[k,C]=c.useState(!1),[P,R]=c.useState(!1),[_,F]=c.useState(!1),[W,O]=c.useState(!1),{page:D,track:N}=w();c.useEffect((()=>{D({userJourney:y.SWAP,screen:"ApproveERC20",extras:{swapFormInfo:t.swapFormInfo}})}),[]);const L=c.useMemo((()=>n.find((e=>e.address===t.swapFormInfo.fromTokenAddress))),[n,t.swapFormInfo.fromTokenAddress]),V=c.useCallback((()=>{f({payload:{type:E.UPDATE_VIEW,view:{type:A.ERROR_VIEW,error:new Error("No checkout object or no provider object found")}}})}),[f]),U=c.useCallback((()=>{f({payload:{type:E.UPDATE_VIEW,view:{type:Ee.SWAP,data:t.swapFormInfo}}})}),[f]),M=(e,t)=>{e.type!==v.UNPREDICTABLE_GAS_LIMIT?e.type===v.TRANSACTION_FAILED||e.type===v.INSUFFICIENT_FUNDS||e.receipt&&0===e.receipt.status?f({payload:{type:E.UPDATE_VIEW,view:{type:Ee.FAIL,reason:"Transaction failed",data:t}}}):(console.error("Approve ERC20 failed",e),f({payload:{type:E.UPDATE_VIEW,view:{type:A.ERROR_VIEW,error:e}}})):f({payload:{type:E.UPDATE_VIEW,view:{type:Ee.PRICE_SURGE,data:t}}})},q=(e,t=!1)=>({...e,gasPrice:t?p.from(0):void 0}),$=c.useCallback((async()=>{if(!P)if(N({userJourney:y.SWAP,screen:"ApproveERC20",control:"ApproveSpending",controlType:"Button"}),R(!0),d&&l){if(!x){h(!0);try{const e=await d.sendTransaction({provider:l,transaction:q(t.approveTransaction,S)});I(!0);if(1!==(await e.transactionResponse.wait()).status)return void f({payload:{type:E.UPDATE_VIEW,view:{type:Ee.FAIL,data:t.swapFormInfo}}});I(!1),h(!1),C(!0)}catch(e){if(I(!1),h(!1),e.type===v.USER_REJECTED_REQUEST_ERROR)return void F(!0);M(e,t.swapFormInfo)}finally{R(!1)}}}else V()}),[d,l,V,f,O,t.approveTransaction,t.swapFormInfo,x,h,I]),Q=c.useMemo((()=>a(K,{heading:o(`views.APPROVE_ERC20.approveSpending.content.${S?"passport":"metamask"}.heading`),children:[S&&i(s,{children:o("views.APPROVE_ERC20.approveSpending.content.passport.body")}),!S&&i(s,{children:o("views.APPROVE_ERC20.approveSpending.content.metamask.body",{amount:`${t.swapFormInfo.fromAmount} ${L?.symbol||""}`})})]})),[t.swapFormInfo,L,S]),Y=c.useMemo((()=>i(X,{loading:P,actionText:o(_?"views.APPROVE_ERC20.approveSpending.footer.retryText":"views.APPROVE_ERC20.approveSpending.footer.buttonText"),onActionClick:$})),[_,$,P]),Z=c.useCallback((async()=>{if(!P)if(N({userJourney:y.SWAP,screen:"ApproveERC20",control:"ApproveSwap",controlType:"Button"}),R(!0),d&&l){if(!x){h(!0);try{const e=await d.sendTransaction({provider:l,transaction:q(t.transaction,S)});h(!1),f({payload:{type:E.UPDATE_VIEW,view:{type:Ee.IN_PROGRESS,data:{transactionResponse:e.transactionResponse,swapForm:t.swapFormInfo}}}})}catch(e){if(h(!1),e.type===v.USER_REJECTED_REQUEST_ERROR)return void O(!0);M(e,t.swapFormInfo)}finally{R(!1)}}}else V()}),[d,l,V,f,O,t.transaction,t.swapFormInfo,x,h]),ee=i(K,{heading:o("views.APPROVE_ERC20.approveSwap.content.heading"),children:i(s,{children:o("views.APPROVE_ERC20.approveSwap.content.body")})}),te=c.useMemo((()=>i(X,{loading:P,actionText:o(W?"views.APPROVE_ERC20.approveSwap.footer.retryText":"views.APPROVE_ERC20.approveSwap.footer.buttonText"),onActionClick:Z})),[W,Z,P]);return a(B,{children:[b&&i(J,{loadingText:o("views.APPROVE_ERC20.approveSpending.loading.text")}),!b&&i(H,{header:i(G,{transparent:!0,showBack:!0,onCloseButtonClick:()=>z(T),onBackButtonClick:U}),floatHeader:!0,heroContent:i(k?fe:Ie,{}),footer:k?te:Y,children:k?ee:Q})]})}function wt({amount:t,fromTokenAddress:o,toTokenAddress:n,config:s}){const{t:r}=e(),{eventTargetState:{eventTarget:d}}=c.useContext(j),{environment:l,theme:p,isOnRampEnabled:f,isSwapEnabled:g,isBridgeEnabled:v}=s,{connectLoaderState:{checkout:S,provider:x}}=c.useContext(m),[h,b]=c.useReducer(Q,{...Y,history:[]}),[I,k]=c.useReducer(_e,Ce),{page:C}=w(),[P,R]=c.useState(!1),_=c.useMemo((()=>({swapState:I,swapDispatch:k})),[I,k]),F=c.useMemo((()=>({viewState:h,viewDispatch:b})),[h,b]),W=c.useCallback(((e,t)=>{b({payload:{type:E.UPDATE_VIEW,view:{type:A.ERROR_VIEW,tryAgain:t,error:e}}})}),[b]),O=c.useCallback((()=>{b({payload:{type:E.UPDATE_VIEW,view:{type:Ee.SWAP}}})}),[b]),D=c.useCallback((async()=>{if(!S)throw new Error("loadBalances: missing checkout");if(!x)throw new Error("loadBalances: missing provider");try{const e=await ye({checkout:S,provider:x,allowTokenListType:Z.SWAP});if(void 0===e)return!1;k({payload:{type:Pe.SET_ALLOWED_TOKENS,allowedTokens:e.allowList.tokens}}),k({payload:{type:Pe.SET_TOKEN_BALANCES,tokenBalances:e.allowedBalances}})}catch(e){if(ee.nonRetryable(e))return W(e,D),!1}return!0}),[S,x]);return c.useEffect((()=>{(async()=>{if(!S||!x)return;const e=await S.getNetworkInfo({provider:x});if(e.chainId!==T(S.config))return;let t;try{t=await S.config.remote.getConfig("dex")}catch(e){return void W(e)}const o=new te({chainId:e.chainId,baseConfig:new oe({environment:l}),secondaryFees:t.secondaryFees,overrides:t.overrides});k({payload:{type:Pe.SET_EXCHANGE,exchange:o}}),k({payload:{type:Pe.SET_NETWORK,network:e}}),await D()&&h.view.type===A.LOADING_VIEW&&O()})()}),[S,x]),i(u.Provider,{value:F,children:i(Re.Provider,{value:_,children:a(he,{environment:l,children:[h.view.type===A.LOADING_VIEW&&i(J,{loadingText:r("views.LOADING_VIEW.text")}),h.view.type===Ee.SWAP&&i(pt,{theme:p,fromAmount:h.view.data?.fromAmount??t,fromTokenAddress:h.view.data?.fromTokenAddress??o,toTokenAddress:h.view.data?.toTokenAddress??n}),h.view.type===Ee.IN_PROGRESS&&i(ut,{transactionResponse:h.view.data.transactionResponse,swapForm:h.view.data.swapForm}),h.view.type===Ee.APPROVE_ERC20&&i(mt,{data:h.view.data}),h.view.type===Ee.SUCCESS&&i(ae,{statusText:r("views.SWAP.success.text"),actionText:r("views.SWAP.success.actionText"),onRenderEvent:()=>{C({userJourney:y.SWAP,screen:"SwapSuccess",extras:{fromTokenAddress:h.view.data?.fromTokenAddress,fromAmount:h.view.data?.fromAmount,toTokenAddress:h.view.data?.toTokenAddress,toAmount:h.view.data?.toAmount}}),ne(d,h.view.data.transactionHash)},onActionClick:()=>z(d),statusType:se.SUCCESS,testId:"success-view"}),h.view.type===Ee.FAIL&&i(ae,{statusText:r("views.SWAP.failed.text"),actionText:r("views.SWAP.failed.actionText"),onRenderEvent:()=>{C({userJourney:y.SWAP,screen:"SwapFailed"}),re(d,"Transaction failed")},onActionClick:()=>{h.view.type===Ee.FAIL&&b({payload:{type:E.UPDATE_VIEW,view:{type:Ee.SWAP,data:h.view.data}}})},statusType:se.FAILURE,onCloseClick:()=>z(d),testId:"fail-view"}),h.view.type===Ee.PRICE_SURGE&&i(ae,{statusText:r("views.SWAP.rejected.text"),actionText:r("views.SWAP.rejected.actionText"),onRenderEvent:()=>{C({userJourney:y.SWAP,screen:"PriceSurge"}),ie(d,"Price surge")},onActionClick:()=>{h.view.type===Ee.PRICE_SURGE&&b({payload:{type:E.UPDATE_VIEW,view:{type:Ee.SWAP,data:h.view.data}}})},statusType:se.WARNING,onCloseClick:()=>z(d),testId:"price-surge-view"}),h.view.type===A.ERROR_VIEW&&i(de,{actionText:r("views.ERROR_VIEW.actionText"),onActionClick:async()=>{R(!0);const e=h.view;if(!e.tryAgain)return O(),void R(!1);await e.tryAgain()&&O(),R(!1)},onCloseClick:()=>z(d),errorEventActionLoading:P}),h.view.type===A.TOP_UP_VIEW&&i(xe,{analytics:{userJourney:y.SWAP},checkout:S,provider:x,widgetEvent:le.IMTBL_SWAP_WIDGET_EVENT,showOnrampOption:f,showSwapOption:g,showBridgeOption:v,onCloseButtonClick:()=>z(d)})]})})})}export{wt as default};
@@ -1 +0,0 @@
1
- import{as as t,co as e,cp as n,cq as o,cr as i,cs as r,ct as s,r as a,z as c,bF as l,j as u,n as d,M as f,a as m,l as h,V as E,E as p,t as g,bZ as S,$ as v,H as _,o as w,a3 as A,I,p as T,F as b}from"./index-BS9il7eh.js";const C=new e(n),O={},y=t.from(0),R=t.from(-1);function x(t,n,o,i){const r={fault:n,operation:o};return void 0!==i&&(r.value=i),C.throwError(t,e.errors.NUMERIC_FAULT,r)}let N="0";for(;N.length<256;)N+=N;function F(e){if("number"!=typeof e)try{e=t.from(e).toNumber()}catch(t){}return"number"==typeof e&&e>=0&&e<=256&&!(e%1)?"1"+N.substring(0,e):C.throwArgumentError("invalid decimal size","decimals",e)}function P(e,n){null==n&&(n=0);const o=F(n),i=(e=t.from(e)).lt(y);i&&(e=e.mul(R));let r=e.mod(o).toString();for(;r.length<o.length-1;)r="0"+r;r=r.match(/^([0-9]*[1-9]|0)(0*)/)[1];const s=e.div(o).toString();return e=1===o.length?s:s+"."+r,i&&(e="-"+e),e}function L(e,n){null==n&&(n=0);const o=F(n);"string"==typeof e&&e.match(/^-?[0-9.]+$/)||C.throwArgumentError("invalid decimal value","value",e);const i="-"===e.substring(0,1);i&&(e=e.substring(1)),"."===e&&C.throwArgumentError("missing value","value",e);const r=e.split(".");r.length>2&&C.throwArgumentError("too many decimal points","value",e);let s=r[0],a=r[1];for(s||(s="0"),a||(a="0");"0"===a[a.length-1];)a=a.substring(0,a.length-1);for(a.length>o.length-1&&x("fractional component exceeds decimals","underflow","parseFixed"),""===a&&(a="0");a.length<o.length-1;)a+="0";const c=t.from(s),l=t.from(a);let u=c.mul(o).add(l);return i&&(u=u.mul(R)),u}class U{constructor(t,n,o,i){t!==O&&C.throwError("cannot use FixedFormat constructor; use FixedFormat.from",e.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.signed=n,this.width=o,this.decimals=i,this.name=(n?"":"u")+"fixed"+String(o)+"x"+String(i),this._multiplier=F(i),Object.freeze(this)}static from(t){if(t instanceof U)return t;"number"==typeof t&&(t=`fixed128x${t}`);let e=!0,n=128,o=18;if("string"==typeof t)if("fixed"===t);else if("ufixed"===t)e=!1;else{const i=t.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);i||C.throwArgumentError("invalid fixed format","format",t),e="u"!==i[1],n=parseInt(i[2]),o=parseInt(i[3])}else if(t){const i=(e,n,o)=>null==t[e]?o:(typeof t[e]!==n&&C.throwArgumentError("invalid fixed format ("+e+" not "+n+")","format."+e,t[e]),t[e]);e=i("signed","boolean",e),n=i("width","number",n),o=i("decimals","number",o)}return n%8&&C.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),o>80&&C.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",o),new U(O,e,n,o)}}class k{constructor(t,n,o,i){t!==O&&C.throwError("cannot use FixedNumber constructor; use FixedNumber.from",e.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=n,this._value=o,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(t){this.format.name!==t.format.name&&C.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",t)}addUnsafe(t){this._checkFormat(t);const e=L(this._value,this.format.decimals),n=L(t._value,t.format.decimals);return k.fromValue(e.add(n),this.format.decimals,this.format)}subUnsafe(t){this._checkFormat(t);const e=L(this._value,this.format.decimals),n=L(t._value,t.format.decimals);return k.fromValue(e.sub(n),this.format.decimals,this.format)}mulUnsafe(t){this._checkFormat(t);const e=L(this._value,this.format.decimals),n=L(t._value,t.format.decimals);return k.fromValue(e.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(t){this._checkFormat(t);const e=L(this._value,this.format.decimals),n=L(t._value,t.format.decimals);return k.fromValue(e.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){const t=this.toString().split(".");1===t.length&&t.push("0");let e=k.from(t[0],this.format);const n=!t[1].match(/^(0*)$/);return this.isNegative()&&n&&(e=e.subUnsafe(W.toFormat(e.format))),e}ceiling(){const t=this.toString().split(".");1===t.length&&t.push("0");let e=k.from(t[0],this.format);const n=!t[1].match(/^(0*)$/);return!this.isNegative()&&n&&(e=e.addUnsafe(W.toFormat(e.format))),e}round(t){null==t&&(t=0);const e=this.toString().split(".");if(1===e.length&&e.push("0"),(t<0||t>80||t%1)&&C.throwArgumentError("invalid decimal count","decimals",t),e[1].length<=t)return this;const n=k.from("1"+N.substring(0,t),this.format),o=D.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(o).floor().divUnsafe(n)}isZero(){return"0.0"===this._value||"0"===this._value}isNegative(){return"-"===this._value[0]}toString(){return this._value}toHexString(e){if(null==e)return this._hex;e%8&&C.throwArgumentError("invalid byte width","width",e);const n=t.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return o(n,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(t){return k.fromString(this._value,t)}static fromValue(t,e,n){return null!=n||null==e||i(e)||(n=e,e=null),null==e&&(e=0),null==n&&(n="fixed"),k.fromString(P(t,e),U.from(n))}static fromString(t,e){null==e&&(e="fixed");const n=U.from(e),i=L(t,n.decimals);!n.signed&&i.lt(y)&&x("unsigned value cannot be negative","overflow","value",t);let r=null;n.signed?r=i.toTwos(n.width).toHexString():(r=i.toHexString(),r=o(r,n.width/8));const s=P(i,n.decimals);return new k(O,r,s,n)}static fromBytes(e,n){null==n&&(n="fixed");const o=U.from(n);if(r(e).length>o.width/8)throw new Error("overflow");let i=t.from(e);o.signed&&(i=i.fromTwos(o.width));const s=i.toTwos((o.signed?0:1)+o.width).toHexString(),a=P(i,o.decimals);return new k(O,s,a,o)}static from(t,n){if("string"==typeof t)return k.fromString(t,n);if(s(t))return k.fromBytes(t,n);try{return k.fromValue(t,0,n)}catch(t){if(t.code!==e.errors.INVALID_ARGUMENT)throw t}return C.throwArgumentError("invalid FixedNumber value","value",t)}static isFixedNumber(t){return!(!t||!t._isFixedNumber)}}const W=k.from(1),D=k.from("0.5"),B=new e("units/5.7.0"),V=["wei","kwei","mwei","gwei","szabo","finney","ether"];function M(t,e){if("string"==typeof e){const t=V.indexOf(e);-1!==t&&(e=3*t)}return P(t,null!=e?e:18)}function $(t,e){if("string"!=typeof t&&B.throwArgumentError("value must be a string","value",t),"string"==typeof e){const t=V.indexOf(e);-1!==t&&(e=3*t)}return L(t,null!=e?e:18)}function G(t){return $(t,18)}var K;!function(t){t.USD="usd"}(K||(K={}));const H={cryptoFiat:null,fiatSymbol:K.USD,tokenSymbols:[],conversions:new Map};var Y;!function(t){t.SET_CRYPTO_FIAT="SET_CRYPTO_FIAT",t.SET_FIAT_SYMBOL="SET_FIAT_SYMBOL",t.SET_TOKEN_SYMBOLS="SET_TOKEN_SYMBOLS",t.SET_CONVERSIONS="SET_CONVERSIONS"}(Y||(Y={}));const z=a.createContext({cryptoFiatState:H,cryptoFiatDispatch:()=>{}}),j=(t,e)=>{switch(e.payload.type){case Y.SET_CRYPTO_FIAT:return{...t,cryptoFiat:e.payload.cryptoFiat};case Y.SET_FIAT_SYMBOL:return{...t,fiatSymbol:e.payload.fiatSymbol};case Y.SET_TOKEN_SYMBOLS:return{...t,tokenSymbols:e.payload.tokenSymbols};case Y.SET_CONVERSIONS:return{...t,conversions:e.payload.conversions};default:return t}};var q;!function(t){t.SWAP="SWAP",t.IN_PROGRESS="IN_PROGRESS",t.SUCCESS="SUCCESS",t.FAIL="FAIL",t.PRICE_SURGE="PRICE_SURGE",t.APPROVE_ERC20="APPROVE_ERC20_SWAP"}(q||(q={}));class X{baseConfig;constructor({baseConfig:t}){this.baseConfig=t}}const J={[c.SANDBOX]:"https://checkout-api.sandbox.immutable.com",[c.PRODUCTION]:"https://checkout-api.immutable.com"};class Z{coinsCache;overridesCache;config;constructor(t){this.coinsCache=null,this.overridesCache=null,this.config=t.baseConfig}urlWithPath(t){return J[this.config.environment]+t}async fetchOverrides(){if(null!==this.overridesCache)return;const t=this.urlWithPath("/v1/fiat/coins/overrides"),e=await l.get(t);if(200!==e.status)throw new Error(`Error fetching coins overrides: ${e.status} ${e.statusText}`);this.overridesCache=new Map(Object.entries(e.data))}async fetchCoins(){if(null!==this.coinsCache)return;await this.fetchOverrides();const t=this.urlWithPath("/v1/fiat/coins/all"),e=await l.get(t);if(200!==e.status)throw new Error(`Error fetching coins list: ${e.status} ${e.statusText}`);const{data:n}=e;this.coinsCache=new Map;for(const t of n){const e=this.overridesCache.get(t.symbol.toLowerCase());this.coinsCache.set(t.symbol.toLowerCase(),e||t.id.toLowerCase())}}async convert({tokenSymbols:t,fiatSymbols:e=[]}){if(!t||0===t.length)throw new Error("Error missing token symbols to convert");const n=e.filter((t=>""!==t));0===n.length&&n.push("usd"),await this.fetchCoins();const o=t.map((t=>this.coinsCache.get(t.toLowerCase()))).filter((t=>""!==t&&void 0!==t)).join(","),i=n.join(",").toLowerCase(),r=this.urlWithPath(`/v1/fiat/conversion?ids=${o}&currencies=${i}`),s=await l.get(r);if(200!==s.status)throw new Error(`Error fetching prices: ${s.status} ${s.statusText}`);const{data:a}=s,c={};for(const e of t){const t=e.toLowerCase(),n=this.coinsCache.get(t);c[t]={},n&&(c[t]=a[n]||{})}return c}}const Q=async(t,e,n)=>{try{if(0===n.length)return new Map;return((t,e)=>{const n=new Map;for(const o in t){const i=t[o][e];void 0!==i&&n.set(o,i)}return n})(await t.convert({tokenSymbols:n,fiatSymbols:[e]}),e)}catch(t){return new Map}},tt=["ETH","IMX"];function et({environment:t,children:e}){const[n,o]=a.useReducer(j,H),{cryptoFiat:i,fiatSymbol:r,tokenSymbols:s}=n;return a.useEffect((()=>{o({payload:{type:Y.SET_CRYPTO_FIAT,cryptoFiat:new Z(new X({baseConfig:{environment:t}}))}})}),[]),a.useEffect((()=>{i&&r&&(async()=>{const t=await Q(i,r,[...new Set([...s,...tt])]);o({payload:{type:Y.SET_CONVERSIONS,conversions:t}})})()}),[i,s,r]),u(z.Provider,{value:{cryptoFiatState:n,cryptoFiatDispatch:o},children:e})}var nt;!function(t){t.WALLET_NETWORK_SELECTION="WALLET_NETWORK_SELECTION",t.BRIDGE_FORM="BRIDGE_FORM",t.BRIDGE_REVIEW="BRIDGE_REVIEW",t.IN_PROGRESS="IN_PROGRESS",t.BRIDGE_FAILURE="BRIDGE_FAILURE",t.APPROVE_TRANSACTION="APPROVE_TRANSACTION",t.TRANSACTIONS="TRANSACTIONS",t.CLAIM_WITHDRAWAL="CLAIM_WITHDRAWAL",t.CLAIM_WITHDRAWAL_IN_PROGRESS="CLAIM_WITHDRAWAL_IN_PROGRESS",t.CLAIM_WITHDRAWAL_SUCCESS="CLAIM_WITHDRAWAL_SUCCESS",t.CLAIM_WITHDRAWAL_FAILURE="CLAIM_WITHDRAWAL_FAILURE"}(nt||(nt={}));const ot=(t,e,n)=>{const o=a.useRef(!1);a.useEffect((()=>{o.current||("function"!=typeof e||e())&&(t(),o.current=!0)}),n||[])};const it=(t,e)=>{const{fees:n,token:o}=t;if(void 0===n.totalFees)return"-.--";if(void 0===o)return"-.--";const i=((t,e,n)=>{let o=-1;if(t&&e){const i=M(t,e.decimals),r=n.get(e.symbol.toLocaleLowerCase());if(r){const t=parseFloat(i);if(Number.isNaN(t))return o;o=t*r}}return o})(n.totalFees,o,e);return i<0?"-.--":function(t){if(t<0)return"-.--";const e=t.toString();if(e.includes("e")||0===t)return"0.00";if(t<.01)for(let n=0;n<e.length;n++)if("0"!==e[n]&&"."!==e[n])return t.toFixed(n-1);return t.toFixed(2)}(i)};var rt;function st({testId:t,icon:e,iconVariant:n,intentIcon:o,heading:i,caption:r,onClick:s,renderFeeFunction:a,isDisabled:c}){return u(m,{testId:"top-up-view",sx:{paddingY:"1px"},children:d(f,{testId:`menu-item-${t}`,size:"small",emphasized:!0,onClick:c?void 0:s,sx:c?{opacity:"0.5",cursor:"not-allowed"}:{},children:[u(f.Icon,{icon:e,variant:n}),u(f.Label,{size:"medium",children:i}),u(f.IntentIcon,{icon:o}),d(f.Caption,{testId:`menu-item-caption-${t}`,children:[r,u("br",{}),c?"":a("-.--",!1)]})]})})}!function(t){t.ONRAMP="ONRAMP",t.IN_PROGRESS_LOADING="IN_PROGRESS_LOADING",t.IN_PROGRESS="IN_PROGRESS",t.SUCCESS="SUCCESS",t.FAIL="FAIL"}(rt||(rt={}));const at={[c.SANDBOX]:"https://checkout-playground.sandbox.immutable.com",[c.PRODUCTION]:"https://toolkit.immutable.com"};function ct({widgetEvent:t,checkout:e,provider:n,showOnrampOption:o,showSwapOption:i,showBridgeOption:r,tokenAddress:s,amount:l,analytics:f,onCloseButtonClick:C,onBackButtonClick:O,heading:y,subheading:R}){const{t:x}=h(),{userJourney:N}=f,{viewDispatch:F}=a.useContext(E),{cryptoFiatState:P,cryptoFiatDispatch:L}=a.useContext(z),{conversions:U,fiatSymbol:k}=P,W=e?.config.environment??c.SANDBOX,{eventTargetState:{eventTarget:D}}=a.useContext(p),[B,V]=a.useState("-.--"),[,M]=a.useState("-.--"),[$,G]=a.useState(!0),K=y?x(...y):x("views.TOP_UP_VIEW.header.title"),H=R?x(...R):null,{page:j,track:X}=g();ot((()=>{j({userJourney:N,screen:"TopUp"})})),a.useEffect((()=>{L&&L({payload:{type:Y.SET_TOKEN_SYMBOLS,tokenSymbols:tt}})}),[L]),a.useEffect((()=>{e&&(async()=>{const t=await e.gasEstimate({gasEstimateType:S.BRIDGE_TO_L2}),n=await it(t,U);M(n)})()}),[void 0!==e]),a.useEffect((()=>{e&&(async()=>{const t=(t=>{const{minPercentage:e,maxPercentage:n}=t;return void 0===e||void 0===n?"-.--":`${e}% to ${n}`})(await e.getExchangeFeeEstimate());V(t)})()}),[void 0!==e]),a.useEffect((()=>{e&&(async()=>{G(await e.isSwapAvailable())})()}),[void 0!==e]);const J=(t,e,n="Button")=>{X({userJourney:N,screen:"TopUp",control:t,controlType:n,extras:e})},Z=()=>{if(t===I.IMTBL_ONRAMP_WIDGET_EVENT){const e={tokenAddress:"",amount:""};return F({payload:{type:T.UPDATE_VIEW,view:{type:rt.ONRAMP,data:e}}}),void J("OnRamp",{...e,widgetEvent:t})}const e={tokenAddress:s??"",amount:l??""};b.sendRequestOnrampEvent(D,t,e),J("OnRamp",{...e,widgetEvent:t})},Q=t=>u(m,{sx:{fontSize:"base.text.caption.small.regular.fontSize",c:"base.color.translucent.standard.600"},children:t}),et=[{testId:"onramp",icon:"BankCard",iconVariant:"bold",textConfigKey:"views.TOP_UP_VIEW.topUpOptions.debit",onClickEvent:Z,fee:()=>Q(`${x("views.TOP_UP_VIEW.topUpOptions.debit.subcaption")} ≈ ${B}%`),isAvailable:!0,isEnabled:o},{testId:"onramp",icon:"BankCard",textConfigKey:"views.TOP_UP_VIEW.topUpOptions.credit",onClickEvent:Z,fee:()=>Q(`${x("views.TOP_UP_VIEW.topUpOptions.credit.subcaption")} ≈ ${B}%`),isAvailable:!0,isEnabled:o},{testId:"advanced",icon:"Minting",iconVariant:"bold",intentIcon:"JumpTo",textConfigKey:"views.TOP_UP_VIEW.topUpOptions.advanced",onClickEvent:()=>{const e=at[W];J("AdvancedOptions",{...{tokenAddress:s??"",amount:l??""},widgetEvent:t}),window.open(`${e}/squid-bridge/`,"_blank")},fee:()=>Q(""),isAvailable:!0,isEnabled:!0},{testId:"swap",icon:"Swap",textConfigKey:"views.TOP_UP_VIEW.topUpOptions.swap",onClickEvent:()=>{if(t===I.IMTBL_SWAP_WIDGET_EVENT){const e={toTokenAddress:"",fromAmount:"",fromTokenAddress:""};return F({payload:{type:T.UPDATE_VIEW,view:{type:q.SWAP,data:e}}}),void J("Swap",{...e,widgetEvent:t})}const e={fromTokenAddress:"",toTokenAddress:s??"",amount:""};b.sendRequestSwapEvent(D,t,e),J("Swap",{...e,widgetEvent:t})},fee:()=>Q(`${x("views.TOP_UP_VIEW.topUpOptions.swap.subcaption")} ≈ $0.05 ${k.toUpperCase()}`),isAvailable:$,isEnabled:i},{testId:"bridge",icon:"ArrowForward",textConfigKey:"views.TOP_UP_VIEW.topUpOptions.bridge",onClickEvent:()=>{if(t===I.IMTBL_BRIDGE_WIDGET_EVENT){const e={fromTokenAddress:"",fromAmount:""};return F({payload:{type:T.UPDATE_VIEW,view:{type:nt.WALLET_NETWORK_SELECTION,data:e}}}),void J("Bridge",{...e,widgetEvent:t})}const e={tokenAddress:"",amount:""};b.sendRequestBridgeEvent(D,t,e),J("Bridge",{...e,widgetEvent:t})},fee:()=>Q(""),isAvailable:!0,isEnabled:r}];return u(A,{header:u(v,{onBackButtonClick:O,onCloseButtonClick:C,showBack:!0}),children:d(m,{sx:{paddingX:"base.spacing.x4",paddingY:"base.spacing.x4"},children:[u(_,{size:"small",children:K}),H&&u(w,{size:"small",sx:{color:"base.color.text.body.secondary"},children:H}),u(m,{sx:{paddingY:"base.spacing.x4"},children:et.sort(((t,e)=>Number(e.isAvailable)-Number(t.isAvailable))).map((t=>t.isEnabled&&u(st,{testId:t.testId,icon:t.icon,iconVariant:t.iconVariant,intentIcon:t.intentIcon,heading:x(`${t.textConfigKey}.heading`),caption:t.isAvailable?x(`${t.textConfigKey}.caption`):x(`${t.textConfigKey}.disabledCaption`),onClick:t.onClickEvent,renderFeeFunction:t.fee,isDisabled:!t.isAvailable},x(`${t.textConfigKey}.heading`).toLowerCase())))})]})})}export{nt as B,z as C,rt as O,q as S,ct as T,Y as a,et as b,G as c,M as f,$ as p,ot as u};