@moonpay/cli 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2WTRKQ5U.js +47 -0
- package/dist/chunk-7WGPMBRA.js +34 -0
- package/dist/chunk-AT2QGHZK.js +6 -0
- package/dist/chunk-GXU26BRG.js +795 -0
- package/dist/chunk-INE4OXJA.js +2 -0
- package/dist/chunk-JLT4XDAY.js +2 -0
- package/dist/chunk-KBP3ULPH.js +1 -0
- package/dist/chunk-LMDE72OE.js +2 -0
- package/dist/chunk-OYYN2ANR.js +4 -0
- package/dist/chunk-RGIDTLVF.js +28 -0
- package/dist/chunk-SEOEJZOL.js +2 -0
- package/dist/chunk-TOZGDNCY.js +2 -0
- package/dist/chunk-WZYJQ7YV.js +3 -0
- package/dist/chunk-X4FGWJTX.js +4 -0
- package/dist/cjs-45IF6THY.js +50 -0
- package/dist/cjs-TXBROUGT.js +2 -0
- package/dist/client-HKXT43GQ.js +2 -0
- package/dist/client-LENSTDQC.js +2 -0
- package/dist/esm-4G6WDGDX.js +116 -0
- package/dist/esm-4JOSPTGT.js +2 -0
- package/dist/esm-FE2LDJCN.js +2 -0
- package/dist/esm-GGU7JFHZ.js +32 -0
- package/dist/esm-GMRPTFSK.js +2 -0
- package/dist/esm-QATSH3KB.js +2 -0
- package/dist/index.js +2 -2
- package/dist/ledger-7LVGD3PM.js +11 -0
- package/dist/mcp-ILIKIYXA.js +2 -0
- package/dist/src-X7XKGWIB.js +2 -0
- package/dist/store-JISBK7RI.js +2 -0
- package/package.json +11 -5
- package/skills/moonpay-hardware-wallet/SKILL.md +121 -0
- package/dist/chunk-5JISHR3O.js +0 -3
- package/dist/chunk-VNKUCDMG.js +0 -33
- package/dist/mcp-JMWCGUIQ.js +0 -2
- package/dist/store-YMEPPWTO.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
process.noDeprecation = true; import { createRequire as __createRequire } from "module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import{F as X,La as p,Ma as y,Na as A,Oa as lo,P as Nr,R as so,S as m,T as v,U as Ar,V as Pr,b as N,c as xe,d as re,da as co,l as oo,p as Ir,r as ao,v as no,y as io}from"./chunk-2WTRKQ5U.js";import{a as Ga}from"./chunk-RGIDTLVF.js";import{a as wr,c as kr,e as ro}from"./chunk-LMDE72OE.js";var Yr=kr((xr,Sa)=>{"use strict";(function(e,t){typeof xr=="object"?Sa.exports=xr=t():typeof define=="function"&&define.amd?define([],t):e.CryptoJS=t()})(xr,function(){var e=e||(function(t,r){var o;if(typeof window<"u"&&window.crypto&&(o=window.crypto),typeof self<"u"&&self.crypto&&(o=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(o=globalThis.crypto),!o&&typeof window<"u"&&window.msCrypto&&(o=window.msCrypto),!o&&typeof global<"u"&&global.crypto&&(o=global.crypto),!o&&typeof wr=="function")try{o=wr("crypto")}catch{}var a=function(){if(o){if(typeof o.getRandomValues=="function")try{return o.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof o.randomBytes=="function")try{return o.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||(function(){function u(){}return function(T){var L;return u.prototype=T,L=new u,u.prototype=null,L}})(),i={},s=i.lib={},c=s.Base=(function(){return{extend:function(u){var T=n(this);return u&&T.mixIn(u),(!T.hasOwnProperty("init")||this.init===T.init)&&(T.init=function(){T.$super.init.apply(this,arguments)}),T.init.prototype=T,T.$super=this,T},create:function(){var u=this.extend();return u.init.apply(u,arguments),u},init:function(){},mixIn:function(u){for(var T in u)u.hasOwnProperty(T)&&(this[T]=u[T]);u.hasOwnProperty("toString")&&(this.toString=u.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),l=s.WordArray=c.extend({init:function(u,T){u=this.words=u||[],T!=r?this.sigBytes=T:this.sigBytes=u.length*4},toString:function(u){return(u||C).stringify(this)},concat:function(u){var T=this.words,L=u.words,R=this.sigBytes,j=u.sigBytes;if(this.clamp(),R%4)for(var M=0;M<j;M++){var xt=L[M>>>2]>>>24-M%4*8&255;T[R+M>>>2]|=xt<<24-(R+M)%4*8}else for(var rt=0;rt<j;rt+=4)T[R+rt>>>2]=L[rt>>>2];return this.sigBytes+=j,this},clamp:function(){var u=this.words,T=this.sigBytes;u[T>>>2]&=4294967295<<32-T%4*8,u.length=t.ceil(T/4)},clone:function(){var u=c.clone.call(this);return u.words=this.words.slice(0),u},random:function(u){for(var T=[],L=0;L<u;L+=4)T.push(a());return new l.init(T,u)}}),d=i.enc={},C=d.Hex={stringify:function(u){for(var T=u.words,L=u.sigBytes,R=[],j=0;j<L;j++){var M=T[j>>>2]>>>24-j%4*8&255;R.push((M>>>4).toString(16)),R.push((M&15).toString(16))}return R.join("")},parse:function(u){for(var T=u.length,L=[],R=0;R<T;R+=2)L[R>>>3]|=parseInt(u.substr(R,2),16)<<24-R%8*4;return new l.init(L,T/2)}},b=d.Latin1={stringify:function(u){for(var T=u.words,L=u.sigBytes,R=[],j=0;j<L;j++){var M=T[j>>>2]>>>24-j%4*8&255;R.push(String.fromCharCode(M))}return R.join("")},parse:function(u){for(var T=u.length,L=[],R=0;R<T;R++)L[R>>>2]|=(u.charCodeAt(R)&255)<<24-R%4*8;return new l.init(L,T)}},x=d.Utf8={stringify:function(u){try{return decodeURIComponent(escape(b.stringify(u)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(u){return b.parse(unescape(encodeURIComponent(u)))}},_=s.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(u){typeof u=="string"&&(u=x.parse(u)),this._data.concat(u),this._nDataBytes+=u.sigBytes},_process:function(u){var T,L=this._data,R=L.words,j=L.sigBytes,M=this.blockSize,xt=M*4,rt=j/xt;u?rt=t.ceil(rt):rt=t.max((rt|0)-this._minBufferSize,0);var mt=rt*M,ge=t.min(mt*4,j);if(mt){for(var ee=0;ee<mt;ee+=M)this._doProcessBlock(R,ee);T=R.splice(0,mt),L.sigBytes-=ge}return new l.init(T,ge)},clone:function(){var u=c.clone.call(this);return u._data=this._data.clone(),u},_minBufferSize:0}),S=s.Hasher=_.extend({cfg:c.extend(),init:function(u){this.cfg=this.cfg.extend(u),this.reset()},reset:function(){_.reset.call(this),this._doReset()},update:function(u){return this._append(u),this._process(),this},finalize:function(u){u&&this._append(u);var T=this._doFinalize();return T},blockSize:512/32,_createHelper:function(u){return function(T,L){return new u.init(L).finalize(T)}},_createHmacHelper:function(u){return function(T,L){return new z.HMAC.init(u,L).finalize(T)}}}),z=i.algo={};return i})(Math);return e})});var va=kr((Er,_a)=>{"use strict";(function(e,t){typeof Er=="object"?_a.exports=Er=t(Yr()):typeof define=="function"&&define.amd?define(["./core"],t):t(e.CryptoJS)})(Er,function(e){return(function(t){var r=e,o=r.lib,a=o.WordArray,n=o.Hasher,i=r.algo,s=[],c=[];(function(){function C(S){for(var z=t.sqrt(S),u=2;u<=z;u++)if(!(S%u))return!1;return!0}function b(S){return(S-(S|0))*4294967296|0}for(var x=2,_=0;_<64;)C(x)&&(_<8&&(s[_]=b(t.pow(x,1/2))),c[_]=b(t.pow(x,1/3)),_++),x++})();var l=[],d=i.SHA256=n.extend({_doReset:function(){this._hash=new a.init(s.slice(0))},_doProcessBlock:function(C,b){for(var x=this._hash.words,_=x[0],S=x[1],z=x[2],u=x[3],T=x[4],L=x[5],R=x[6],j=x[7],M=0;M<64;M++){if(M<16)l[M]=C[b+M]|0;else{var xt=l[M-15],rt=(xt<<25|xt>>>7)^(xt<<14|xt>>>18)^xt>>>3,mt=l[M-2],ge=(mt<<15|mt>>>17)^(mt<<13|mt>>>19)^mt>>>10;l[M]=rt+l[M-7]+ge+l[M-16]}var ee=T&L^~T&R,Ba=_&S^_&z^S&z,$a=(_<<30|_>>>2)^(_<<19|_>>>13)^(_<<10|_>>>22),ja=(T<<26|T>>>6)^(T<<21|T>>>11)^(T<<7|T>>>25),eo=j+ja+ee+c[M]+l[M],Va=$a+Ba;j=R,R=L,L=T,T=u+eo|0,u=z,z=S,S=_,_=eo+Va|0}x[0]=x[0]+_|0,x[1]=x[1]+S|0,x[2]=x[2]+z|0,x[3]=x[3]+u|0,x[4]=x[4]+T|0,x[5]=x[5]+L|0,x[6]=x[6]+R|0,x[7]=x[7]+j|0},_doFinalize:function(){var C=this._data,b=C.words,x=this._nDataBytes*8,_=C.sigBytes*8;return b[_>>>5]|=128<<24-_%32,b[(_+64>>>9<<4)+14]=t.floor(x/4294967296),b[(_+64>>>9<<4)+15]=x,C.sigBytes=b.length*4,this._process(),this._hash},clone:function(){var C=n.clone.call(this);return C._hash=this._hash.clone(),C}});r.SHA256=n._createHelper(d),r.HmacSHA256=n._createHmacHelper(d)})(Math),e.SHA256})});var Da=kr((Tr,ba)=>{"use strict";(function(e,t,r){typeof Tr=="object"?ba.exports=Tr=t(Yr(),va()):typeof define=="function"&&define.amd?define(["./core","./sha256"],t):t(e.CryptoJS)})(Tr,function(e){return(function(){var t=e,r=t.lib,o=r.WordArray,a=t.algo,n=a.SHA256,i=a.SHA224=n.extend({_doReset:function(){this._hash=new o.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var s=n._doFinalize.call(this);return s.sigBytes-=4,s}});t.SHA224=n._createHelper(i),t.HmacSHA224=n._createHmacHelper(i)})(),e.SHA224})});var Et={CalldataContextLoader:Symbol.for("CalldataContextLoader"),DappCalldataDescriptorDataSource:Symbol.for("DappCalldataDescriptorDataSource"),TokenCalldataDescriptorDataSource:Symbol.for("TokenCalldataDescriptorDataSource")};var Lt={DynamicNetworkDataSource:Symbol("DynamicNetworkDataSource"),DynamicNetworkContextLoader:Symbol("DynamicNetworkContextLoader")};var ot={TrustedNameDataSource:Symbol.for("TrustedNameDataSource"),TrustedNameContextLoader:Symbol.for("TrustedNameContextLoader"),TrustedNameContextFieldLoader:Symbol.for("TrustedNameContextFieldLoader")};var Rt={ExternalPluginDataSource:Symbol.for("externalPluginDataSource"),ExternalPluginContextLoader:Symbol.for("externalPluginContextLoader")};var st={NftDataSource:Symbol.for("nftDataSource"),NftContextLoader:Symbol.for("nftContextLoader"),NftContextFieldLoader:Symbol.for("nftContextFieldLoader")};var at={ProxyDataSource:Symbol.for("ProxyDataSource"),ProxyContextFieldLoader:Symbol.for("ProxyContextFieldLoader")};var Ft={SafeAddressDataSource:Symbol.for("SafeAddressDataSource"),SafeAddressLoader:Symbol.for("SafeAddressLoader")};var f=(e=>(e.TOKEN="token",e.NFT="nft",e.TRUSTED_NAME="trustedName",e.PLUGIN="plugin",e.EXTERNAL_PLUGIN="externalPlugin",e.TRANSACTION_INFO="transactionInfo",e.PROXY_INFO="proxyInfo",e.ENUM="enum",e.TRANSACTION_FIELD_DESCRIPTION="transactionFieldDescription",e.TRANSACTION_CHECK="transactionCheck",e.DYNAMIC_NETWORK="dynamicNetwork",e.DYNAMIC_NETWORK_ICON="dynamicNetworkIcon",e.ERROR="error",e.SAFE="safe",e.SIGNER="signer",e))(f||{}),Tt=(e=>(e.TOKEN="token",e.NFT="nft",e.TRUSTED_NAME="trustedName",e.ENUM="enum",e.CALLDATA="calldata",e))(Tt||{});var Mt={SolanaDataSource:Symbol.for("SolanaDataSource"),SolanaContextLoader:Symbol.for("SolanaContextLoader")};var K={TokenDataSource:Symbol.for("TokenDataSource"),TokenContextLoader:Symbol.for("TokenContextLoader"),TokenContextFieldLoader:Symbol.for("TokenContextFieldLoader")};var nt={TransactionCheckDataSource:Symbol.for("TransactionCheckDataSource"),TransactionCheckContextLoader:Symbol.for("TransactionCheckContextLoader"),TypedDataCheckDataSource:Symbol.for("TypedDataCheckDataSource"),TypedDataCheckContextLoader:Symbol.for("TypedDataCheckContextLoader")};var Ut={TypedDataDataSource:Symbol.for("TypedDataDataSource"),TypedDataContextLoader:Symbol.for("TypedDataContextLoader")};import Ja from"axios";var g={Config:Symbol.for("config"),OriginToken:Symbol.for("originToken"),ContextModuleLoggerFactory:Symbol.for("contextModuleLoggerFactory")};var P={PkiCertificateDataSource:Symbol.for("PkiCertificateDataSource"),PkiCertificateLoader:Symbol.for("PkiCertificateLoader")};var ct=(e=>(e.Test="test",e.PersoV2="persov2",e.LedgerRootV3="ledger_root_v3",e.PluginSelectorKey="plugin_selector_key",e.NftMetadataKey="nft_metadata_key",e.PartnerMetadataKey="partner_metadata_key",e.Erc20MetadataKey="erc20_metadata_key",e.DomainMetadataKey="domain_metadata_key",e.CalCalldataKey="cal_calldata_key",e.CalTrustedNameKey="cal_trusted_name_key",e.CalNetwork="cal_network",e))(ct||{});var k=(e=>(e.GenuineCheck="genuine_check",e.ExchangePayload="exchange_payload",e.NftMeta="nft_meta",e.TrustedName="trusted_name",e.BackupProvider="backup_provider",e.ProtectOrchestrator="protect_orchestrator",e.PluginMeta="plugin_meta",e.CoinMeta="coin_meta",e.SeedIdAuth="seed_id_auth",e.TxSimulationSigner="tx_simu_signer",e.Calldata="calldata",e.Network="network",e.LESMultisig="les_multisig",e))(k||{});var D="X-Ledger-Client-Version",U="X-Ledger-Client-Origin";var Or="81ff";var Ct=class{static stringToHex(t){let r="";for(let o=0;o<t.length;o++){let a=t.charCodeAt(o).toString(16);r+=a.padStart(2,"0")}return r}static appendSignatureToPayload(t,r,o){r.length%2!==0&&(r="0"+r);let a=(r.length/2).toString(16);return a.length%2!==0&&(a="0"+a),`${t}${o}${a}${r}`}};var w={dependencies:{axios:"catalog:","crypto-js":"catalog:",ethers:"catalog:",inversify:"catalog:","purify-ts":"catalog:","reflect-metadata":"catalog:"},devDependencies:{"@ledgerhq/device-management-kit":"workspace:^","@ledgerhq/eslint-config-dsdk":"workspace:^","@ledgerhq/ldmk-tool":"workspace:^","@ledgerhq/prettier-config-dsdk":"workspace:^","@ledgerhq/tsconfig-dsdk":"workspace:^","@ledgerhq/vitest-config-dmk":"workspace:^","@types/crypto-js":"catalog:","ts-node":"catalog:"},exports:{".":{import:"./lib/esm/index.js",require:"./lib/cjs/index.js",types:"./lib/types/index.d.ts"},"./*":{import:"./lib/esm/*",require:"./lib/cjs/*",types:"./lib/types/*"}},files:["./lib"],license:"Apache-2.0",name:"@ledgerhq/context-module",peerDependencies:{"@ledgerhq/device-management-kit":"^1.1.0"},private:!1,repository:{type:"git",url:"https://github.com/LedgerHQ/device-sdk-ts.git"},scripts:{build:"pnpm ldmk-tool build --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",dev:'concurrently "pnpm watch:builds" "pnpm watch:types"',lint:"eslint","lint:fix":"pnpm lint --fix",postpack:"find . -name '*.tgz' -exec cp {} ../../../dist/ \\; ",prebuild:"rimraf lib",prettier:"prettier . --check","prettier:fix":"prettier . --write",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest",typecheck:"tsc --noEmit","watch:builds":"pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json","watch:types":'concurrently "tsc --watch -p tsconfig.prod.json" "tsc-alias --watch -p tsconfig.prod.json"'},version:"1.14.1"};var Wa=Object.defineProperty,za=Object.getOwnPropertyDescriptor,Xa=(e,t,r,o)=>{for(var a=o>1?void 0:o?za(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Wa(t,r,a),a},po=(e,t)=>(r,o)=>t(r,o,e),oe=class{constructor(e,t,r){this.config=e,this._certificateLoader=t,this.endpoint=r}async getCalldataDescriptors({chainId:e,address:t,selector:r,deviceModelId:o}){let a;try{a=(await Ja.request({method:"GET",url:`${this.config.cal.url}/${this.endpoint}`,params:{output:"descriptors_calldata",chain_id:e,contracts:t,contract_address:t,ref:`branch:${this.config.cal.branch}`},headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}})).data}catch(n){return m(new Error(`[ContextModule] HttpCalldataDescriptorDataSource: Failed to fetch calldata descriptors: ${n}`))}if(!Array.isArray(a))return m(new Error("[ContextModule] HttpCalldataDescriptorDataSource: Response is not an array"));if(a.length===0)return m(new Error(`[ContextModule] HttpCalldataDescriptorDataSource: No data for contract ${t} and selector ${r}`));for(let n of a){t=t.toLowerCase(),r=`0x${r.slice(2).toLowerCase()}`;let i=n.descriptors_calldata?.[t]?.[r];if(!i||!this.isCalldataDescriptorV1(i,this.config.cal.mode))continue;let s=i.transaction_info.descriptor.data,c=i.transaction_info.descriptor.signatures[this.config.cal.mode],l={targetDevice:o,keyUsage:k.Calldata,keyId:ct.CalCalldataKey},d=await this._certificateLoader.loadCertificate(l),C={type:f.TRANSACTION_INFO,payload:Ct.appendSignatureToPayload(s,c,Or),certificate:d},b=[];for(let[_,S]of Object.entries(i.enums))for(let[z,{data:u,signatures:T}]of Object.entries(S))b.push({type:f.ENUM,id:Number(_),value:Number(z),payload:Ct.appendSignatureToPayload(u,T[this.config.cal.mode],Or),certificate:d});let x=i.fields.map(_=>({type:f.TRANSACTION_FIELD_DESCRIPTION,payload:_.descriptor,reference:this.getReference(_.param)}));return v([C,...b,...x])}return m(new Error(`[ContextModule] HttpCalldataDescriptorDataSource: Invalid response for contract ${t} and selector ${r}`))}getReference(e){if(e.type==="TOKEN_AMOUNT"&&e.token!==void 0&&e.token.type==="path")return{type:Tt.TOKEN,valuePath:this.toGenericPath(e.token.binary_path)};if(e.type==="TOKEN_AMOUNT"&&e.token!==void 0&&e.token.type==="constant")return{type:Tt.TOKEN,value:e.token.value};if(e.type==="NFT"&&e.collection.type==="path")return{type:Tt.NFT,valuePath:this.toGenericPath(e.collection.binary_path)};if(e.type==="NFT"&&e.collection.type==="constant")return{type:Tt.NFT,value:e.collection.value};if(e.type==="TRUSTED_NAME"&&e.value.type==="path")return{type:Tt.TRUSTED_NAME,valuePath:this.toGenericPath(e.value.binary_path),types:e.types,sources:e.sources};if(e.type==="ENUM"&&e.value.type==="path")return{type:Tt.ENUM,valuePath:this.toGenericPath(e.value.binary_path),id:e.id};if(e.type==="CALLDATA"&&e.value.type==="path"&&e.callee.type==="path")return{type:Tt.CALLDATA,valuePath:this.toGenericPath(e.value.binary_path),callee:this.toGenericPath(e.callee.binary_path),selector:e.selector?.type==="path"?this.toGenericPath(e.selector.binary_path):void 0,amount:e.amount?.type==="path"?this.toGenericPath(e.amount.binary_path):void 0,spender:e.spender?.type==="path"?this.toGenericPath(e.spender.binary_path):void 0,chainId:e.chainId?.type==="path"?this.toGenericPath(e.chainId.binary_path):void 0}}toGenericPath(e){return e.type==="CONTAINER"?e.value:e.elements.map(t=>{if(t.type==="ARRAY"){let{weight:r,...o}=t;return{itemSize:r,...o}}else if(t.type==="LEAF"){let{leaf_type:r,...o}=t;return{leafType:r,...o}}return t})}isCalldataDescriptorV1(e,t){return typeof e=="object"&&e.type==="calldata"&&e.version==="v1"&&this.isTransactionInfoV1(e.transaction_info,t)&&this.isEnumV1(e.enums,t)&&Array.isArray(e.fields)&&e.fields.every(r=>this.isFieldV1(r))}isTransactionInfoV1(e,t){return typeof e=="object"&&typeof e.descriptor=="object"&&typeof e.descriptor.data=="string"&&typeof e.descriptor.signatures=="object"&&typeof e.descriptor.signatures[t]=="string"}isEnumV1(e,t){return typeof e=="object"&&Object.entries(e).every(([r,o])=>typeof r=="string"&&typeof o=="object"&&Object.entries(o).every(([a,n])=>typeof a=="string"&&typeof n=="object"&&typeof n.data=="string"&&n.signatures!==void 0&&this.isCalldataSignatures(n.signatures,t)))}isCalldataSignatures(e,t){return typeof e=="object"&&typeof e[t]=="string"}isFieldV1(e){return typeof e=="object"&&typeof e.descriptor=="string"&&typeof e.param=="object"&&typeof e.param.value=="object"&&this.isDescriptorValueV1(e.param.value)&&(e.param.type==="RAW"||e.param.type==="AMOUNT"||e.param.type==="DATETIME"||e.param.type==="DURATION"||e.param.type==="UNIT"||e.param.type==="ENUM"||e.param.type==="NFT"&&this.isDescriptorValueV1(e.param.collection)||e.param.type==="TOKEN_AMOUNT"&&(e.param.token===void 0||this.isDescriptorValueV1(e.param.token))||e.param.type==="TRUSTED_NAME"&&Array.isArray(e.param.types)&&Array.isArray(e.param.sources)&&e.param.types.every(t=>typeof t=="string")&&e.param.sources.every(t=>typeof t=="string")||e.param.type==="CALLDATA"&&this.isDescriptorValueV1(e.param.value)&&this.isDescriptorValueV1(e.param.callee)&&(e.param.selector===void 0||this.isDescriptorValueV1(e.param.selector))&&(e.param.amount===void 0||this.isDescriptorValueV1(e.param.amount))&&(e.param.spender===void 0||this.isDescriptorValueV1(e.param.spender))&&(e.param.chainId===void 0||this.isDescriptorValueV1(e.param.chainId)))}isDescriptorValueV1(e){return typeof e=="object"&&typeof e.type_family=="string"&&["UINT","INT","UFIXED","FIXED","ADDRESS","BOOL","BYTES","STRING"].includes(e.type_family)&&(typeof e.type_size>"u"||typeof e.type_size=="number")&&(e.type==="path"&&this.isCalldataDescriptorValueBinaryPathV1(e)||e.type==="constant"&&this.isCalldataDescriptorValueConstantV1(e))}isCalldataDescriptorValueConstantV1(e){return typeof e=="object"&&e.type==="constant"&&typeof e.value=="string"}isCalldataDescriptorValueBinaryPathV1(e){return typeof e=="object"&&(e.type==="path"&&e.binary_path.type==="CONTAINER"&&["FROM","TO","VALUE"].includes(e.binary_path.value)||e.binary_path.type==="DATA"&&Array.isArray(e.binary_path.elements)&&e.binary_path.elements.every(t=>this.isPathElementV1(t)))}isPathElementV1(e){return typeof e=="object"&&(e.type==="REF"||e.type==="TUPLE"&&typeof e.offset=="number"||e.type==="ARRAY"&&typeof e.weight=="number"&&(typeof e.start>"u"||typeof e.start=="number")&&(typeof e.end>"u"||typeof e.end=="number")||e.type==="LEAF"&&typeof e.leaf_type=="string"&&["ARRAY_LEAF","TUPLE_LEAF","STATIC_LEAF","DYNAMIC_LEAF"].includes(e.leaf_type)||e.type==="SLICE"&&(typeof e.start>"u"||typeof e.start=="number")&&(typeof e.end>"u"||typeof e.end=="number"))}};oe=Xa([y(),po(0,p(g.Config)),po(1,p(P.PkiCertificateLoader))],oe);var qa=Object.defineProperty,Ya=Object.getOwnPropertyDescriptor,Za=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ya(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&qa(t,r,a),a},Ee=(e,t)=>(r,o)=>t(r,o,e),Qa=[f.TRANSACTION_INFO,f.TRANSACTION_FIELD_DESCRIPTION,f.PROXY_INFO,f.ENUM],Te=class{constructor(e,t,r,o){this.dappDataSource=e,this.tokenDataSource=t,this.proxyDataSource=r,this.logger=o("CalldataContextLoader")}logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"to"in e&&"data"in e&&"selector"in e&&"chainId"in e&&"deviceModelId"in e&&e.deviceModelId!==void 0&&e.deviceModelId!==X.NANO_S&&typeof e.chainId=="number"&&N(e.to)&&e.to!=="0x"&&N(e.data)&&N(e.selector)&&e.selector!=="0x"&&Qa.every(r=>t.includes(r))}async load(e){let{to:t,data:r,selector:o,chainId:a,deviceModelId:n}=e,i={address:t,chainId:a,selector:o,deviceModelId:n,data:r},s=(await this._getContexts(i,this.dappDataSource).alt(this._getContexts(i,this.tokenDataSource)).alt(this._getContextsWithProxy(i,this.dappDataSource)).run()).caseOf({Just:c=>c,Nothing:()=>[{type:f.ERROR,error:new Error("[ContextModule] CalldataContextLoader: No calldata contexts found")}]});return this.logger.debug("load result",{data:{result:s}}),s}_getContexts({address:e,chainId:t,selector:r,deviceModelId:o},a){return Pr(async({liftMaybe:n})=>{let i=await a.getCalldataDescriptors({deviceModelId:o,address:e,chainId:t,selector:r});return n(i.toMaybe().filter(s=>s.length>0))})}_getContextsWithProxy({address:e,chainId:t,selector:r,deviceModelId:o,data:a},n){return Pr(async({liftMaybe:i})=>{let s=await this.proxyDataSource.getProxyImplementationAddress({calldata:a,proxyAddress:e,chainId:t,challenge:""});return i(s.toMaybe())}).map(({implementationAddress:i})=>{let s={address:i,chainId:t,selector:r,deviceModelId:o,data:a};return this._getContexts(s,n).map(c=>[{type:f.PROXY_INFO,payload:"0x"},...c])}).join()}};Te=Za([y(),Ee(0,p(Et.DappCalldataDescriptorDataSource)),Ee(1,p(Et.TokenCalldataDescriptorDataSource)),Ee(2,p(at.ProxyDataSource)),Ee(3,p(g.ContextModuleLoggerFactory))],Te);var uo=()=>new A(({bind:e})=>{e(Et.DappCalldataDescriptorDataSource).toDynamicValue(t=>new oe(t.get(g.Config),t.get(P.PkiCertificateLoader),"dapps")),e(Et.TokenCalldataDescriptorDataSource).toDynamicValue(t=>new oe(t.get(g.Config),t.get(P.PkiCertificateLoader),"tokens")),e(Et.CalldataContextLoader).to(Te)});var fo=e=>new A(({bind:t})=>{t(g.Config).toConstantValue(e)});import an from"axios";var tn=Object.defineProperty,en=Object.getOwnPropertyDescriptor,rn=(e,t,r,o)=>{for(var a=o>1?void 0:o?en(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&tn(t,r,a),a},on=(e,t)=>(r,o)=>t(r,o,e),nn={nanos:X.NANO_S,nanosp:X.NANO_SP,nanox:X.NANO_X,stax:X.STAX,flex:X.FLEX,apexp:X.APEX},Ce=class{constructor(e){this.config=e}async getDynamicNetworkConfiguration(e){let t;try{t=(await an.get(`${this.config.cal.url}/networks?output=id,descriptors,icons&chain_id=${e}`,{headers:{[D]:`context-module/${w.version}`}})).data}catch(a){return m(a instanceof Error?a:new Error("Failed to fetch network configuration"))}let r=t?.[0];if(!r)return m(new Error(`Network configuration not found for chain ID: ${e}`));if(!this.isValidNetworkData(r))return m(new Error(`Invalid network configuration response for chain ID: ${e}`));let o=this.transformToNetworkConfiguration(r);return v(o)}isValidNetworkData(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.id!="string"||!t.descriptors||typeof t.descriptors!="object")return!1;for(let r of Object.values(t.descriptors))if(!this.isValidDescriptor(r))return!1;return!(t.icons&&typeof t.icons!="object")}isValidDescriptor(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.data!="string"||typeof t.descriptorType!="string"||typeof t.descriptorVersion!="string"||!t.signatures||typeof t.signatures!="object")return!1;let r=t.signatures;return!(typeof r.prod!="string"||typeof r.test!="string")}transformToNetworkConfiguration(e){let t=Object.entries(e.descriptors).reduce((r,[o,a])=>{let n=nn[o.toLowerCase()];return n===void 0||(r[n]={descriptorType:a.descriptorType,descriptorVersion:a.descriptorVersion,data:a.data,signatures:a.signatures,icon:e.icons?.[o]}),r},{});return{id:e.id,descriptors:t}}};Ce=rn([y(),on(0,p(g.Config))],Ce);var sn=Object.defineProperty,cn=Object.getOwnPropertyDescriptor,ln=(e,t,r,o)=>{for(var a=o>1?void 0:o?cn(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&sn(t,r,a),a},Se=(e,t)=>(r,o)=>t(r,o,e),dn="15",pn=[f.DYNAMIC_NETWORK,f.DYNAMIC_NETWORK_ICON],_e=class{_networkDataSource;_config;_certificateLoader;logger;constructor(e,t,r,o){this._networkDataSource=e,this._config=t,this._certificateLoader=r,this.logger=o("DynamicNetworkContextLoader")}canHandle(e,t){return typeof e=="object"&&e!==null&&"chainId"in e&&"deviceModelId"in e&&e.deviceModelId!==void 0&&e.deviceModelId!==X.NANO_S&&typeof e.chainId=="number"&&pn.every(r=>t.includes(r))}async load(e){let{chainId:t,deviceModelId:r}=e,o=await this._networkDataSource.getDynamicNetworkConfiguration(t),a=await this._certificateLoader.loadCertificate({keyId:ct.CalNetwork,keyUsage:k.Network,targetDevice:r}),n=o.caseOf({Left:()=>[],Right:i=>{let s=[],c=i.descriptors[r];if(!c)return[];let l=c.signatures[this._config.cal.mode];if(!l)return[];let d=Ct.appendSignatureToPayload(c.data,l,dn);return s.push({type:f.DYNAMIC_NETWORK,payload:d,certificate:a}),c.icon&&s.push({type:f.DYNAMIC_NETWORK_ICON,payload:c.icon}),s}});return this.logger.debug("load result",{data:{result:n}}),n}};_e=ln([y(),Se(0,p(Lt.DynamicNetworkDataSource)),Se(1,p(g.Config)),Se(2,p(P.PkiCertificateLoader)),Se(3,p(g.ContextModuleLoggerFactory))],_e);var mo=()=>new A(({bind:e})=>{e(Lt.DynamicNetworkDataSource).to(Ce),e(Lt.DynamicNetworkContextLoader).to(_e)});import yn from"axios";var un=Object.defineProperty,fn=Object.getOwnPropertyDescriptor,mn=(e,t,r,o)=>{for(var a=o>1?void 0:o?fn(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&un(t,r,a),a},hn=(e,t)=>(r,o)=>t(r,o,e),ve=class{constructor(e){this.config=e}async getDappInfos({chainId:e,address:t,selector:r}){try{let o=await yn.request({method:"GET",url:`${this.config.cal.url}/dapps`,params:{output:"b2c,b2c_signatures,abis",chain_id:e,contracts:t},headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}});if(!o.data[0])return v(void 0);t=t.toLowerCase(),r=`0x${r.slice(2).toLowerCase()}`;let{erc20OfInterest:a,method:n,plugin:i}=o.data[0].b2c?.contracts?.find(d=>d.address===t)?.selectors?.[r]||{},{signature:s,serialized_data:c}=o.data[0].b2c_signatures?.[t]?.[r]||{};if(!a||!n||!i||!s||!c)return v(void 0);let l=o.data[0].abis?.[t];return l?v({selectorDetails:{method:n,plugin:i,erc20OfInterest:a,signature:s,serializedData:c},abi:l}):v(void 0)}catch{return m(new Error("[ContextModule] HttpExternalPluginDataSource: Error fetching dapp infos"))}}};ve=mn([y(),hn(0,p(g.Config))],ve);var ho="6.14.1";function gn(e,t,r){let o=t.split("|").map(n=>n.trim());for(let n=0;n<o.length;n++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}let a=new Error(`invalid value for type ${t}`);throw a.code="INVALID_ARGUMENT",a.argument=`value.${r}`,a.value=e,a}function I(e,t,r){for(let o in t){let a=t[o],n=r?r[o]:null;n&&gn(a,n,o),Object.defineProperty(e,o,{enumerable:!0,value:a,writable:!1})}}function zt(e){if(e==null)return"null";if(Array.isArray(e))return"[ "+e.map(zt).join(", ")+" ]";if(e instanceof Uint8Array){let t="0123456789abcdef",r="0x";for(let o=0;o<e.length;o++)r+=t[e[o]>>4],r+=t[e[o]&15];return r}if(typeof e=="object"&&typeof e.toJSON=="function")return zt(e.toJSON());switch(typeof e){case"boolean":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"number":return e.toString();case"string":return JSON.stringify(e);case"object":{let t=Object.keys(e);return t.sort(),"{ "+t.map(r=>`${zt(r)}: ${zt(e[r])}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function be(e,t){return e&&e.code===t}function De(e,t,r){let o=e;{let n=[];if(r){if("message"in r||"code"in r||"name"in r)throw new Error(`value will overwrite populated values: ${zt(r)}`);for(let i in r){if(i==="shortMessage")continue;let s=r[i];n.push(i+"="+zt(s))}}n.push(`code=${t}`),n.push(`version=${ho}`),n.length&&(e+=" ("+n.join(", ")+")")}let a;switch(t){case"INVALID_ARGUMENT":a=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":a=new RangeError(e);break;default:a=new Error(e)}return I(a,{code:t}),r&&Object.assign(a,r),a.shortMessage==null&&I(a,{shortMessage:o}),a}function F(e,t,r,o){if(!e)throw De(t,r,o)}function h(e,t,r,o){F(e,t,"INVALID_ARGUMENT",{argument:r,value:o})}function ae(e,t,r){r==null&&(r=""),r&&(r=": "+r),F(e>=t,"missing argument"+r,"MISSING_ARGUMENT",{count:e,expectedCount:t}),F(e<=t,"too many arguments"+r,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}var xn=["NFD","NFC","NFKD","NFKC"].reduce((e,t)=>{try{if("test".normalize(t)!=="test")throw new Error("bad");if(t==="NFD"&&"\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken");e.push(t)}catch{}return e},[]);function Lr(e){F(xn.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function Xt(e,t,r){if(r==null&&(r=""),e!==t){let o=r,a="new";r&&(o+=".",a+=" "+r),F(!1,`private constructor; use ${o}from* methods`,"UNSUPPORTED_OPERATION",{operation:a})}}function go(e,t,r){if(e instanceof Uint8Array)return r?new Uint8Array(e):e;if(typeof e=="string"&&e.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)){let o=new Uint8Array((e.length-2)/2),a=2;for(let n=0;n<o.length;n++)o[n]=parseInt(e.substring(a,a+2),16),a+=2;return o}h(!1,"invalid BytesLike value",t||"value",e)}function J(e,t){return go(e,t,!1)}function q(e,t){return go(e,t,!0)}function Jt(e,t){return!(typeof e!="string"||!e.match(/^0x[0-9A-Fa-f]*$/)||typeof t=="number"&&e.length!==2+2*t||t===!0&&e.length%2!==0)}var yo="0123456789abcdef";function H(e){let t=J(e),r="0x";for(let o=0;o<t.length;o++){let a=t[o];r+=yo[(a&240)>>4]+yo[a&15]}return r}function St(e){return"0x"+e.map(t=>H(t).substring(2)).join("")}function Dt(e,t,r){let o=J(e);return r!=null&&r>o.length&&F(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:o,length:o.length,offset:r}),H(o.slice(t??0,r??o.length))}function xo(e,t,r){let o=J(e);F(t>=o.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(o),length:t,offset:t+1});let a=new Uint8Array(t);return a.fill(0),r?a.set(o,t-o.length):a.set(o,0),H(a)}function Rr(e,t){return xo(e,t,!0)}function Fr(e,t){return xo(e,t,!1)}var we=BigInt(0),lt=BigInt(1),qt=9007199254740991;function Mr(e,t){let r=ne(e,"value"),o=BigInt(dt(t,"width"));if(F(r>>o===we,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),r>>o-lt){let a=(lt<<o)-lt;return-((~r&a)+lt)}return r}function Ur(e,t){let r=ht(e,"value"),o=BigInt(dt(t,"width")),a=lt<<o-lt;if(r<we){r=-r,F(r<=a,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});let n=(lt<<o)-lt;return(~r&n)+lt}else F(r<a,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return r}function Yt(e,t){let r=ne(e,"value"),o=BigInt(dt(t,"bits"));return r&(lt<<o)-lt}function ht(e,t){switch(typeof e){case"bigint":return e;case"number":return h(Number.isInteger(e),"underflow",t||"value",e),h(e>=-qt&&e<=qt,"overflow",t||"value",e),BigInt(e);case"string":try{if(e==="")throw new Error("empty string");return e[0]==="-"&&e[1]!=="-"?-BigInt(e.substring(1)):BigInt(e)}catch(r){h(!1,`invalid BigNumberish string: ${r.message}`,t||"value",e)}}h(!1,"invalid BigNumberish value",t||"value",e)}function ne(e,t){let r=ht(e,t);return F(r>=we,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),r}var Eo="0123456789abcdef";function ke(e){if(e instanceof Uint8Array){let t="0x0";for(let r of e)t+=Eo[r>>4],t+=Eo[r&15];return BigInt(t)}return ht(e)}function dt(e,t){switch(typeof e){case"bigint":return h(e>=-qt&&e<=qt,"overflow",t||"value",e),Number(e);case"number":return h(Number.isInteger(e),"underflow",t||"value",e),h(e>=-qt&&e<=qt,"overflow",t||"value",e),e;case"string":try{if(e==="")throw new Error("empty string");return dt(BigInt(e),t)}catch(r){h(!1,`invalid numeric string: ${r.message}`,t||"value",e)}}h(!1,"invalid numeric value",t||"value",e)}function Hr(e){return dt(ke(e))}function ie(e,t){let o=ne(e,"value").toString(16);if(t==null)o.length%2&&(o="0"+o);else{let a=dt(t,"width");for(F(a*2>=o.length,`value exceeds width (${a} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});o.length<a*2;)o="0"+o}return"0x"+o}function Br(e){let t=ne(e,"value");if(t===we)return new Uint8Array([]);let r=t.toString(16);r.length%2&&(r="0"+r);let o=new Uint8Array(r.length/2);for(let a=0;a<o.length;a++){let n=a*2;o[a]=parseInt(r.substring(n,n+2),16)}return o}function En(e,t,r,o,a){h(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",r)}function To(e,t,r,o,a){if(e==="BAD_PREFIX"||e==="UNEXPECTED_CONTINUE"){let n=0;for(let i=t+1;i<r.length&&r[i]>>6===2;i++)n++;return n}return e==="OVERRUN"?r.length-t-1:0}function Tn(e,t,r,o,a){return e==="OVERLONG"?(h(typeof a=="number","invalid bad code point for replacement","badCodepoint",a),o.push(a),0):(o.push(65533),To(e,t,r,o,a))}var Co=Object.freeze({error:En,ignore:To,replace:Tn});function Cn(e,t){t==null&&(t=Co.error);let r=J(e,"bytes"),o=[],a=0;for(;a<r.length;){let n=r[a++];if(n>>7===0){o.push(n);continue}let i=null,s=null;if((n&224)===192)i=1,s=127;else if((n&240)===224)i=2,s=2047;else if((n&248)===240)i=3,s=65535;else{(n&192)===128?a+=t("UNEXPECTED_CONTINUE",a-1,r,o):a+=t("BAD_PREFIX",a-1,r,o);continue}if(a-1+i>=r.length){a+=t("OVERRUN",a-1,r,o);continue}let c=n&(1<<8-i-1)-1;for(let l=0;l<i;l++){let d=r[a];if((d&192)!=128){a+=t("MISSING_CONTINUE",a,r,o),c=null;break}c=c<<6|d&63,a++}if(c!==null){if(c>1114111){a+=t("OUT_OF_RANGE",a-1-i,r,o,c);continue}if(c>=55296&&c<=57343){a+=t("UTF16_SURROGATE",a-1-i,r,o,c);continue}if(c<=s){a+=t("OVERLONG",a-1-i,r,o,c);continue}o.push(c)}}return o}function se(e,t){h(typeof e=="string","invalid string value","str",e),t!=null&&(Lr(t),e=e.normalize(t));let r=[];for(let o=0;o<e.length;o++){let a=e.charCodeAt(o);if(a<128)r.push(a);else if(a<2048)r.push(a>>6|192),r.push(a&63|128);else if((a&64512)==55296){o++;let n=e.charCodeAt(o);h(o<e.length&&(n&64512)===56320,"invalid surrogate pair","str",e);let i=65536+((a&1023)<<10)+(n&1023);r.push(i>>18|240),r.push(i>>12&63|128),r.push(i>>6&63|128),r.push(i&63|128)}else r.push(a>>12|224),r.push(a>>6&63|128),r.push(a&63|128)}return new Uint8Array(r)}function Sn(e){return e.map(t=>t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10&1023)+55296,(t&1023)+56320))).join("")}function $r(e,t){return Sn(Cn(e,t))}var W=32,jr=new Uint8Array(W),_n=["then"],Ie={},vo=new WeakMap;function Ht(e){return vo.get(e)}function So(e,t){vo.set(e,t)}function ce(e,t){let r=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw r.error=t,r}function Vr(e,t,r){return e.indexOf(null)>=0?t.map((o,a)=>o instanceof yt?Vr(Ht(o),o,r):o):e.reduce((o,a,n)=>{let i=t.getValue(a);return a in o||(r&&i instanceof yt&&(i=Vr(Ht(i),i,r)),o[a]=i),o},{})}var yt=class e extends Array{#t;constructor(...t){let r=t[0],o=t[1],a=(t[2]||[]).slice(),n=!0;r!==Ie&&(o=t,a=[],n=!1),super(o.length),o.forEach((c,l)=>{this[l]=c});let i=a.reduce((c,l)=>(typeof l=="string"&&c.set(l,(c.get(l)||0)+1),c),new Map);if(So(this,Object.freeze(o.map((c,l)=>{let d=a[l];return d!=null&&i.get(d)===1?d:null}))),this.#t=[],this.#t==null&&this.#t,!n)return;Object.freeze(this);let s=new Proxy(this,{get:(c,l,d)=>{if(typeof l=="string"){if(l.match(/^[0-9]+$/)){let b=dt(l,"%index");if(b<0||b>=this.length)throw new RangeError("out of result range");let x=c[b];return x instanceof Error&&ce(`index ${b}`,x),x}if(_n.indexOf(l)>=0)return Reflect.get(c,l,d);let C=c[l];if(C instanceof Function)return function(...b){return C.apply(this===d?c:this,b)};if(!(l in c))return c.getValue.apply(this===d?c:this,[l])}return Reflect.get(c,l,d)}});return So(s,Ht(this)),s}toArray(t){let r=[];return this.forEach((o,a)=>{o instanceof Error&&ce(`index ${a}`,o),t&&o instanceof e&&(o=o.toArray(t)),r.push(o)}),r}toObject(t){let r=Ht(this);return r.reduce((o,a,n)=>(F(a!=null,`value at index ${n} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),Vr(r,this,t)),{})}slice(t,r){t==null&&(t=0),t<0&&(t+=this.length,t<0&&(t=0)),r==null&&(r=this.length),r<0&&(r+=this.length,r<0&&(r=0)),r>this.length&&(r=this.length);let o=Ht(this),a=[],n=[];for(let i=t;i<r;i++)a.push(this[i]),n.push(o[i]);return new e(Ie,a,n)}filter(t,r){let o=Ht(this),a=[],n=[];for(let i=0;i<this.length;i++){let s=this[i];s instanceof Error&&ce(`index ${i}`,s),t.call(r,s,i,this)&&(a.push(s),n.push(o[i]))}return new e(Ie,a,n)}map(t,r){let o=[];for(let a=0;a<this.length;a++){let n=this[a];n instanceof Error&&ce(`index ${a}`,n),o.push(t.call(r,n,a,this))}return o}getValue(t){let r=Ht(this).indexOf(t);if(r===-1)return;let o=this[r];return o instanceof Error&&ce(`property ${JSON.stringify(t)}`,o.error),o}static fromItems(t,r){return new e(Ie,t,r)}};function _o(e){let t=Br(e);return F(t.length<=W,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:W,offset:t.length}),t.length!==W&&(t=q(St([jr.slice(t.length%W),t]))),t}var V=class{name;type;localName;dynamic;constructor(t,r,o,a){I(this,{name:t,type:r,localName:o,dynamic:a},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(t,r){h(!1,t,this.localName,r)}},Bt=class{#t;#e;constructor(){this.#t=[],this.#e=0}get data(){return St(this.#t)}get length(){return this.#e}#r(t){return this.#t.push(t),this.#e+=t.length,t.length}appendWriter(t){return this.#r(q(t.data))}writeBytes(t){let r=q(t),o=r.length%W;return o&&(r=q(St([r,jr.slice(o)]))),this.#r(r)}writeValue(t){return this.#r(_o(t))}writeUpdatableValue(){let t=this.#t.length;return this.#t.push(jr),this.#e+=W,r=>{this.#t[t]=_o(r)}}},Ne=class e{allowLoose;#t;#e;#r;#o;#a;constructor(t,r,o){I(this,{allowLoose:!!r}),this.#t=q(t),this.#r=0,this.#o=null,this.#a=o??1024,this.#e=0}get data(){return H(this.#t)}get dataLength(){return this.#t.length}get consumed(){return this.#e}get bytes(){return new Uint8Array(this.#t)}#n(t){if(this.#o)return this.#o.#n(t);this.#r+=t,F(this.#a<1||this.#r<=this.#a*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#a} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:q(this.#t),offset:this.#e,length:t,info:{bytesRead:this.#r,dataLength:this.dataLength}})}#i(t,r,o){let a=Math.ceil(r/W)*W;return this.#e+a>this.#t.length&&(this.allowLoose&&o&&this.#e+r<=this.#t.length?a=r:F(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:q(this.#t),length:this.#t.length,offset:this.#e+a})),this.#t.slice(this.#e,this.#e+a)}subReader(t){let r=new e(this.#t.slice(this.#e+t),this.allowLoose,this.#a);return r.#o=this,r}readBytes(t,r){let o=this.#i(0,t,!!r);return this.#n(t),this.#e+=o.length,o.slice(0,t)}readValue(){return ke(this.readBytes(W))}readIndex(){return Hr(this.readBytes(W))}};import{keccak_256 as vn}from"@noble/hashes/sha3";var bo=!1,Do=function(e){return vn(e)},wo=Do;function it(e){let t=J(e,"data");return H(wo(t))}it._=Do;it.lock=function(){bo=!0};it.register=function(e){if(bo)throw new TypeError("keccak256 is locked");wo=e};Object.freeze(it);var bn=BigInt(0),Dn=BigInt(36);function ko(e){e=e.toLowerCase();let t=e.substring(2).split(""),r=new Uint8Array(40);for(let a=0;a<40;a++)r[a]=t[a].charCodeAt(0);let o=J(it(r));for(let a=0;a<40;a+=2)o[a>>1]>>4>=8&&(t[a]=t[a].toUpperCase()),(o[a>>1]&15)>=8&&(t[a+1]=t[a+1].toUpperCase());return"0x"+t.join("")}var Gr={};for(let e=0;e<10;e++)Gr[String(e)]=String(e);for(let e=0;e<26;e++)Gr[String.fromCharCode(65+e)]=String(10+e);var Io=15;function wn(e){e=e.toUpperCase(),e=e.substring(4)+e.substring(0,2)+"00";let t=e.split("").map(o=>Gr[o]).join("");for(;t.length>=Io;){let o=t.substring(0,Io);t=parseInt(o,10)%97+t.substring(o.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}var kn=(function(){let e={};for(let t=0;t<36;t++){let r="0123456789abcdefghijklmnopqrstuvwxyz"[t];e[r]=BigInt(t)}return e})();function In(e){e=e.toLowerCase();let t=bn;for(let r=0;r<e.length;r++)t=t*Dn+kn[e[r]];return t}function $t(e){if(h(typeof e=="string","invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);let t=ko(e);return h(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){h(e.substring(2,4)===wn(e),"bad icap checksum","address",e);let t=In(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return ko("0x"+t)}h(!1,"invalid address","address",e)}var pt={};function E(e,t){let r=!1;return t<0&&(r=!0,t*=-1),new B(pt,`${r?"":"u"}int${t}`,e,{signed:r,width:t})}function O(e,t){return new B(pt,`bytes${t||""}`,e,{size:t})}var No=Symbol.for("_ethers_typed"),B=class e{type;value;#t;_typedSymbol;constructor(t,r,o,a){a==null&&(a=null),Xt(pt,t,"Typed"),I(this,{_typedSymbol:No,type:r,value:o}),this.#t=a,this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(t=>t.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return this.#t}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return this.#t===!0?-1:this.#t===!1?this.value.length:null}static from(t,r){return new e(pt,t,r)}static uint8(t){return E(t,8)}static uint16(t){return E(t,16)}static uint24(t){return E(t,24)}static uint32(t){return E(t,32)}static uint40(t){return E(t,40)}static uint48(t){return E(t,48)}static uint56(t){return E(t,56)}static uint64(t){return E(t,64)}static uint72(t){return E(t,72)}static uint80(t){return E(t,80)}static uint88(t){return E(t,88)}static uint96(t){return E(t,96)}static uint104(t){return E(t,104)}static uint112(t){return E(t,112)}static uint120(t){return E(t,120)}static uint128(t){return E(t,128)}static uint136(t){return E(t,136)}static uint144(t){return E(t,144)}static uint152(t){return E(t,152)}static uint160(t){return E(t,160)}static uint168(t){return E(t,168)}static uint176(t){return E(t,176)}static uint184(t){return E(t,184)}static uint192(t){return E(t,192)}static uint200(t){return E(t,200)}static uint208(t){return E(t,208)}static uint216(t){return E(t,216)}static uint224(t){return E(t,224)}static uint232(t){return E(t,232)}static uint240(t){return E(t,240)}static uint248(t){return E(t,248)}static uint256(t){return E(t,256)}static uint(t){return E(t,256)}static int8(t){return E(t,-8)}static int16(t){return E(t,-16)}static int24(t){return E(t,-24)}static int32(t){return E(t,-32)}static int40(t){return E(t,-40)}static int48(t){return E(t,-48)}static int56(t){return E(t,-56)}static int64(t){return E(t,-64)}static int72(t){return E(t,-72)}static int80(t){return E(t,-80)}static int88(t){return E(t,-88)}static int96(t){return E(t,-96)}static int104(t){return E(t,-104)}static int112(t){return E(t,-112)}static int120(t){return E(t,-120)}static int128(t){return E(t,-128)}static int136(t){return E(t,-136)}static int144(t){return E(t,-144)}static int152(t){return E(t,-152)}static int160(t){return E(t,-160)}static int168(t){return E(t,-168)}static int176(t){return E(t,-176)}static int184(t){return E(t,-184)}static int192(t){return E(t,-192)}static int200(t){return E(t,-200)}static int208(t){return E(t,-208)}static int216(t){return E(t,-216)}static int224(t){return E(t,-224)}static int232(t){return E(t,-232)}static int240(t){return E(t,-240)}static int248(t){return E(t,-248)}static int256(t){return E(t,-256)}static int(t){return E(t,-256)}static bytes1(t){return O(t,1)}static bytes2(t){return O(t,2)}static bytes3(t){return O(t,3)}static bytes4(t){return O(t,4)}static bytes5(t){return O(t,5)}static bytes6(t){return O(t,6)}static bytes7(t){return O(t,7)}static bytes8(t){return O(t,8)}static bytes9(t){return O(t,9)}static bytes10(t){return O(t,10)}static bytes11(t){return O(t,11)}static bytes12(t){return O(t,12)}static bytes13(t){return O(t,13)}static bytes14(t){return O(t,14)}static bytes15(t){return O(t,15)}static bytes16(t){return O(t,16)}static bytes17(t){return O(t,17)}static bytes18(t){return O(t,18)}static bytes19(t){return O(t,19)}static bytes20(t){return O(t,20)}static bytes21(t){return O(t,21)}static bytes22(t){return O(t,22)}static bytes23(t){return O(t,23)}static bytes24(t){return O(t,24)}static bytes25(t){return O(t,25)}static bytes26(t){return O(t,26)}static bytes27(t){return O(t,27)}static bytes28(t){return O(t,28)}static bytes29(t){return O(t,29)}static bytes30(t){return O(t,30)}static bytes31(t){return O(t,31)}static bytes32(t){return O(t,32)}static address(t){return new e(pt,"address",t)}static bool(t){return new e(pt,"bool",!!t)}static bytes(t){return new e(pt,"bytes",t)}static string(t){return new e(pt,"string",t)}static array(t,r){throw new Error("not implemented yet")}static tuple(t,r){throw new Error("not implemented yet")}static overrides(t){return new e(pt,"overrides",Object.assign({},t))}static isTyped(t){return t&&typeof t=="object"&&"_typedSymbol"in t&&t._typedSymbol===No}static dereference(t,r){if(e.isTyped(t)){if(t.type!==r)throw new Error(`invalid type: expecetd ${r}, got ${t.type}`);return t.value}return t}};var Ae=class extends V{constructor(t){super("address","address",t,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(t,r){let o=B.dereference(r,"string");try{o=$t(o)}catch(a){return this._throwError(a.message,r)}return t.writeValue(o)}decode(t){return $t(ie(t.readValue(),20))}};var Pe=class extends V{coder;constructor(t){super(t.name,t.type,"_",t.dynamic),this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,r){return this.coder.encode(t,r)}decode(t){return this.coder.decode(t)}};function Kr(e,t,r){let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let c={};o=t.map(l=>{let d=l.localName;return F(d,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:r}),F(!c[d],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:r}),c[d]=!0,r[d]})}else h(!1,"invalid tuple value","tuple",r);h(t.length===o.length,"types/value length mismatch","tuple",r);let a=new Bt,n=new Bt,i=[];t.forEach((c,l)=>{let d=o[l];if(c.dynamic){let C=n.length;c.encode(n,d);let b=a.writeUpdatableValue();i.push(x=>{b(x+C)})}else c.encode(a,d)}),i.forEach(c=>{c(a.length)});let s=e.appendWriter(a);return s+=e.appendWriter(n),s}function Wr(e,t){let r=[],o=[],a=e.subReader(0);return t.forEach(n=>{let i=null;if(n.dynamic){let s=e.readIndex(),c=a.subReader(s);try{i=n.decode(c)}catch(l){if(be(l,"BUFFER_OVERRUN"))throw l;i=l,i.baseType=n.name,i.name=n.localName,i.type=n.type}}else try{i=n.decode(e)}catch(s){if(be(s,"BUFFER_OVERRUN"))throw s;i=s,i.baseType=n.name,i.name=n.localName,i.type=n.type}if(i==null)throw new Error("investigate");r.push(i),o.push(n.localName||null)}),yt.fromItems(r,o)}var Oe=class extends V{coder;length;constructor(t,r,o){let a=t.type+"["+(r>=0?r:"")+"]",n=r===-1||t.dynamic;super("array",a,o,n),I(this,{coder:t,length:r})}defaultValue(){let t=this.coder.defaultValue(),r=[];for(let o=0;o<this.length;o++)r.push(t);return r}encode(t,r){let o=B.dereference(r,"array");Array.isArray(o)||this._throwError("expected array value",o);let a=this.length;a===-1&&(a=o.length,t.writeValue(o.length)),ae(o.length,a,"coder array"+(this.localName?" "+this.localName:""));let n=[];for(let i=0;i<o.length;i++)n.push(this.coder);return Kr(t,n,o)}decode(t){let r=this.length;r===-1&&(r=t.readIndex(),F(r*W<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:r*W,length:t.dataLength}));let o=[];for(let a=0;a<r;a++)o.push(new Pe(this.coder));return Wr(t,o)}};var Le=class extends V{constructor(t){super("bool","bool",t,!1)}defaultValue(){return!1}encode(t,r){let o=B.dereference(r,"bool");return t.writeValue(o?1:0)}decode(t){return!!t.readValue()}};var le=class extends V{constructor(t,r){super(t,t,r,!0)}defaultValue(){return"0x"}encode(t,r){r=q(r);let o=t.writeValue(r.length);return o+=t.writeBytes(r),o}decode(t){return t.readBytes(t.readIndex(),!0)}},Re=class extends le{constructor(t){super("bytes",t)}decode(t){return H(super.decode(t))}};var Fe=class extends V{size;constructor(t,r){let o="bytes"+String(t);super(o,o,r,!1),I(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(t,r){let o=q(B.dereference(r,this.type));return o.length!==this.size&&this._throwError("incorrect data length",r),t.writeBytes(o)}decode(t){return H(t.readBytes(this.size))}};var Nn=new Uint8Array([]),Me=class extends V{constructor(t){super("null","",t,!1)}defaultValue(){return null}encode(t,r){return r!=null&&this._throwError("not null",r),t.writeBytes(Nn)}decode(t){return t.readBytes(0),null}};var An=BigInt(0),Pn=BigInt(1),On=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ue=class extends V{size;signed;constructor(t,r,o){let a=(r?"int":"uint")+t*8;super(a,a,o,!1),I(this,{size:t,signed:r},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,r){let o=ht(B.dereference(r,this.type)),a=Yt(On,W*8);if(this.signed){let n=Yt(a,this.size*8-1);(o>n||o<-(n+Pn))&&this._throwError("value out-of-bounds",r),o=Ur(o,8*W)}else(o<An||o>Yt(a,this.size*8))&&this._throwError("value out-of-bounds",r);return t.writeValue(o)}decode(t){let r=Yt(t.readValue(),this.size*8);return this.signed&&(r=Mr(r,this.size*8)),r}};var He=class extends le{constructor(t){super("string",t)}defaultValue(){return""}encode(t,r){return super.encode(t,se(B.dereference(r,"string")))}decode(t){return $r(super.decode(t))}};var jt=class extends V{coders;constructor(t,r){let o=!1,a=[];t.forEach(i=>{i.dynamic&&(o=!0),a.push(i.type)});let n="tuple("+a.join(",")+")";super("tuple",n,r,o),I(this,{coders:Object.freeze(t.slice())})}defaultValue(){let t=[];this.coders.forEach(o=>{t.push(o.defaultValue())});let r=this.coders.reduce((o,a)=>{let n=a.localName;return n&&(o[n]||(o[n]=0),o[n]++),o},{});return this.coders.forEach((o,a)=>{let n=o.localName;!n||r[n]!==1||(n==="length"&&(n="_length"),t[n]==null&&(t[n]=t[a]))}),Object.freeze(t)}encode(t,r){let o=B.dereference(r,"tuple");return Kr(t,this.coders,o)}decode(t){return Wr(t,this.coders)}};function wt(e){return it(se(e))}function Y(e){let t=new Set;return e.forEach(r=>t.add(r)),Object.freeze(t)}var Ln="external public payable override",Rn=Y(Ln.split(" ")),Bo="constant external internal payable private public pure view override",Fn=Y(Bo.split(" ")),$o="constructor error event fallback function receive struct",jo=Y($o.split(" ")),Vo="calldata memory storage payable indexed",Mn=Y(Vo.split(" ")),Un="tuple returns",Hn=[$o,Vo,Un,Bo].join(" "),Bn=Y(Hn.split(" ")),$n={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},jn=new RegExp("^(\\s*)"),Vn=new RegExp("^([0-9]+)"),Gn=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Go=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),Ko=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),ut=class e{#t;#e;get offset(){return this.#t}get length(){return this.#e.length-this.#t}constructor(t){this.#t=0,this.#e=t.slice()}clone(){return new e(this.#e)}reset(){this.#t=0}#r(t=0,r=0){return new e(this.#e.slice(t,r).map(o=>Object.freeze(Object.assign({},o,{match:o.match-t,linkBack:o.linkBack-t,linkNext:o.linkNext-t}))))}popKeyword(t){let r=this.peek();if(r.type!=="KEYWORD"||!t.has(r.text))throw new Error(`expected keyword ${r.text}`);return this.pop().text}popType(t){if(this.peek().type!==t){let r=this.peek();throw new Error(`expected ${t}; got ${r.type} ${JSON.stringify(r.text)}`)}return this.pop().text}popParen(){let t=this.peek();if(t.type!=="OPEN_PAREN")throw new Error("bad start");let r=this.#r(this.#t+1,t.match+1);return this.#t=t.match+1,r}popParams(){let t=this.peek();if(t.type!=="OPEN_PAREN")throw new Error("bad start");let r=[];for(;this.#t<t.match-1;){let o=this.peek().linkNext;r.push(this.#r(this.#t+1,o)),this.#t=o}return this.#t=t.match+1,r}peek(){if(this.#t>=this.#e.length)throw new Error("out-of-bounds");return this.#e[this.#t]}peekKeyword(t){let r=this.peekType("KEYWORD");return r!=null&&t.has(r)?r:null}peekType(t){if(this.length===0)return null;let r=this.peek();return r.type===t?r.text:null}pop(){let t=this.peek();return this.#t++,t}toString(){let t=[];for(let r=this.#t;r<this.#e.length;r++){let o=this.#e[r];t.push(`${o.type}:${o.text}`)}return`<TokenString ${t.join(" ")}>`}};function Pt(e){let t=[],r=i=>{let s=n<e.length?JSON.stringify(e[n]):"$EOI";throw new Error(`invalid token ${s} at ${n}: ${i}`)},o=[],a=[],n=0;for(;n<e.length;){let i=e.substring(n),s=i.match(jn);s&&(n+=s[1].length,i=e.substring(n));let c={depth:o.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:n,value:-1};t.push(c);let l=$n[i[0]]||"";if(l){if(c.type=l,c.text=i[0],n++,l==="OPEN_PAREN")o.push(t.length-1),a.push(t.length-1);else if(l=="CLOSE_PAREN")o.length===0&&r("no matching open bracket"),c.match=o.pop(),t[c.match].match=t.length-1,c.depth--,c.linkBack=a.pop(),t[c.linkBack].linkNext=t.length-1;else if(l==="COMMA")c.linkBack=a.pop(),t[c.linkBack].linkNext=t.length-1,a.push(t.length-1);else if(l==="OPEN_BRACKET")c.type="BRACKET";else if(l==="CLOSE_BRACKET"){let d=t.pop().text;if(t.length>0&&t[t.length-1].type==="NUMBER"){let C=t.pop().text;d=C+d,t[t.length-1].value=dt(C)}if(t.length===0||t[t.length-1].type!=="BRACKET")throw new Error("missing opening bracket");t[t.length-1].text+=d}continue}if(s=i.match(Gn),s){if(c.text=s[1],n+=c.text.length,Bn.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(Ko)){c.type="TYPE";continue}c.type="ID";continue}if(s=i.match(Vn),s){c.text=s[1],c.type="NUMBER",n+=c.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(i[0])} at position ${n}`)}return new ut(t.map(i=>Object.freeze(i)))}function Ao(e,t){let r=[];for(let o in t.keys())e.has(o)&&r.push(o);if(r.length>1)throw new Error(`conflicting types: ${r.join(", ")}`)}function Be(e,t){if(t.peekKeyword(jo)){let r=t.pop().text;if(r!==e)throw new Error(`expected ${e}, got ${r}`)}return t.popType("ID")}function vt(e,t){let r=new Set;for(;;){let o=e.peekType("KEYWORD");if(o==null||t&&!t.has(o))break;if(e.pop(),r.has(o))throw new Error(`duplicate keywords: ${JSON.stringify(o)}`);r.add(o)}return Object.freeze(r)}function Wo(e){let t=vt(e,Fn);return Ao(t,Y("constant payable nonpayable".split(" "))),Ao(t,Y("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function _t(e,t){return e.popParams().map(r=>G.from(r,t))}function zo(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return ht(e.pop().text);throw new Error("invalid gas")}return null}function Vt(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}var Kn=new RegExp(/^(.*)\[([0-9]*)\]$/);function Po(e){let t=e.match(Ko);if(h(t,"invalid type","type",e),e==="uint")return"uint256";if(e==="int")return"int256";if(t[2]){let r=parseInt(t[2]);h(r!==0&&r<=32,"invalid bytes length","type",e)}else if(t[3]){let r=parseInt(t[3]);h(r!==0&&r<=256&&r%8===0,"invalid numeric width","type",e)}return e}var $={},Z=Symbol.for("_ethers_internal"),Oo="_ParamTypeInternal",Lo="_ErrorInternal",Ro="_EventInternal",Fo="_ConstructorInternal",Mo="_FallbackInternal",Uo="_FunctionInternal",Ho="_StructInternal",G=class e{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(t,r,o,a,n,i,s,c){if(Xt(t,$,"ParamType"),Object.defineProperty(this,Z,{value:Oo}),i&&(i=Object.freeze(i.slice())),a==="array"){if(s==null||c==null)throw new Error("")}else if(s!=null||c!=null)throw new Error("");if(a==="tuple"){if(i==null)throw new Error("")}else if(i!=null)throw new Error("");I(this,{name:r,type:o,baseType:a,indexed:n,components:i,arrayLength:s,arrayChildren:c})}format(t){if(t==null&&(t="sighash"),t==="json"){let o=this.name||"";if(this.isArray()){let n=JSON.parse(this.arrayChildren.format("json"));return n.name=o,n.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(n)}let a={type:this.baseType==="tuple"?"tuple":this.type,name:o};return typeof this.indexed=="boolean"&&(a.indexed=this.indexed),this.isTuple()&&(a.components=this.components.map(n=>JSON.parse(n.format(t)))),JSON.stringify(a)}let r="";return this.isArray()?(r+=this.arrayChildren.format(t),r+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?r+="("+this.components.map(o=>o.format(t)).join(t==="full"?", ":",")+")":r+=this.type,t!=="sighash"&&(this.indexed===!0&&(r+=" indexed"),t==="full"&&this.name&&(r+=" "+this.name)),r}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(t,r){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw new Error("array is wrong length");let o=this;return t.map(a=>o.arrayChildren.walk(a,r))}if(this.isTuple()){if(!Array.isArray(t))throw new Error("invalid tuple value");if(t.length!==this.components.length)throw new Error("array is wrong length");let o=this;return t.map((a,n)=>o.components[n].walk(a,r))}return r(this.type,t)}#t(t,r,o,a){if(this.isArray()){if(!Array.isArray(r))throw new Error("invalid array value");if(this.arrayLength!==-1&&r.length!==this.arrayLength)throw new Error("array is wrong length");let i=this.arrayChildren,s=r.slice();s.forEach((c,l)=>{i.#t(t,c,o,d=>{s[l]=d})}),a(s);return}if(this.isTuple()){let i=this.components,s;if(Array.isArray(r))s=r.slice();else{if(r==null||typeof r!="object")throw new Error("invalid tuple value");s=i.map(c=>{if(!c.name)throw new Error("cannot use object value with unnamed components");if(!(c.name in r))throw new Error(`missing value for component ${c.name}`);return r[c.name]})}if(s.length!==this.components.length)throw new Error("array is wrong length");s.forEach((c,l)=>{i[l].#t(t,c,o,d=>{s[l]=d})}),a(s);return}let n=o(this.type,r);n.then?t.push((async function(){a(await n)})()):a(n)}async walkAsync(t,r){let o=[],a=[t];return this.#t(o,t,r,n=>{a[0]=n}),o.length&&await Promise.all(o),a[0]}static from(t,r){if(e.isParamType(t))return t;if(typeof t=="string")try{return e.from(Pt(t),r)}catch{h(!1,"invalid param type","obj",t)}else if(t instanceof ut){let s="",c="",l=null;vt(t,Y(["tuple"])).has("tuple")||t.peekType("OPEN_PAREN")?(c="tuple",l=t.popParams().map(S=>e.from(S)),s=`tuple(${l.map(S=>S.format()).join(",")})`):(s=Po(t.popType("TYPE")),c=s);let d=null,C=null;for(;t.length&&t.peekType("BRACKET");){let S=t.pop();d=new e($,"",s,c,null,l,C,d),C=S.value,s+=S.text,c="array",l=null}let b=null;if(vt(t,Mn).has("indexed")){if(!r)throw new Error("");b=!0}let _=t.peekType("ID")?t.pop().text:"";if(t.length)throw new Error("leftover tokens");return new e($,_,s,c,b,l,C,d)}let o=t.name;h(!o||typeof o=="string"&&o.match(Go),"invalid name","obj.name",o);let a=t.indexed;a!=null&&(h(r,"parameter cannot be indexed","obj.indexed",t.indexed),a=!!a);let n=t.type,i=n.match(Kn);if(i){let s=parseInt(i[2]||"-1"),c=e.from({type:i[1],components:t.components});return new e($,o||"",n,"array",a,null,s,c)}if(n==="tuple"||n.startsWith("tuple(")||n.startsWith("(")){let s=t.components!=null?t.components.map(l=>e.from(l)):null;return new e($,o||"",n,"tuple",a,s,null,null)}return n=Po(t.type),new e($,o||"",n,n,a,null,null,null)}static isParamType(t){return t&&t[Z]===Oo}},At=class e{type;inputs;constructor(t,r,o){Xt(t,$,"Fragment"),o=Object.freeze(o.slice()),I(this,{type:r,inputs:o})}static from(t){if(typeof t=="string"){try{e.from(JSON.parse(t))}catch{}return e.from(Pt(t))}if(t instanceof ut)switch(t.peekKeyword(jo)){case"constructor":return It.from(t);case"error":return tt.from(t);case"event":return kt.from(t);case"fallback":case"receive":return pe.from(t);case"function":return Nt.from(t);case"struct":return Zt.from(t)}else if(typeof t=="object"){switch(t.type){case"constructor":return It.from(t);case"error":return tt.from(t);case"event":return kt.from(t);case"fallback":case"receive":return pe.from(t);case"function":return Nt.from(t);case"struct":return Zt.from(t)}F(!1,`unsupported type: ${t.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}h(!1,"unsupported frgament object","obj",t)}static isConstructor(t){return It.isFragment(t)}static isError(t){return tt.isFragment(t)}static isEvent(t){return kt.isFragment(t)}static isFunction(t){return Nt.isFragment(t)}static isStruct(t){return Zt.isFragment(t)}},Gt=class extends At{name;constructor(t,r,o,a){super(t,r,a),h(typeof o=="string"&&o.match(Go),"invalid identifier","name",o),a=Object.freeze(a.slice()),I(this,{name:o})}};function de(e,t){return"("+t.map(r=>r.format(e)).join(e==="full"?", ":",")+")"}var tt=class e extends Gt{constructor(t,r,o){super(t,"error",r,o),Object.defineProperty(this,Z,{value:Lo})}get selector(){return wt(this.format("sighash")).substring(0,10)}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(o=>JSON.parse(o.format(t)))});let r=[];return t!=="sighash"&&r.push("error"),r.push(this.name+de(t,this.inputs)),r.join(" ")}static from(t){if(e.isFragment(t))return t;if(typeof t=="string")return e.from(Pt(t));if(t instanceof ut){let r=Be("error",t),o=_t(t);return Vt(t),new e($,r,o)}return new e($,t.name,t.inputs?t.inputs.map(G.from):[])}static isFragment(t){return t&&t[Z]===Lo}},kt=class e extends Gt{anonymous;constructor(t,r,o,a){super(t,"event",r,o),Object.defineProperty(this,Z,{value:Ro}),I(this,{anonymous:a})}get topicHash(){return wt(this.format("sighash"))}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(o=>JSON.parse(o.format(t)))});let r=[];return t!=="sighash"&&r.push("event"),r.push(this.name+de(t,this.inputs)),t!=="sighash"&&this.anonymous&&r.push("anonymous"),r.join(" ")}static getTopicHash(t,r){return r=(r||[]).map(a=>G.from(a)),new e($,t,r,!1).topicHash}static from(t){if(e.isFragment(t))return t;if(typeof t=="string")try{return e.from(Pt(t))}catch{h(!1,"invalid event fragment","obj",t)}else if(t instanceof ut){let r=Be("event",t),o=_t(t,!0),a=!!vt(t,Y(["anonymous"])).has("anonymous");return Vt(t),new e($,r,o,a)}return new e($,t.name,t.inputs?t.inputs.map(r=>G.from(r,!0)):[],!!t.anonymous)}static isFragment(t){return t&&t[Z]===Ro}},It=class e extends At{payable;gas;constructor(t,r,o,a,n){super(t,r,o),Object.defineProperty(this,Z,{value:Fo}),I(this,{payable:a,gas:n})}format(t){if(F(t!=null&&t!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),t==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(o=>JSON.parse(o.format(t)))});let r=[`constructor${de(t,this.inputs)}`];return this.payable&&r.push("payable"),this.gas!=null&&r.push(`@${this.gas.toString()}`),r.join(" ")}static from(t){if(e.isFragment(t))return t;if(typeof t=="string")try{return e.from(Pt(t))}catch{h(!1,"invalid constuctor fragment","obj",t)}else if(t instanceof ut){vt(t,Y(["constructor"]));let r=_t(t),o=!!vt(t,Rn).has("payable"),a=zo(t);return Vt(t),new e($,"constructor",r,o,a)}return new e($,"constructor",t.inputs?t.inputs.map(G.from):[],!!t.payable,t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[Z]===Fo}},pe=class e extends At{payable;constructor(t,r,o){super(t,"fallback",r),Object.defineProperty(this,Z,{value:Mo}),I(this,{payable:o})}format(t){let r=this.inputs.length===0?"receive":"fallback";if(t==="json"){let o=this.payable?"payable":"nonpayable";return JSON.stringify({type:r,stateMutability:o})}return`${r}()${this.payable?" payable":""}`}static from(t){if(e.isFragment(t))return t;if(typeof t=="string")try{return e.from(Pt(t))}catch{h(!1,"invalid fallback fragment","obj",t)}else if(t instanceof ut){let r=t.toString(),o=t.peekKeyword(Y(["fallback","receive"]));if(h(o,"type must be fallback or receive","obj",r),t.popKeyword(Y(["fallback","receive"]))==="receive"){let s=_t(t);return h(s.length===0,"receive cannot have arguments","obj.inputs",s),vt(t,Y(["payable"])),Vt(t),new e($,[],!0)}let n=_t(t);n.length?h(n.length===1&&n[0].type==="bytes","invalid fallback inputs","obj.inputs",n.map(s=>s.format("minimal")).join(", ")):n=[G.from("bytes")];let i=Wo(t);if(h(i==="nonpayable"||i==="payable","fallback cannot be constants","obj.stateMutability",i),vt(t,Y(["returns"])).has("returns")){let s=_t(t);h(s.length===1&&s[0].type==="bytes","invalid fallback outputs","obj.outputs",s.map(c=>c.format("minimal")).join(", "))}return Vt(t),new e($,n,i==="payable")}if(t.type==="receive")return new e($,[],!0);if(t.type==="fallback"){let r=[G.from("bytes")],o=t.stateMutability==="payable";return new e($,r,o)}h(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[Z]===Mo}},Nt=class e extends Gt{constant;outputs;stateMutability;payable;gas;constructor(t,r,o,a,n,i){super(t,"function",r,a),Object.defineProperty(this,Z,{value:Uo}),n=Object.freeze(n.slice()),I(this,{constant:o==="view"||o==="pure",gas:i,outputs:n,payable:o==="payable",stateMutability:o})}get selector(){return wt(this.format("sighash")).substring(0,10)}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(o=>JSON.parse(o.format(t))),outputs:this.outputs.map(o=>JSON.parse(o.format(t)))});let r=[];return t!=="sighash"&&r.push("function"),r.push(this.name+de(t,this.inputs)),t!=="sighash"&&(this.stateMutability!=="nonpayable"&&r.push(this.stateMutability),this.outputs&&this.outputs.length&&(r.push("returns"),r.push(de(t,this.outputs))),this.gas!=null&&r.push(`@${this.gas.toString()}`)),r.join(" ")}static getSelector(t,r){return r=(r||[]).map(a=>G.from(a)),new e($,t,"view",r,[],null).selector}static from(t){if(e.isFragment(t))return t;if(typeof t=="string")try{return e.from(Pt(t))}catch{h(!1,"invalid function fragment","obj",t)}else if(t instanceof ut){let o=Be("function",t),a=_t(t),n=Wo(t),i=[];vt(t,Y(["returns"])).has("returns")&&(i=_t(t));let s=zo(t);return Vt(t),new e($,o,n,a,i,s)}let r=t.stateMutability;return r==null&&(r="payable",typeof t.constant=="boolean"?(r="view",t.constant||(r="payable",typeof t.payable=="boolean"&&!t.payable&&(r="nonpayable"))):typeof t.payable=="boolean"&&!t.payable&&(r="nonpayable")),new e($,t.name,r,t.inputs?t.inputs.map(G.from):[],t.outputs?t.outputs.map(G.from):[],t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[Z]===Uo}},Zt=class e extends Gt{constructor(t,r,o){super(t,"struct",r,o),Object.defineProperty(this,Z,{value:Ho})}format(){throw new Error("@TODO")}static from(t){if(typeof t=="string")try{return e.from(Pt(t))}catch{h(!1,"invalid struct fragment","obj",t)}else if(t instanceof ut){let r=Be("struct",t),o=_t(t);return Vt(t),new e($,r,o)}return new e($,t.name,t.inputs?t.inputs.map(G.from):[])}static isFragment(t){return t&&t[Z]===Ho}};var ft=new Map;ft.set(0,"GENERIC_PANIC");ft.set(1,"ASSERT_FALSE");ft.set(17,"OVERFLOW");ft.set(18,"DIVIDE_BY_ZERO");ft.set(33,"ENUM_RANGE_ERROR");ft.set(34,"BAD_STORAGE_DATA");ft.set(49,"STACK_UNDERFLOW");ft.set(50,"ARRAY_RANGE_ERROR");ft.set(65,"OUT_OF_MEMORY");ft.set(81,"UNINITIALIZED_FUNCTION_CALL");var Wn=new RegExp(/^bytes([0-9]*)$/),zn=new RegExp(/^(u?int)([0-9]*)$/),zr=null,Xo=1024;function Xn(e,t,r,o){let a="missing revert data",n=null,i=null,s=null;if(r){a="execution reverted";let l=J(r);if(r=H(r),l.length===0)a+=" (no data present; likely require(false) occurred",n="require(false)";else if(l.length%32!==4)a+=" (could not decode reason; invalid data length)";else if(H(l.slice(0,4))==="0x08c379a0")try{n=o.decode(["string"],l.slice(4))[0],s={signature:"Error(string)",name:"Error",args:[n]},a+=`: ${JSON.stringify(n)}`}catch{a+=" (could not decode reason; invalid string data)"}else if(H(l.slice(0,4))==="0x4e487b71")try{let d=Number(o.decode(["uint256"],l.slice(4))[0]);s={signature:"Panic(uint256)",name:"Panic",args:[d]},n=`Panic due to ${ft.get(d)||"UNKNOWN"}(${d})`,a+=`: ${n}`}catch{a+=" (could not decode panic code)"}else a+=" (unknown custom error)"}let c={to:t.to?$t(t.to):null,data:t.data||"0x"};return t.from&&(c.from=$t(t.from)),De(a,"CALL_EXCEPTION",{action:e,data:r,reason:n,transaction:c,invocation:i,revert:s})}var bt=class e{#t(t){if(t.isArray())return new Oe(this.#t(t.arrayChildren),t.arrayLength,t.name);if(t.isTuple())return new jt(t.components.map(o=>this.#t(o)),t.name);switch(t.baseType){case"address":return new Ae(t.name);case"bool":return new Le(t.name);case"string":return new He(t.name);case"bytes":return new Re(t.name);case"":return new Me(t.name)}let r=t.type.match(zn);if(r){let o=parseInt(r[2]||"256");return h(o!==0&&o<=256&&o%8===0,"invalid "+r[1]+" bit length","param",t),new Ue(o/8,r[1]==="int",t.name)}if(r=t.type.match(Wn),r){let o=parseInt(r[1]);return h(o!==0&&o<=32,"invalid bytes length","param",t),new Fe(o,t.name)}h(!1,"invalid type","type",t.type)}getDefaultValue(t){let r=t.map(a=>this.#t(G.from(a)));return new jt(r,"_").defaultValue()}encode(t,r){ae(r.length,t.length,"types/values length mismatch");let o=t.map(i=>this.#t(G.from(i))),a=new jt(o,"_"),n=new Bt;return a.encode(n,r),n.data}decode(t,r,o){let a=t.map(i=>this.#t(G.from(i)));return new jt(a,"_").decode(new Ne(r,o,Xo))}static _setDefaultMaxInflation(t){h(typeof t=="number"&&Number.isInteger(t),"invalid defaultMaxInflation factor","value",t),Xo=t}static defaultAbiCoder(){return zr==null&&(zr=new e),zr}static getBuiltinCallException(t,r,o){return Xn(t,r,o,e.defaultAbiCoder())}};var ue=class{fragment;name;signature;topic;args;constructor(t,r,o){let a=t.name,n=t.format();I(this,{fragment:t,name:a,signature:n,topic:r,args:o})}},fe=class{fragment;name;args;signature;selector;value;constructor(t,r,o,a){let n=t.name,i=t.format();I(this,{fragment:t,name:n,args:o,signature:i,selector:r,value:a})}},me=class{fragment;name;args;signature;selector;constructor(t,r,o){let a=t.name,n=t.format();I(this,{fragment:t,name:a,args:o,signature:n,selector:r})}},Qt=class{hash;_isIndexed;static isIndexed(t){return!!(t&&t._isIndexed)}constructor(t){I(this,{hash:t,_isIndexed:!0})}},Jo={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},qo={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&Jo[e.toString()]&&(t=Jo[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}},Ot=class e{fragments;deploy;fallback;receive;#t;#e;#r;#o;constructor(t){let r=[];typeof t=="string"?r=JSON.parse(t):r=t,this.#r=new Map,this.#t=new Map,this.#e=new Map;let o=[];for(let i of r)try{o.push(At.from(i))}catch(s){console.log(`[Warning] Invalid Fragment ${JSON.stringify(i)}:`,s.message)}I(this,{fragments:Object.freeze(o)});let a=null,n=!1;this.#o=this.getAbiCoder(),this.fragments.forEach((i,s)=>{let c;switch(i.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}I(this,{deploy:i});return;case"fallback":i.inputs.length===0?n=!0:(h(!a||i.payable!==a.payable,"conflicting fallback fragments",`fragments[${s}]`,i),a=i,n=a.payable);return;case"function":c=this.#r;break;case"event":c=this.#e;break;case"error":c=this.#t;break;default:return}let l=i.format();c.has(l)||c.set(l,i)}),this.deploy||I(this,{deploy:It.from("constructor()")}),I(this,{fallback:a,receive:n})}format(t){let r=t?"minimal":"full";return this.fragments.map(a=>a.format(r))}formatJson(){let t=this.fragments.map(r=>r.format("json"));return JSON.stringify(t.map(r=>JSON.parse(r)))}getAbiCoder(){return bt.defaultAbiCoder()}#a(t,r,o){if(Jt(t)){let n=t.toLowerCase();for(let i of this.#r.values())if(n===i.selector)return i;return null}if(t.indexOf("(")===-1){let n=[];for(let[i,s]of this.#r)i.split("(")[0]===t&&n.push(s);if(r){let i=r.length>0?r[r.length-1]:null,s=r.length,c=!0;B.isTyped(i)&&i.type==="overrides"&&(c=!1,s--);for(let l=n.length-1;l>=0;l--){let d=n[l].inputs.length;d!==s&&(!c||d!==s-1)&&n.splice(l,1)}for(let l=n.length-1;l>=0;l--){let d=n[l].inputs;for(let C=0;C<r.length;C++)if(B.isTyped(r[C])){if(C>=d.length){if(r[C].type==="overrides")continue;n.splice(l,1);break}if(r[C].type!==d[C].baseType){n.splice(l,1);break}}}}if(n.length===1&&r&&r.length!==n[0].inputs.length){let i=r[r.length-1];(i==null||Array.isArray(i)||typeof i!="object")&&n.splice(0,1)}if(n.length===0)return null;if(n.length>1&&o){let i=n.map(s=>JSON.stringify(s.format())).join(", ");h(!1,`ambiguous function description (i.e. matches ${i})`,"key",t)}return n[0]}let a=this.#r.get(Nt.from(t).format());return a||null}getFunctionName(t){let r=this.#a(t,null,!1);return h(r,"no matching function","key",t),r.name}hasFunction(t){return!!this.#a(t,null,!1)}getFunction(t,r){return this.#a(t,r||null,!0)}forEachFunction(t){let r=Array.from(this.#r.keys());r.sort((o,a)=>o.localeCompare(a));for(let o=0;o<r.length;o++){let a=r[o];t(this.#r.get(a),o)}}#n(t,r,o){if(Jt(t)){let n=t.toLowerCase();for(let i of this.#e.values())if(n===i.topicHash)return i;return null}if(t.indexOf("(")===-1){let n=[];for(let[i,s]of this.#e)i.split("(")[0]===t&&n.push(s);if(r){for(let i=n.length-1;i>=0;i--)n[i].inputs.length<r.length&&n.splice(i,1);for(let i=n.length-1;i>=0;i--){let s=n[i].inputs;for(let c=0;c<r.length;c++)if(B.isTyped(r[c])&&r[c].type!==s[c].baseType){n.splice(i,1);break}}}if(n.length===0)return null;if(n.length>1&&o){let i=n.map(s=>JSON.stringify(s.format())).join(", ");h(!1,`ambiguous event description (i.e. matches ${i})`,"key",t)}return n[0]}let a=this.#e.get(kt.from(t).format());return a||null}getEventName(t){let r=this.#n(t,null,!1);return h(r,"no matching event","key",t),r.name}hasEvent(t){return!!this.#n(t,null,!1)}getEvent(t,r){return this.#n(t,r||null,!0)}forEachEvent(t){let r=Array.from(this.#e.keys());r.sort((o,a)=>o.localeCompare(a));for(let o=0;o<r.length;o++){let a=r[o];t(this.#e.get(a),o)}}getError(t,r){if(Jt(t)){let a=t.toLowerCase();if(qo[a])return tt.from(qo[a].signature);for(let n of this.#t.values())if(a===n.selector)return n;return null}if(t.indexOf("(")===-1){let a=[];for(let[n,i]of this.#t)n.split("(")[0]===t&&a.push(i);if(a.length===0)return t==="Error"?tt.from("error Error(string)"):t==="Panic"?tt.from("error Panic(uint256)"):null;if(a.length>1){let n=a.map(i=>JSON.stringify(i.format())).join(", ");h(!1,`ambiguous error description (i.e. ${n})`,"name",t)}return a[0]}if(t=tt.from(t).format(),t==="Error(string)")return tt.from("error Error(string)");if(t==="Panic(uint256)")return tt.from("error Panic(uint256)");let o=this.#t.get(t);return o||null}forEachError(t){let r=Array.from(this.#t.keys());r.sort((o,a)=>o.localeCompare(a));for(let o=0;o<r.length;o++){let a=r[o];t(this.#t.get(a),o)}}_decodeParams(t,r){return this.#o.decode(t,r)}_encodeParams(t,r){return this.#o.encode(t,r)}encodeDeploy(t){return this._encodeParams(this.deploy.inputs,t||[])}decodeErrorResult(t,r){if(typeof t=="string"){let o=this.getError(t);h(o,"unknown error","fragment",t),t=o}return h(Dt(r,0,4)===t.selector,`data signature does not match error ${t.name}.`,"data",r),this._decodeParams(t.inputs,Dt(r,4))}encodeErrorResult(t,r){if(typeof t=="string"){let o=this.getError(t);h(o,"unknown error","fragment",t),t=o}return St([t.selector,this._encodeParams(t.inputs,r||[])])}decodeFunctionData(t,r){if(typeof t=="string"){let o=this.getFunction(t);h(o,"unknown function","fragment",t),t=o}return h(Dt(r,0,4)===t.selector,`data signature does not match function ${t.name}.`,"data",r),this._decodeParams(t.inputs,Dt(r,4))}encodeFunctionData(t,r){if(typeof t=="string"){let o=this.getFunction(t);h(o,"unknown function","fragment",t),t=o}return St([t.selector,this._encodeParams(t.inputs,r||[])])}decodeFunctionResult(t,r){if(typeof t=="string"){let n=this.getFunction(t);h(n,"unknown function","fragment",t),t=n}let o="invalid length for result data",a=q(r);if(a.length%32===0)try{return this.#o.decode(t.outputs,a)}catch{o="could not decode result data"}F(!1,o,"BAD_DATA",{value:H(a),info:{method:t.name,signature:t.format()}})}makeError(t,r){let o=J(t,"data"),a=bt.getBuiltinCallException("call",r,o);if(a.message.startsWith("execution reverted (unknown custom error)")){let s=H(o.slice(0,4)),c=this.getError(s);if(c)try{let l=this.#o.decode(c.inputs,o.slice(4));a.revert={name:c.name,signature:c.format(),args:l},a.reason=a.revert.signature,a.message=`execution reverted: ${a.reason}`}catch{a.message="execution reverted (coult not decode custom error)"}}let i=this.parseTransaction(r);return i&&(a.invocation={method:i.name,signature:i.signature,args:i.args}),a}encodeFunctionResult(t,r){if(typeof t=="string"){let o=this.getFunction(t);h(o,"unknown function","fragment",t),t=o}return H(this.#o.encode(t.outputs,r||[]))}encodeFilterTopics(t,r){if(typeof t=="string"){let n=this.getEvent(t);h(n,"unknown event","eventFragment",t),t=n}F(r.length<=t.inputs.length,`too many arguments for ${t.format()}`,"UNEXPECTED_ARGUMENT",{count:r.length,expectedCount:t.inputs.length});let o=[];t.anonymous||o.push(t.topicHash);let a=(n,i)=>n.type==="string"?wt(i):n.type==="bytes"?it(H(i)):(n.type==="bool"&&typeof i=="boolean"?i=i?"0x01":"0x00":n.type.match(/^u?int/)?i=ie(i):n.type.match(/^bytes/)?i=Fr(i,32):n.type==="address"&&this.#o.encode(["address"],[i]),Rr(H(i),32));for(r.forEach((n,i)=>{let s=t.inputs[i];if(!s.indexed){h(n==null,"cannot filter non-indexed parameters; must be null","contract."+s.name,n);return}n==null?o.push(null):s.baseType==="array"||s.baseType==="tuple"?h(!1,"filtering with tuples or arrays not supported","contract."+s.name,n):Array.isArray(n)?o.push(n.map(c=>a(s,c))):o.push(a(s,n))});o.length&&o[o.length-1]===null;)o.pop();return o}encodeEventLog(t,r){if(typeof t=="string"){let i=this.getEvent(t);h(i,"unknown event","eventFragment",t),t=i}let o=[],a=[],n=[];return t.anonymous||o.push(t.topicHash),h(r.length===t.inputs.length,"event arguments/values mismatch","values",r),t.inputs.forEach((i,s)=>{let c=r[s];if(i.indexed)if(i.type==="string")o.push(wt(c));else if(i.type==="bytes")o.push(it(c));else{if(i.baseType==="tuple"||i.baseType==="array")throw new Error("not implemented");o.push(this.#o.encode([i.type],[c]))}else a.push(i),n.push(c)}),{data:this.#o.encode(a,n),topics:o}}decodeEventLog(t,r,o){if(typeof t=="string"){let x=this.getEvent(t);h(x,"unknown event","eventFragment",t),t=x}if(o!=null&&!t.anonymous){let x=t.topicHash;h(Jt(o[0],32)&&o[0].toLowerCase()===x,"fragment/topic mismatch","topics[0]",o[0]),o=o.slice(1)}let a=[],n=[],i=[];t.inputs.forEach((x,_)=>{x.indexed?x.type==="string"||x.type==="bytes"||x.baseType==="tuple"||x.baseType==="array"?(a.push(G.from({type:"bytes32",name:x.name})),i.push(!0)):(a.push(x),i.push(!1)):(n.push(x),i.push(!1))});let s=o!=null?this.#o.decode(a,St(o)):null,c=this.#o.decode(n,r,!0),l=[],d=[],C=0,b=0;return t.inputs.forEach((x,_)=>{let S=null;if(x.indexed)if(s==null)S=new Qt(null);else if(i[_])S=new Qt(s[b++]);else try{S=s[b++]}catch(z){S=z}else try{S=c[C++]}catch(z){S=z}l.push(S),d.push(x.name||null)}),yt.fromItems(l,d)}parseTransaction(t){let r=J(t.data,"tx.data"),o=ht(t.value!=null?t.value:0,"tx.value"),a=this.getFunction(H(r.slice(0,4)));if(!a)return null;let n=this.#o.decode(a.inputs,r.slice(4));return new fe(a,a.selector,n,o)}parseCallResult(t){throw new Error("@TODO")}parseLog(t){let r=this.getEvent(t.topics[0]);return!r||r.anonymous?null:new ue(r,r.topicHash,this.decodeEventLog(r,t.data,t.topics))}parseError(t){let r=H(t),o=this.getError(Dt(r,0,4));if(!o)return null;let a=this.#o.decode(o.inputs,Dt(r,4));return new me(o,o.selector,a)}static from(t){return t instanceof e?t:typeof t=="string"?new e(JSON.parse(t)):typeof t.formatJson=="function"?new e(t.formatJson()):typeof t.format=="function"?new e(t.format("json")):new e(t)}};var gt={AbiDecoderDataSource:Symbol.for("AbiDecoderDataSource"),CommandDecoderDataSource:Symbol.for("CommandDecoderDataSource"),UniswapContextLoader:Symbol.for("UniswapContextLoader")};var Jn=Object.defineProperty,qn=Object.getOwnPropertyDescriptor,Yn=(e,t,r,o)=>{for(var a=o>1?void 0:o?qn(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Jn(t,r,a),a},$e=(e,t)=>(r,o)=>t(r,o,e),Zn=[f.EXTERNAL_PLUGIN,f.TOKEN],je=class{constructor(e,t,r,o){this._externalPluginDataSource=e,this._tokenDataSource=t,this._uniswapLoader=r,this._customPluginLoaders={Uniswap:this._uniswapLoader},this.logger=o("ExternalPluginContextLoader")}_customPluginLoaders;logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"to"in e&&"data"in e&&"selector"in e&&"chainId"in e&&typeof e.chainId=="number"&&N(e.to)&&e.to!=="0x"&&N(e.data)&&e.data!=="0x"&&N(e.selector)&&e.selector!=="0x"&&Zn.every(r=>t.includes(r))}async load(e){let{to:t,data:r,selector:o,chainId:a}=e,n=await this._externalPluginDataSource.getDappInfos({address:t,chainId:a,selector:o}),i=await Ar(async({liftEither:s})=>{let c=await s(n);if(!c)return[];let l={type:f.EXTERNAL_PLUGIN,payload:c.selectorDetails.serializedData.concat(c.selectorDetails.signature)},d=this._customPluginLoaders[c.selectorDetails.plugin];if(d!==void 0&&d.canHandle(e,[f.TOKEN])){let _=await d.load(e);return[l,..._]}let C=this.getDecodedCallData(c.abi,c.selectorDetails.method,r);if(C.isLeft())return[{type:f.ERROR,error:C.extract()},l];let b=C.extract(),x=c.selectorDetails.erc20OfInterest.map(async _=>this.getTokenPayload(e,_,b));return[...(await Promise.all(x)).map(_=>_.caseOf({Left:S=>({type:f.ERROR,error:S}),Right:S=>({type:f.TOKEN,payload:S})})),l]}).caseOf({Left:s=>[{type:f.ERROR,error:s}],Right:s=>s});return this.logger.debug("load result",{data:{result:i}}),i}getTokenPayload(e,t,r){let o=this.getAddressFromPath(t,r);return Ar(({fromPromise:a})=>a(this._tokenDataSource.getTokenInfosPayload({address:o,chainId:e.chainId})))}getDecodedCallData(e,t,r){try{let o=new Ot(e);return v(o.decodeFunctionData(t,r))}catch{return m(new Error("[ContextModule] ExternalPluginContextLoader: Unable to parse abi"))}}getAddressFromPath(e,t){let r=t;for(let o of e.split("."))o==="-1"?r=r[r.length-1]:r=r[o];if(!N(r))throw new Error("[ContextModule] ExternalPluginContextLoader: Unable to get address");return r}};je=Yn([y(),$e(0,p(Rt.ExternalPluginDataSource)),$e(1,p(K.TokenDataSource)),$e(2,p(gt.UniswapContextLoader)),$e(3,p(g.ContextModuleLoggerFactory))],je);var Zo=()=>new A(({bind:e})=>{e(Rt.ExternalPluginDataSource).to(ve),e(Rt.ExternalPluginContextLoader).to(je)});import Qo from"axios";var Qn=Object.defineProperty,ti=Object.getOwnPropertyDescriptor,ei=(e,t,r,o)=>{for(var a=o>1?void 0:o?ti(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Qn(t,r,a),a},ri=(e,t)=>(r,o)=>t(r,o,e),Ve=class{constructor(e){this.config=e}async getSetPluginPayload({chainId:e,address:t,selector:r}){try{let o=await Qo.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v1/ethereum/${e}/contracts/${t}/plugin-selector/${r}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}});return o.data.payload?v(o.data.payload):m(new Error("[ContextModule] HttpNftDataSource: unexpected empty response"))}catch{return m(new Error("[ContextModule] HttpNftDataSource: Failed to fetch set plugin payload"))}}async getNftInfosPayload({chainId:e,address:t}){try{let r=await Qo.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v1/ethereum/${e}/contracts/${t}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}});return r.data.payload?v(r.data.payload):m(new Error("[ContextModule] HttpNftDataSource: no nft metadata"))}catch{return m(new Error("[ContextModule] HttpNftDataSource: Failed to fetch nft informations"))}}};Ve=ei([y(),ri(0,p(g.Config))],Ve);var oi=Object.defineProperty,ai=Object.getOwnPropertyDescriptor,ni=(e,t,r,o)=>{for(var a=o>1?void 0:o?ai(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&oi(t,r,a),a},ii=(e,t)=>(r,o)=>t(r,o,e),Ge=class{constructor(e){this._dataSource=e}canHandle(e,t){return t===f.NFT&&typeof e=="object"&&e!==null&&"chainId"in e&&"address"in e}async loadField(e){return(await this._dataSource.getNftInfosPayload({address:e.address,chainId:e.chainId})).caseOf({Left:t=>({type:f.ERROR,error:t}),Right:t=>({type:f.NFT,payload:t})})}};Ge=ni([y(),ii(0,p(st.NftDataSource))],Ge);var si=Object.defineProperty,ci=Object.getOwnPropertyDescriptor,li=(e,t,r,o)=>{for(var a=o>1?void 0:o?ci(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&si(t,r,a),a},ta=(e,t)=>(r,o)=>t(r,o,e),ea=(e=>(e.Approve="0x095ea7b3",e.SetApprovalForAll="0xa22cb465",e.TransferFrom="0x23b872dd",e.SafeTransferFrom="0x42842e0e",e.SafeTransferFromWithData="0xb88d4fde",e))(ea||{}),ra=(e=>(e.SetApprovalForAll="0xa22cb465",e.SafeTransferFrom="0xf242432a",e.SafeBatchTransferFrom="0x2eb2c2d6",e))(ra||{}),di=[...Object.values(ea),...Object.values(ra)],pi=[f.PLUGIN,f.NFT],Ke=class{_dataSource;logger;constructor(e,t){this._dataSource=e,this.logger=t("NftContextLoader")}canHandle(e,t){return typeof e=="object"&&e!==null&&"to"in e&&"selector"in e&&"chainId"in e&&typeof e.chainId=="number"&&N(e.to)&&e.to!=="0x"&&N(e.selector)&&this.isSelectorSupported(e.selector)&&pi.every(r=>t.includes(r))}async load(e){let t=[],{to:r,selector:o,chainId:a}=e,n=(await this._dataSource.getSetPluginPayload({chainId:a,address:r,selector:o})).caseOf({Left:s=>({type:f.ERROR,error:s}),Right:s=>({type:f.PLUGIN,payload:s})});if(n.type===f.ERROR)return this.logger.debug("load result",{data:{result:[n]}}),[n];t.push(n);let i=(await this._dataSource.getNftInfosPayload({chainId:a,address:r})).caseOf({Left:s=>({type:f.ERROR,error:s}),Right:s=>({type:f.NFT,payload:s})});return i.type===f.ERROR?(this.logger.debug("load result",{data:{result:[i]}}),[i]):(t.push(i),this.logger.debug("load result",{data:{result:t}}),t)}isSelectorSupported(e){return Object.values(di).includes(e)}};Ke=li([y(),ta(0,p(st.NftDataSource)),ta(1,p(g.ContextModuleLoggerFactory))],Ke);var oa=()=>new A(({bind:e})=>{e(st.NftDataSource).to(Ve),e(st.NftContextLoader).to(Ke),e(st.NftContextFieldLoader).to(Ge)});import gi from"axios";var We=class{static keyUsageMap=new Map([[k.GenuineCheck,1],[k.ExchangePayload,2],[k.NftMeta,3],[k.TrustedName,4],[k.BackupProvider,5],[k.ProtectOrchestrator,6],[k.PluginMeta,7],[k.CoinMeta,8],[k.SeedIdAuth,9],[k.TxSimulationSigner,10],[k.Calldata,11],[k.Network,12],[k.LESMultisig,14]]);static mapKeyUsageForFirmware(t){return Object.values(k).includes(t)?this.keyUsageMap.get(t)??-1:-1}};var fi=Object.defineProperty,mi=Object.getOwnPropertyDescriptor,hi=(e,t,r,o)=>{for(var a=o>1?void 0:o?mi(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&fi(t,r,a),a},yi=(e,t)=>(r,o)=>t(r,o,e),ze=class{constructor(e){this.config=e}async fetchCertificate(e){let t={output:"descriptor",target_device:e.targetDevice,latest:!0,public_key_id:e.keyId,public_key_usage:e.keyUsage};try{let r=await gi.request({method:"GET",url:`${this.config.cal.url}/certificates`,params:t,headers:{[D]:`context-module/${w.version}`}});if(r.status==200&&r.data!==void 0&&r.data.length>0&&this.isValidPkiCertificateResponse(r.data[0],this.config.cal.mode)){let o=xe(Ct.appendSignatureToPayload(r.data[0].descriptor.data,r.data[0].descriptor.signatures[this.config.cal.mode],"15"));if(!o)return m(Error("[ContextModule] HttpPkiCertificateDataSource: Cannot generate payload from fetched PKI Certificate"));let a={payload:o,keyUsageNumber:We.mapKeyUsageForFirmware(e.keyUsage)};return v(a)}else return m(Error("[ContextModule] HttpPkiCertificateDataSource: failed to fetch PKI for given descriptor"))}catch{return m(Error("[ContextModule] HttpPkiCertificateDataSource: failed to fetch PKI for given descriptor"))}}isValidPkiCertificateResponse(e,t){return typeof e=="object"&&e!==null&&"descriptor"in e&&typeof e.descriptor=="object"&&e.descriptor!==null&&"data"in e.descriptor&&typeof e.descriptor.data=="string"&&"signatures"in e.descriptor&&typeof e.descriptor.signatures=="object"&&e.descriptor.signatures!==null&&t in e.descriptor.signatures&&typeof e.descriptor.signatures[t]=="string"}};ze=hi([y(),yi(0,p(g.Config))],ze);var xi=Object.defineProperty,Ei=Object.getOwnPropertyDescriptor,Ti=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ei(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&xi(t,r,a),a},Ci=(e,t)=>(r,o)=>t(r,o,e),Xe=class{_dataSource;constructor(e){this._dataSource=e}async loadCertificate(e){return(await this._dataSource.fetchCertificate(e)).orDefault(void 0)}};Xe=Ti([y(),Ci(0,p(P.PkiCertificateDataSource))],Xe);var aa=()=>new A(({bind:e})=>{e(P.PkiCertificateDataSource).to(ze),e(P.PkiCertificateLoader).to(Xe)});import Di from"axios";var Si=Object.defineProperty,_i=Object.getOwnPropertyDescriptor,vi=(e,t,r,o)=>{for(var a=o>1?void 0:o?_i(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Si(t,r,a),a},bi=(e,t)=>(r,o)=>t(r,o,e),Je=class{constructor(e){this.config=e}async getProxyImplementationAddress({proxyAddress:e,chainId:t,challenge:r,calldata:o}){let a;try{a=(await Di.request({method:"POST",url:`${this.config.metadataServiceDomain.url}/v2/ethereum/${t}/contract/proxy/delegate`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken},data:{proxy:e,data:o,challenge:r}})).data}catch{return m(new Error("[ContextModule] HttpProxyDataSource: Failed to fetch delegate proxy"))}return a?this.isProxyDelegateCallDto(a)?a.addresses[0]?v({implementationAddress:a.addresses[0],signedDescriptor:a.signedDescriptor,keyId:ct.DomainMetadataKey,keyUsage:k.TrustedName}):m(new Error(`[ContextModule] HttpProxyDataSource: No implementation address found for proxy ${e} on chain ${t}`)):m(new Error(`[ContextModule] HttpProxyDataSource: Invalid proxy delegate call response format for proxy ${e} on chain ${t}`)):m(new Error(`[ContextModule] HttpProxyDataSource: No data received for proxy ${e} on chain ${t}`))}isProxyDelegateCallDto(e){return typeof e=="object"&&e!==null&&"addresses"in e&&"signedDescriptor"in e&&Array.isArray(e.addresses)&&e.addresses.every(t=>typeof t=="string")&&typeof e.signedDescriptor=="string"}};Je=vi([y(),bi(0,p(g.Config))],Je);import Ai from"axios";var wi=Object.defineProperty,ki=Object.getOwnPropertyDescriptor,Ii=(e,t,r,o)=>{for(var a=o>1?void 0:o?ki(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&wi(t,r,a),a},Ni=(e,t)=>(r,o)=>t(r,o,e),qe=class{constructor(e){this.config=e}async getProxyImplementationAddress({proxyAddress:e,chainId:t,challenge:r}){let o;try{o=(await Ai.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v3/ethereum/${t}/contract/proxy/${e}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken},params:{challenge:r,resolver:"SAFE_GATEWAY"}})).data}catch{return m(new Error("[ContextModule] HttpSafeProxyDataSource: Failed to fetch safe proxy implementation"))}return o?this.isSafeProxyImplementationAddressDto(o)?v({implementationAddress:o.implementationAddress,signedDescriptor:o.signedDescriptor,keyId:o.keyId,keyUsage:o.keyUsage}):m(new Error(`[ContextModule] HttpSafeProxyDataSource: Invalid safe proxy response format for proxy ${e} on chain ${t}`)):m(new Error(`[ContextModule] HttpSafeProxyDataSource: No data received for proxy ${e} on chain ${t}`))}isSafeProxyImplementationAddressDto(e){return typeof e=="object"&&e!==null&&"proxyAddress"in e&&"implementationAddress"in e&&"standard"in e&&"signedDescriptor"in e&&"providedBy"in e&&"keyId"in e&&"keyUsage"in e&&typeof e.proxyAddress=="string"&&typeof e.implementationAddress=="string"&&typeof e.standard=="string"&&typeof e.signedDescriptor=="string"&&typeof e.providedBy=="string"&&typeof e.keyId=="string"&&typeof e.keyUsage=="string"}};qe=Ii([y(),Ni(0,p(g.Config))],qe);var Pi=Object.defineProperty,Oi=Object.getOwnPropertyDescriptor,Li=(e,t,r,o)=>{for(var a=o>1?void 0:o?Oi(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Pi(t,r,a),a},na=(e,t)=>(r,o)=>t(r,o,e),Ye=class{constructor(e,t){this._proxyDataSource=e,this._certificateLoader=t}canHandle(e,t){return t===f.PROXY_INFO&&typeof e=="object"&&e!==null&&"chainId"in e&&"proxyAddress"in e&&"calldata"in e&&"challenge"in e&&"deviceModelId"in e}async loadField(e){return(await this._proxyDataSource.getProxyImplementationAddress({calldata:e.calldata,proxyAddress:e.proxyAddress,chainId:e.chainId,challenge:e.challenge})).caseOf({Left:t=>Promise.resolve({type:f.ERROR,error:t}),Right:async({signedDescriptor:t,keyId:r,keyUsage:o})=>{let a=await this._certificateLoader.loadCertificate({keyId:r,keyUsage:o,targetDevice:e.deviceModelId});return{type:f.PROXY_INFO,payload:t,certificate:a}}})}};Ye=Li([y(),na(0,p(at.ProxyDataSource)),na(1,p(P.PkiCertificateLoader))],Ye);var ia=e=>new A(({bind:t})=>{e?.datasource?.proxy==="safe"?t(at.ProxyDataSource).to(qe):t(at.ProxyDataSource).to(Je),t(at.ProxyContextFieldLoader).to(Ye)});import Hi from"axios";var Ri=Object.defineProperty,Fi=Object.getOwnPropertyDescriptor,Mi=(e,t,r,o)=>{for(var a=o>1?void 0:o?Fi(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Ri(t,r,a),a},Ui=(e,t)=>(r,o)=>t(r,o,e),Ze=class{constructor(e){this.config=e}async getDescriptors({safeContractAddress:e,chainId:t,challenge:r}){try{let o=await Hi.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v2/ethereum/${t}/safe/account/${e}`,params:{challenge:r},headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}});return o.data?this.isSafeAccountDto(o.data)?v({account:{signedDescriptor:o.data.accountDescriptor.signedDescriptor,keyId:o.data.accountDescriptor.keyId,keyUsage:o.data.accountDescriptor.keyUsage},signers:{signedDescriptor:o.data.signersDescriptor.signedDescriptor,keyId:o.data.signersDescriptor.keyId,keyUsage:o.data.signersDescriptor.keyUsage}}):m(new Error("[ContextModule] HttpSafeAccountDataSource: invalid safe account response format")):m(new Error("[ContextModule] HttpSafeAccountDataSource: unexpected empty response"))}catch{return m(new Error("[ContextModule] HttpSafeAccountDataSource: Failed to fetch safe account descriptors"))}}isSafeAccountDto(e){return typeof e=="object"&&e!==null&&"accountDescriptor"in e&&"signersDescriptor"in e&&typeof e.accountDescriptor=="object"&&typeof e.signersDescriptor=="object"&&this.isSafeDescriptorDto(e.accountDescriptor)&&this.isSafeDescriptorDto(e.signersDescriptor)}isSafeDescriptorDto(e){return typeof e=="object"&&e!==null&&"signedDescriptor"in e&&"keyId"in e&&"keyUsage"in e&&typeof e.signedDescriptor=="string"&&typeof e.keyId=="string"&&typeof e.keyUsage=="string"}};Ze=Mi([Ui(0,p(g.Config))],Ze);var Bi=Object.defineProperty,$i=Object.getOwnPropertyDescriptor,ji=(e,t,r,o)=>{for(var a=o>1?void 0:o?$i(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Bi(t,r,a),a},sa=(e,t)=>(r,o)=>t(r,o,e),Vi=[f.SAFE,f.SIGNER],Qe=class{constructor(e,t){this._dataSource=e,this._certificateLoader=t}canHandle(e,t){return t.every(r=>Vi.includes(r))&&typeof e=="object"&&e!==null&&"safeContractAddress"in e&&N(e.safeContractAddress)&&e.safeContractAddress!=="0x"&&"chainId"in e&&typeof e.chainId=="number"&&"deviceModelId"in e&&e.deviceModelId!==void 0&&"challenge"in e&&typeof e.challenge=="string"&&e.challenge.length>0}async load({safeContractAddress:e,chainId:t,deviceModelId:r,challenge:o}){return(await this._dataSource.getDescriptors({safeContractAddress:e,chainId:t,challenge:o})).caseOf({Left:a=>Promise.resolve([{type:f.ERROR,error:a}]),Right:async({account:a,signers:n})=>[{type:f.SAFE,payload:a.signedDescriptor,certificate:await this._certificateLoader.loadCertificate({keyId:a.keyId,keyUsage:a.keyUsage,targetDevice:r})},{type:f.SIGNER,payload:n.signedDescriptor,certificate:await this._certificateLoader.loadCertificate({keyId:n.keyId,keyUsage:n.keyUsage,targetDevice:r})}]})}};Qe=ji([y(),sa(0,p(Ft.SafeAddressDataSource)),sa(1,p(P.PkiCertificateLoader))],Qe);var ca=()=>new A(({bind:e})=>{e(Ft.SafeAddressDataSource).to(Ze),e(Ft.SafeAddressLoader).to(Qe)});import la from"axios";var Gi=Object.defineProperty,Ki=Object.getOwnPropertyDescriptor,Wi=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ki(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Gi(t,r,a),a},zi=(e,t)=>(r,o)=>t(r,o,e),tr=class{constructor(e){if(this.config=e,!this.config.originToken)throw new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: origin token is required")}isSolanaSPLOwnerInfo(e){return typeof e!="object"||e===null?!1:typeof e.tokenAccount=="string"&&typeof e.owner=="string"&&typeof e.contract=="string"&&typeof e.signedDescriptor=="string"}async fetchAddressMetadata(e,t){return await la.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v2/solana/owner/${e}?challenge=${t}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}}).then(r=>this.isSolanaSPLOwnerInfo(r.data)?v(r.data):m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: invalid fetchAddressMetadata response shape"))).catch(()=>m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: Failed to fetch address metadata")))}async computeAddressMetadata(e,t,r){return await la.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v2/solana/computed-token-account/${e}/${t}?challenge=${r}`,headers:{[D]:`context-module/${w.version}`,"X-Ledger-Client-Origin":this.config.originToken}}).then(o=>this.isSolanaSPLOwnerInfo(o.data)?v(o.data):m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: invalid computeAddressMetadata response shape"))).catch(()=>m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: Failed to compute address metadata")))}async getOwnerInfo(e){let{tokenAddress:t,challenge:r,createATA:o}=e;if(!r)return m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: challenge is required"));let a;if(t)a=await this.fetchAddressMetadata(t,r);else if(o?.address&&o?.mintAddress)a=await this.computeAddressMetadata(o.address,o.mintAddress,r);else return m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: either tokenAddress or valid createATA must be provided"));return a.chain(n=>{let i=xe(n.signedDescriptor);return i?v({tlvDescriptor:i}):m(new Error("[ContextModule] - HttpSolanaOwnerInfoDataSource: invalid base64 tlvDescriptor received"))})}};tr=Wi([y(),zi(0,p(g.Config))],tr);var et=(e=>(e.SOLANA_TOKEN="solanaToken",e.SOLANA_LIFI="solanaLifi",e.ERROR="error",e))(et||{});var Kt={SolanaTokenDataSource:Symbol.for("SolanaTokenDataSource"),SolanaTokenContextLoader:Symbol.for("SolanaTokenContextLoader")};var Xi=Object.defineProperty,Ji=Object.getOwnPropertyDescriptor,qi=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ji(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Xi(t,r,a),a},er=(e,t)=>(r,o)=>t(r,o,e),rr=class{constructor(e,t,r,o){this._dataSource=e,this._certificateLoader=t,this._solanaTokenLoader=r,this.logger=o("DefaultSolanaContextLoader")}logger;async load(e){this.logger.debug("[load] Loading solana context",{data:{input:e}});let{deviceModelId:t}=e,r=await this._certificateLoader.loadCertificate({keyId:"domain_metadata_key",keyUsage:k.TrustedName,targetDevice:t});if(!r)return m(new Error("[ContextModule] DefaultSolanaContextLoader: trustedNamePKICertificate is missing"));let o=[{loader:this._solanaTokenLoader,expectedType:et.SOLANA_TOKEN}].map(({loader:n,expectedType:i})=>{if(n.canHandle(e,i))return n.loadField(e)}).filter(n=>n!==void 0),a=(await Promise.allSettled(o)).map(n=>n.status==="fulfilled"?n.value:void 0).filter(n=>n!==void 0).sort((n,i)=>{let s=n.type===et.SOLANA_TOKEN?0:1,c=i.type===et.SOLANA_TOKEN?0:1;return s-c});return(await this._dataSource.getOwnerInfo(e)).map(({tlvDescriptor:n})=>({trustedNamePKICertificate:r,tlvDescriptor:n,loadersResults:a}))}};rr=qi([y(),er(0,p(Mt.SolanaDataSource)),er(1,p(P.PkiCertificateLoader)),er(2,p(Kt.SolanaTokenContextLoader)),er(3,p(g.ContextModuleLoggerFactory))],rr);var da=()=>new A(({bind:e})=>{e(Mt.SolanaDataSource).to(tr),e(Mt.SolanaContextLoader).to(rr)});import es from"axios";var Yi=Object.defineProperty,Zi=Object.getOwnPropertyDescriptor,Qi=(e,t,r,o)=>{for(var a=o>1?void 0:o?Zi(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Yi(t,r,a),a},ts=(e,t)=>(r,o)=>t(r,o,e),or=class{constructor(e){this.config=e}async getTransactionDescriptorsPayload({templateId:e}){try{let{data:t}=await es.request({method:"GET",url:`${this.config.cal.url}/swap_templates`,params:{template_id:e,output:"id,chain_id,instructions,descriptors",ref:"ref=commit:866b6e7633a7a806fab7f9941bcc3df7ee640784"},headers:{[D]:`context-module/${w.version}`}});return!t||t.length===0||!t[0]?m(new Error(`[ContextModule] HttpSolanaLifiDataSource: no transaction descriptors for id ${e}`)):v(t[0])}catch{return m(new Error("[ContextModule] HttpSolanaLifiDataSource: Failed to fetch transaction descriptors"))}}};or=Qi([y(),ts(0,p(g.Config))],or);var he={SolanaLifiDataSource:Symbol.for("SolanaLifiDataSource"),SolanaLifiContextLoader:Symbol.for("SolanaLifiContextLoader")};var rs=Object.defineProperty,os=Object.getOwnPropertyDescriptor,as=(e,t,r,o)=>{for(var a=o>1?void 0:o?os(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&rs(t,r,a),a},pa=(e,t)=>(r,o)=>t(r,o,e),ar=class{constructor(e,t){this.dataSource=e,this.logger=t("SolanaLifiContextLoader")}logger;canHandle(e,t){if(t!==et.SOLANA_LIFI)return!1;if(typeof e=="object"&&e!==null&&"templateId"in e){let r=e.templateId;return typeof r=="string"&&r.length>0}return!1}async loadField(e){this.logger.debug("[loadField] Loading solana Lifi context",{data:{input:e}});let{templateId:t}=e;return(await this.dataSource.getTransactionDescriptorsPayload({templateId:t})).caseOf({Left:r=>(this.logger.error("[loadField] Error loading solana Lifi context",{data:{error:r}}),{type:et.ERROR,error:r}),Right:r=>(this.logger.debug("[loadField] Successfully loaded solana Lifi context",{data:{payload:this.pluckTransactionData(r)}}),{type:et.SOLANA_LIFI,payload:this.pluckTransactionData(r)})})}pluckTransactionData(e){return{...e.descriptors}}};ar=as([y(),pa(0,p(he.SolanaLifiDataSource)),pa(1,p(g.ContextModuleLoggerFactory))],ar);var ua=()=>new A(({bind:e})=>{e(he.SolanaLifiDataSource).to(or),e(he.SolanaLifiContextLoader).to(ar)});import ls from"axios";var ns=Object.defineProperty,is=Object.getOwnPropertyDescriptor,ss=(e,t,r,o)=>{for(var a=o>1?void 0:o?is(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&ns(t,r,a),a},cs=(e,t)=>(r,o)=>t(r,o,e),nr=class{constructor(e){this.config=e}async getTokenInfosPayload({tokenInternalId:e}){try{let{data:t}=await ls.request({method:"GET",url:`${this.config.cal.url}/tokens`,params:{id:e,output:"id,name,network,network_family,network_type,exchange_app_config_serialized,live_signature,ticker,decimals,blockchain_name,chain_id,contract_address,descriptor,descriptor_exchange_app,units,symbol",ref:`branch:${this.config.cal.branch}`},headers:{[D]:`context-module/${w.version}`}});return!t||t.length===0||!t[0]?m(new Error(`[ContextModule] HttpSolanaTokenDataSource: no token metadata for id ${e}`)):v(t[0])}catch{return m(new Error("[ContextModule] HttpSolanaTokenDataSource: Failed to fetch token informations"))}}};nr=ss([y(),cs(0,p(g.Config))],nr);var ds=Object.defineProperty,ps=Object.getOwnPropertyDescriptor,us=(e,t,r,o)=>{for(var a=o>1?void 0:o?ps(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&ds(t,r,a),a},ir=(e,t)=>(r,o)=>t(r,o,e),sr=class{constructor(e,t,r,o){this.dataSource=e,this.config=t,this._certificateLoader=r,this.logger=o("SolanaTokenContextLoader")}logger;canHandle(e,t){if(t!==et.SOLANA_TOKEN||typeof e!="object"||e===null||!("tokenInternalId"in e))return!1;let r=e.tokenInternalId;return typeof r=="string"&&r.length>0}async loadField(e){this.logger.debug("[loadField] Loading solana token context",{data:{input:e}});let{tokenInternalId:t,deviceModelId:r}=e,o=await this.dataSource.getTokenInfosPayload({tokenInternalId:t}),a=await this._certificateLoader.loadCertificate({keyId:"token_metadata_key",keyUsage:k.CoinMeta,targetDevice:r});return o.caseOf({Left:n=>(this.logger.error("[loadField] Error loading solana token context",{data:{error:n}}),{type:et.ERROR,error:n}),Right:n=>(this.logger.debug("[loadField] Successfully loaded solana token context",{data:{payload:this.pluckTokenData(n),certificate:a}}),{type:et.SOLANA_TOKEN,payload:this.pluckTokenData(n),certificate:a})})}pluckTokenData(e){let t=this.config.cal.mode||"prod";return{solanaTokenDescriptor:{data:e.descriptor.data,signature:e.descriptor.signatures[t]}}}};sr=us([y(),ir(0,p(Kt.SolanaTokenDataSource)),ir(1,p(g.Config)),ir(2,p(P.PkiCertificateLoader)),ir(3,p(g.ContextModuleLoggerFactory))],sr);var fa=()=>new A(({bind:e})=>{e(Kt.SolanaTokenDataSource).to(nr),e(Kt.SolanaTokenContextLoader).to(sr)});import gs from"axios";var fs=Object.defineProperty,ms=Object.getOwnPropertyDescriptor,hs=(e,t,r,o)=>{for(var a=o>1?void 0:o?ms(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&fs(t,r,a),a},ys=(e,t)=>(r,o)=>t(r,o,e),cr=class{constructor(e){this.config=e}async getTokenInfosPayload({chainId:e,address:t}){try{let r=(await gs.request({method:"GET",url:`${this.config.cal.url}/tokens`,params:{contract_address:t,chain_id:e,output:"descriptor",ref:`branch:${this.config.cal.branch}`},headers:{[D]:`context-module/${w.version}`}})).data?.[0];if(!r||!r.descriptor||!r.descriptor.data||!r.descriptor.signatures||typeof r.descriptor.signatures[this.config.cal.mode]!="string")return m(new Error(`[ContextModule] HttpTokenDataSource: no token metadata for address ${t} on chain ${e}`));let o=(r.descriptor.data.length/2-20-4-4).toString(16).padStart(2,"0");return v([o,r.descriptor.data,r.descriptor.signatures[this.config.cal.mode]].join(""))}catch{return m(new Error("[ContextModule] HttpTokenDataSource: Failed to fetch token informations"))}}};cr=hs([y(),ys(0,p(g.Config))],cr);var xs=Object.defineProperty,Es=Object.getOwnPropertyDescriptor,Ts=(e,t,r,o)=>{for(var a=o>1?void 0:o?Es(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&xs(t,r,a),a},ma=(e,t)=>(r,o)=>t(r,o,e),lr=class{constructor(e,t){this._dataSource=e,this._certificateLoader=t}canHandle(e,t){return t===f.TOKEN&&typeof e=="object"&&e!==null&&"chainId"in e&&"address"in e&&"deviceModelId"in e&&e.deviceModelId!==void 0}async loadField(e){let t=await this._dataSource.getTokenInfosPayload({address:e.address,chainId:e.chainId}),r=await this._certificateLoader.loadCertificate({keyId:ct.Erc20MetadataKey,keyUsage:k.CoinMeta,targetDevice:e.deviceModelId});return t.caseOf({Left:o=>({type:f.ERROR,error:o}),Right:o=>({type:f.TOKEN,payload:o,certificate:r})})}};lr=Ts([y(),ma(0,p(K.TokenDataSource)),ma(1,p(P.PkiCertificateLoader))],lr);var Cs=Object.defineProperty,Ss=Object.getOwnPropertyDescriptor,_s=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ss(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Cs(t,r,a),a},ha=(e,t)=>(r,o)=>t(r,o,e),ya=(e=>(e.Approve="0x095ea7b3",e.Transfer="0xa9059cbb",e))(ya||{}),vs=Object.values(ya),bs=[f.TOKEN],dr=class{_dataSource;logger;constructor(e,t){this._dataSource=e,this.logger=t("TokenContextLoader")}canHandle(e,t){return typeof e=="object"&&e!==null&&"to"in e&&"selector"in e&&"chainId"in e&&typeof e.chainId=="number"&&N(e.to)&&e.to!=="0x"&&N(e.selector)&&this.isSelectorSupported(e.selector)&&bs.every(r=>t.includes(r))}async load(e){let{to:t,chainId:r}=e,o=[(await this._dataSource.getTokenInfosPayload({address:t,chainId:r})).caseOf({Left:a=>({type:f.ERROR,error:a}),Right:a=>({type:f.TOKEN,payload:a})})];return this.logger.debug("load result",{data:{result:o}}),o}isSelectorSupported(e){return Object.values(vs).includes(e)}};dr=_s([y(),ha(0,p(K.TokenDataSource)),ha(1,p(g.ContextModuleLoggerFactory))],dr);var ga=()=>new A(({bind:e})=>{e(K.TokenDataSource).to(cr),e(K.TokenContextLoader).to(dr),e(K.TokenContextFieldLoader).to(lr)});import Ns from"axios";var Ds=Object.defineProperty,ws=Object.getOwnPropertyDescriptor,ks=(e,t,r,o)=>{for(var a=o>1?void 0:o?ws(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Ds(t,r,a),a},Is=(e,t)=>(r,o)=>t(r,o,e),pr=class{constructor(e){this.config=e}async getTransactionCheck({chainId:e,rawTx:t,from:r}){let o,a={tx:{from:r,raw:t},chain:e};try{o=(await Ns.request({method:"POST",url:`${this.config.web3checks.url}/ethereum/scan/tx`,data:a,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}})).data}catch{return m(new Error("[ContextModule] HttpTransactionCheckDataSource: Failed to fetch web3 checks information"))}if(!this._isTransactionCheckDto(o))return m(new Error("[ContextModule] HttpTransactionCheckDataSource: Cannot exploit transaction check data received"));let n={publicKeyId:o.public_key_id,descriptor:o.descriptor};return v(n)}_isTransactionCheckDto(e){return e!=null&&typeof e=="object"&&"public_key_id"in e&&e.public_key_id!=null&&typeof e.public_key_id=="string"&&"descriptor"in e&&e.descriptor!=null&&typeof e.descriptor=="string"}};pr=ks([y(),Is(0,p(g.Config))],pr);import Rs from"axios";var As=Object.defineProperty,Ps=Object.getOwnPropertyDescriptor,Os=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ps(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&As(t,r,a),a},Ls=(e,t)=>(r,o)=>t(r,o,e),ur=class{constructor(e){this.config=e}async getTypedDataCheck({from:e,data:t}){let r,o={msg:{from:e,data:t}};try{r=(await Rs.request({method:"POST",url:`${this.config.web3checks.url}/ethereum/scan/eip-712`,data:o,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}})).data}catch{return m(new Error("[ContextModule] HttpTypedDataCheckDataSource: Failed to fetch typed data check information"))}if(!this._isTypedDataCheckDto(r))return m(new Error("[ContextModule] HttpTypedDataCheckDataSource: Cannot exploit typed data check data received"));let a={publicKeyId:r.public_key_id,descriptor:r.descriptor};return v(a)}_isTypedDataCheckDto(e){return e!=null&&typeof e=="object"&&"public_key_id"in e&&e.public_key_id!=null&&typeof e.public_key_id=="string"&&"descriptor"in e&&e.descriptor!=null&&typeof e.descriptor=="string"}};ur=Os([y(),Ls(0,p(g.Config))],ur);var Fs=Object.defineProperty,Ms=Object.getOwnPropertyDescriptor,Us=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ms(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Fs(t,r,a),a},Xr=(e,t)=>(r,o)=>t(r,o,e),Hs=[f.TRANSACTION_CHECK],fr=class{constructor(e,t,r){this.transactionCheckDataSource=e,this.certificateLoader=t,this.logger=r("TransactionCheckContextLoader")}logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"from"in e&&e.from!==void 0&&N(e.from)&&"chainId"in e&&e.chainId!==void 0&&typeof e.chainId=="number"&&"transaction"in e&&e.transaction!==void 0&&"deviceModelId"in e&&e.deviceModelId!==void 0&&e.deviceModelId!==X.NANO_S&&typeof e.chainId=="number"&&N(e.from)&&e.from!=="0x"&&Hs.every(r=>t.includes(r))}async load(e){let{from:t,chainId:r,transaction:o}=e,a=re(o);if(!t||!a)return this.logger.debug("load result",{data:{result:[]}}),[];let n=[await(await this.transactionCheckDataSource.getTransactionCheck({chainId:r,rawTx:a,from:t})).caseOf({Left:i=>Promise.resolve({type:f.ERROR,error:i}),Right:async i=>{let s=await this.certificateLoader.loadCertificate({keyId:i.publicKeyId,keyUsage:k.TxSimulationSigner,targetDevice:e.deviceModelId});return{type:f.TRANSACTION_CHECK,payload:i.descriptor,certificate:s}}})];return this.logger.debug("load result",{data:{result:n}}),n}};fr=Us([y(),Xr(0,p(nt.TransactionCheckDataSource)),Xr(1,p(P.PkiCertificateLoader)),Xr(2,p(g.ContextModuleLoggerFactory))],fr);var Bs=Object.defineProperty,$s=Object.getOwnPropertyDescriptor,js=(e,t,r,o)=>{for(var a=o>1?void 0:o?$s(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Bs(t,r,a),a},Jr=(e,t)=>(r,o)=>t(r,o,e),Vs=[f.TRANSACTION_CHECK],mr=class{constructor(e,t,r){this.typedDataCheckDataSource=e,this.certificateLoader=t,this.logger=r("TypedDataCheckContextLoader")}logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"from"in e&&e.from!==void 0&&N(e.from)&&e.from!=="0x"&&"data"in e&&typeof e.data=="object"&&"deviceModelId"in e&&e.deviceModelId!==void 0&&e.deviceModelId!==X.NANO_S&&Vs.every(r=>t.includes(r))}async load(e){let{from:t,data:r}=e;if(!t||!r)return this.logger.debug("load result",{data:{result:[]}}),[];let o=[await(await this.typedDataCheckDataSource.getTypedDataCheck({data:r,from:t})).caseOf({Left:a=>Promise.resolve({type:f.ERROR,error:a}),Right:async a=>{let n=await this.certificateLoader.loadCertificate({keyId:a.publicKeyId,keyUsage:k.TxSimulationSigner,targetDevice:e.deviceModelId});return{type:f.TRANSACTION_CHECK,payload:a.descriptor,certificate:n}}})];return this.logger.debug("load result",{data:{result:o}}),o}};mr=js([y(),Jr(0,p(nt.TypedDataCheckDataSource)),Jr(1,p(P.PkiCertificateLoader)),Jr(2,p(g.ContextModuleLoggerFactory))],mr);var xa=()=>new A(({bind:e})=>{e(nt.TransactionCheckDataSource).to(pr),e(nt.TransactionCheckContextLoader).to(fr),e(nt.TypedDataCheckDataSource).to(ur),e(nt.TypedDataCheckContextLoader).to(mr)});import Ea from"axios";var Gs=Object.defineProperty,Ks=Object.getOwnPropertyDescriptor,Ws=(e,t,r,o)=>{for(var a=o>1?void 0:o?Ks(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Gs(t,r,a),a},zs=(e,t)=>(r,o)=>t(r,o,e),hr=class{constructor(e){this.config=e}async getDomainNamePayload({chainId:e,domain:t,challenge:r}){let o;try{o=(await Ea.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v2/names/ethereum/${e}/forward/${t}?types=eoa&sources=ens&challenge=${r}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}})).data}catch{return m(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name"))}return o?this.isTrustedNameDto(o)?v({data:o.signedDescriptor.data,keyId:o.keyId,keyUsage:o.keyUsage}):m(new Error(`[ContextModule] HttpTrustedNameDataSource: Invalid trusted name response format for domain ${t} on chain ${e}`)):m(new Error(`[ContextModule] HttpTrustedNameDataSource: No data received for domain ${t} on chain ${e}`))}async getTrustedNamePayload({chainId:e,address:t,challenge:r,sources:o,types:a}){let n;try{o=o.filter(s=>s==="ens"||s==="crypto_asset_list"),n=(await Ea.request({method:"GET",url:`${this.config.metadataServiceDomain.url}/v2/names/ethereum/${e}/reverse/${t}?types=${a.join(",")}&sources=${o.join(",")}&challenge=${r}`,headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}})).data}catch{return m(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name"))}if(!n)return m(new Error(`[ContextModule] HttpTrustedNameDataSource: No data received for address ${t} on chain ${e}`));if(!this.isTrustedNameDto(n))return m(new Error(`[ContextModule] HttpTrustedNameDataSource: Invalid trusted name response format for address ${t} on chain ${e}`));if(typeof n.signedDescriptor.signatures[this.config.cal.mode]!="string")return v({data:n.signedDescriptor.data,keyId:n.keyId,keyUsage:n.keyUsage});let i=n.signedDescriptor.signatures[this.config.cal.mode];return v({data:this.formatTrustedName(n.signedDescriptor.data,i),keyId:n.keyId,keyUsage:n.keyUsage})}formatTrustedName(e,t){t.length%2!==0&&(t="0"+t);let r="15",o=(t.length/2).toString(16);return`${e}${r}${o}${t}`}isTrustedNameDto(e){return typeof e=="object"&&e!==null&&"signedDescriptor"in e&&"keyId"in e&&"keyUsage"in e&&typeof e.keyId=="string"&&typeof e.keyUsage=="string"&&typeof e.signedDescriptor=="object"&&e.signedDescriptor!==null&&"data"in e.signedDescriptor&&"signatures"in e.signedDescriptor&&typeof e.signedDescriptor.data=="string"&&typeof e.signedDescriptor.signatures=="object"}};hr=Ws([y(),zs(0,p(g.Config))],hr);var Xs=Object.defineProperty,Js=Object.getOwnPropertyDescriptor,qs=(e,t,r,o)=>{for(var a=o>1?void 0:o?Js(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Xs(t,r,a),a},Ta=(e,t)=>(r,o)=>t(r,o,e),yr=class{constructor(e,t){this._dataSource=e,this._certificateLoader=t}canHandle(e,t){return t===f.TRUSTED_NAME&&typeof e=="object"&&e!==null&&"chainId"in e&&"address"in e&&"challenge"in e&&"types"in e&&"sources"in e&&"deviceModelId"in e&&e.deviceModelId!==void 0}async loadField(e){return await(await this._dataSource.getTrustedNamePayload({chainId:e.chainId,address:e.address,challenge:e.challenge,types:e.types,sources:e.sources})).caseOf({Left:t=>Promise.resolve({type:f.ERROR,error:t}),Right:async({data:t,keyId:r,keyUsage:o})=>{let a=await this._certificateLoader.loadCertificate({keyId:r,keyUsage:o,targetDevice:e.deviceModelId});return{type:f.TRUSTED_NAME,payload:t,certificate:a}}})}};yr=qs([y(),Ta(0,p(ot.TrustedNameDataSource)),Ta(1,p(P.PkiCertificateLoader))],yr);var Ys=Object.defineProperty,Zs=Object.getOwnPropertyDescriptor,Qs=(e,t,r,o)=>{for(var a=o>1?void 0:o?Zs(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&Ys(t,r,a),a},qr=(e,t)=>(r,o)=>t(r,o,e),tc=[f.TRUSTED_NAME],gr=class{constructor(e,t,r){this._dataSource=e,this._certificateLoader=t,this.logger=r("TrustedNameContextLoader")}logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"chainId"in e&&e.chainId!==void 0&&typeof e.chainId=="number"&&"to"in e&&e.to!==void 0&&N(e.to)&&e.to!=="0x"&&"deviceModelId"in e&&e.deviceModelId!==void 0&&tc.every(r=>t.includes(r))}async load(e){let t=await this._dataSource.getTrustedNamePayload({chainId:e.chainId,address:e.to,challenge:"",types:["eoa"],sources:["ens"]});return this.logger.debug("[ContextModule]: load result",{data:{payload:t}}),await t.caseOf({Left:r=>Promise.resolve([{type:f.ERROR,error:r}]),Right:async({data:r,keyId:o,keyUsage:a})=>{let n=await this._certificateLoader.loadCertificate({keyId:o,keyUsage:a,targetDevice:e.deviceModelId});return[{type:f.TRUSTED_NAME,payload:r,certificate:n}]}})}};gr=Qs([y(),qr(0,p(ot.TrustedNameDataSource)),qr(1,p(P.PkiCertificateLoader)),qr(2,p(g.ContextModuleLoggerFactory))],gr);var Ca=e=>new A(({bind:t})=>{e?.customTrustedNameDataSource?t(ot.TrustedNameDataSource).toConstantValue(e.customTrustedNameDataSource):t(ot.TrustedNameDataSource).to(hr),t(ot.TrustedNameContextLoader).to(gr),t(ot.TrustedNameContextFieldLoader).to(yr)});var wa=ro(Da());import nc from"axios";var Wt=(e=>(e.None="none",e.Present="present",e.VerifyingContract="verifying_contract",e))(Wt||{});var ec=Object.defineProperty,rc=Object.getOwnPropertyDescriptor,oc=(e,t,r,o)=>{for(var a=o>1?void 0:o?rc(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&ec(t,r,a),a},ac=(e,t)=>(r,o)=>t(r,o,e),Cr=class{constructor(e){this.config=e}async getTypedDataFilters({chainId:e,address:t,schema:r,version:o}){let a;try{let n=await nc.request({method:"GET",url:`${this.config.cal.url}/dapps`,params:{contracts:t,chain_id:e,output:"descriptors_eip712",descriptors_eip712_version:o,descriptors_eip712:"<set>",ref:`branch:${this.config.cal.branch}`},headers:{[D]:`context-module/${w.version}`,[U]:this.config.originToken}}),i=(0,wa.default)(JSON.stringify(this.sortTypes(r)).replace(" ","")).toString();t=t.toLowerCase();let s=(n.data??[]).map(d=>d?.descriptors_eip712?.[t]?.[i]).find(Boolean);if(!s)return m(new Error(`[ContextModule] HttpTypedDataDataSource: no typed data filters for address ${t} on chain ${e} for schema ${i}`));if(!Array.isArray(s.instructions))return m(new Error(`[ContextModule] HttpTypedDataDataSource: no message info for address ${t} on chain ${e} for schema ${i}`));let c=[],l={};for(let d of s.instructions)if(this.isInstructionContractInfo(d,this.config.cal.mode))a={displayName:d.display_name,signature:d.signatures[this.config.cal.mode],filtersCount:d.field_mappers_count};else if(o==="v1"&&this.isInstructionFieldV1(d,this.config.cal.mode))c.push({type:"raw",displayName:d.display_name,path:d.field_path,signature:d.signatures[this.config.cal.mode]});else if(this.isInstructionFieldV2(d,this.config.cal.mode))c.push({type:d.format,displayName:d.display_name,path:d.field_path,signature:d.signatures[this.config.cal.mode]});else if(this.isInstructionFieldV2WithCoinRef(d,this.config.cal.mode))c.push({type:d.format,displayName:d.display_name,path:d.field_path,signature:d.signatures[this.config.cal.mode],tokenIndex:d.coin_ref});else if(this.isInstructionFieldV2WithName(d,this.config.cal.mode))c.push({type:d.format,displayName:d.display_name,path:d.field_path,signature:d.signatures[this.config.cal.mode],types:d.name_types,sources:d.name_sources,typesAndSourcesPayload:this.formatTrustedNameTypesAndSources(d)});else if(this.isInstructionCalldataInfo(d,this.config.cal.mode))l[d.calldata_index]={displayName:d.display_name,calldataIndex:d.calldata_index,valueFlag:d.value_filter_flag,calleeFlag:this.convertCalldataPresenceFlag(d.callee_filter_flag),amountFlag:d.amount_filter_flag,spenderFlag:this.convertCalldataPresenceFlag(d.spender_filter_flag),chainIdFlag:d.chain_id_filter_flag,selectorFlag:d.selector_filter_flag,signature:d.signatures[this.config.cal.mode]};else if(this.isInstructionFieldV2Calldata(d,this.config.cal.mode))c.push({type:d.format,displayName:d.display_name,path:d.field_path,signature:d.signatures[this.config.cal.mode],calldataIndex:d.calldata_index});else return m(new Error(`[ContextModule] HttpTypedDataDataSource: invalid typed data field for address ${t} on chain ${e} for schema ${i}`));return a?v({messageInfo:a,filters:c,calldatasInfos:l}):m(new Error(`[ContextModule] HttpTypedDataDataSource: no message info for address ${t} on chain ${e} for schema ${i}`))}catch{return m(new Error("[ContextModule] HttpTypedDataDataSource: Failed to fetch typed data informations"))}}convertCalldataPresenceFlag(e){switch(e){case"none":return Wt.None;case"present":return Wt.Present;case"verifying_contract":return Wt.VerifyingContract;default:{let t=e;throw new Error(`Unhandled flag: ${t}`)}}}formatTrustedNameTypesAndSources(e){let t=e.name_types.length,r=e.name_sources.length,o=e.descriptor.slice((t+r)*2*-1,r*2*-1),a=e.descriptor.slice(r*2*-1),n=t.toString(16).padStart(2,"0"),i=r.toString(16).padStart(2,"0");return n+o+i+a}isInstructionFieldV1(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_path=="string"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"}isInstructionFieldV2(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_path=="string"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"&&typeof e.format=="string"&&["raw","datetime"].includes(e.format)&&e.coin_ref===void 0}isInstructionFieldV2WithCoinRef(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_path=="string"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"&&typeof e.format=="string"&&["token","amount"].includes(e.format)&&typeof e.coin_ref=="number"}isInstructionFieldV2WithName(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_path=="string"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"&&typeof e.format=="string"&&e.format==="trusted-name"&&e.coin_ref===void 0&&Array.isArray(e.name_types)&&Array.isArray(e.name_sources)&&e.name_types.every(r=>typeof r=="string")&&e.name_sources.every(r=>typeof r=="string")}isInstructionContractInfo(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_mappers_count=="number"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"&&e.field_path===void 0}isInstructionCalldataInfo(e,t){return typeof e=="object"&&typeof e.type=="string"&&e.type==="calldata"&&typeof e.display_name=="string"&&typeof e.calldata_index=="number"&&typeof e.value_filter_flag=="boolean"&&typeof e.chain_id_filter_flag=="boolean"&&typeof e.selector_filter_flag=="boolean"&&typeof e.amount_filter_flag=="boolean"&&["none","present","verifying_contract"].includes(e.callee_filter_flag)&&["none","present","verifying_contract"].includes(e.spender_filter_flag)&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"}isInstructionFieldV2Calldata(e,t){return typeof e=="object"&&typeof e.display_name=="string"&&typeof e.field_path=="string"&&typeof e.signatures=="object"&&typeof e.signatures[t]=="string"&&typeof e.format=="string"&&["calldata-value","calldata-callee","calldata-chain-id","calldata-selector","calldata-amount","calldata-spender"].includes(e.format)&&typeof e.calldata_index=="number"}sortTypes(e){return Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,r.map(o=>({name:o.name,type:o.type}))]))}};Cr=oc([y(),ac(0,p(g.Config))],Cr);var sc=Object.defineProperty,cc=Object.getOwnPropertyDescriptor,lc=(e,t,r,o)=>{for(var a=o>1?void 0:o?cc(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&sc(t,r,a),a},ye=(e,t)=>(r,o)=>t(r,o,e),Sr=class{constructor(e,t,r,o,a){this.dataSource=e,this.tokenDataSource=t,this.proxyDataSource=r,this._certificateLoader=o,this.logger=a("DefaultTypedDataContextLoader")}logger;async load(e){let t,r=await this.dataSource.getTypedDataFilters({address:e.verifyingContract,chainId:e.chainId,version:e.version,schema:e.schema});if(r.isLeft()){let{resolvedAddress:l,context:d}=await this.resolveProxy(e);if(d!==void 0&&(t=d,r=await this.dataSource.getTypedDataFilters({address:l,chainId:e.chainId,version:e.version,schema:e.schema})),r.isLeft()){let C={type:"error",error:r.extract()};return this.logger.debug("load result",{data:{result:C}}),C}}let{messageInfo:o,filters:a,calldatasInfos:n}=r.unsafeCoerce(),i=a.reduce((l,d)=>(l[d.path]=d,l),{}),s=await this._certificateLoader.loadCertificate({keyId:ct.Erc20MetadataKey,keyUsage:k.CoinMeta,targetDevice:e.deviceModelId}),c={type:"success",messageInfo:o,filters:i,trustedNamesAddresses:this.extractTrustedNames(a,e),tokens:await this.extractTokens(a,e),calldatas:this.extractCalldatas(a,n,e),certificate:s,proxy:t};return this.logger.debug("load result",{data:{result:c}}),c}async resolveProxy(e){let t=await this.proxyDataSource.getProxyImplementationAddress({calldata:"0x",proxyAddress:e.verifyingContract,chainId:e.chainId,challenge:e.challenge??""});if(t.isLeft())return{resolvedAddress:e.verifyingContract,context:void 0};let r=t.unsafeCoerce(),o=await this._certificateLoader.loadCertificate({keyId:r.keyId,keyUsage:r.keyUsage,targetDevice:e.deviceModelId});return{resolvedAddress:r.implementationAddress,context:{type:f.PROXY_INFO,payload:r.signedDescriptor,certificate:o}}}extractTrustedNames(e,t){return e.filter(r=>r.type==="trusted-name").reduce((r,o)=>{let a=t.fieldsValues.filter(n=>n.path===o.path);if(a.length!==0){let n=a[0],i=this.convertAddressToHexaString(n.value);r[o.path]=i}return r},{})}async extractTokens(e,t){let r={};for(let o of e){if(o.type!=="token"&&o.type!=="amount")continue;let a=o.tokenIndex;if(r[a]===void 0){if(o.type==="token"){let n=t.fieldsValues.filter(c=>c.path===o.path);if(n.length===0)continue;let i=n[0],s=this.convertAddressToHexaString(i.value);if(n.every(c=>this.convertAddressToHexaString(c.value)===s)){let c=t.chainId;(await this.tokenDataSource.getTokenInfosPayload({address:s,chainId:c})).ifRight(l=>{r[a]=l})}}else if(o.type==="amount"&&a===255){let n=t.verifyingContract,i=t.chainId;(await this.tokenDataSource.getTokenInfosPayload({address:n,chainId:i})).ifRight(s=>{r[a]=s})}}}return r}extractCalldatas(e,t,r){let o=e.reduce((n,i)=>{if(i.type==="calldata-value"||i.type==="calldata-callee"||i.type==="calldata-chain-id"||i.type==="calldata-selector"||i.type==="calldata-amount"||i.type==="calldata-spender"){let s=n[i.calldataIndex];s===void 0?n[i.calldataIndex]=[i]:s.push(i)}return n},{}),a={};for(let n in t){let i=t[n],s=o[n];if(!s)continue;let c=this.extractHexaString(s.find(S=>S.type==="calldata-value"),r,"0x"),l=this.extractHexaString(s.find(S=>S.type==="calldata-selector"),r,c.slice(0,10)),d=this.extractAddress(s.find(S=>S.type==="calldata-callee"),r,i.calleeFlag),C=this.extractAddress(s.find(S=>S.type==="calldata-spender"),r,i.spenderFlag),b=this.extractBigint(s.find(S=>S.type==="calldata-amount"),r,void 0),x=this.extractBigint(s.find(S=>S.type==="calldata-chain-id"),r,void 0),_=x!==void 0&&x<Number.MAX_SAFE_INTEGER?Number(x):r.chainId;a[n]={filter:i,subset:{chainId:_,data:c,selector:l,to:d,value:b,from:C}}}return a}extractHexaString(e,t,r){if(e!==void 0){let o=t.fieldsValues.filter(a=>a.path===e.path);if(o.length!==0)return re(o[0].value)}return r}extractAddress(e,t,r,o){if(r===Wt.VerifyingContract)return t.verifyingContract;if(e!==void 0){let a=t.fieldsValues.filter(n=>n.path===e.path);if(a.length!==0)return this.convertAddressToHexaString(a[0].value)}return o}extractBigint(e,t,r){if(e!==void 0){let o=t.fieldsValues.filter(a=>a.path===e.path);if(o.length!==0)return BigInt(re(o[0].value))}return r}convertAddressToHexaString(e){return`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").padStart(40,"0")}`}};Sr=lc([y(),ye(0,p(Ut.TypedDataDataSource)),ye(1,p(K.TokenDataSource)),ye(2,p(at.ProxyDataSource)),ye(3,p(P.PkiCertificateLoader)),ye(4,p(g.ContextModuleLoggerFactory))],Sr);var ka=()=>new A(({bind:e})=>{e(Ut.TypedDataDataSource).to(Cr),e(Ut.TypedDataContextLoader).to(Sr)});var Ia=["function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable"],Na="0x3593564c",Q=(e=>(e.V2_SWAP_EXACT_IN="V2_SWAP_EXACT_IN",e.V2_SWAP_EXACT_OUT="V2_SWAP_EXACT_OUT",e.V3_SWAP_EXACT_IN="V3_SWAP_EXACT_IN",e.V3_SWAP_EXACT_OUT="V3_SWAP_EXACT_OUT",e.WRAP_ETH="WRAP_ETH",e.UNWRAP_ETH="UNWRAP_ETH",e.PERMIT2_PERMIT="PERMIT2_PERMIT",e.PERMIT2_TRANSFER_FROM="PERMIT2_TRANSFER_FROM",e.PERMIT2_PERMIT_BATCH="PERMIT2_PERMIT_BATCH",e.PERMIT2_TRANSFER_FROM_BATCH="PERMIT2_TRANSFER_FROM_BATCH",e.PAY_PORTION="PAY_PORTION",e.SWEEP="SWEEP",e))(Q||{}),Aa={"0x08":"V2_SWAP_EXACT_IN","0x09":"V2_SWAP_EXACT_OUT","0x00":"V3_SWAP_EXACT_IN","0x01":"V3_SWAP_EXACT_OUT","0x0b":"WRAP_ETH","0x0c":"UNWRAP_ETH","0x0a":"PERMIT2_PERMIT","0x0d":"PERMIT2_TRANSFER_FROM","0x02":"PERMIT2_PERMIT_BATCH","0x03":"PERMIT2_TRANSFER_FROM_BATCH","0x06":"PAY_PORTION","0x04":"SWEEP"},Pa=["V2_SWAP_EXACT_IN","V2_SWAP_EXACT_OUT","V3_SWAP_EXACT_IN","V3_SWAP_EXACT_OUT"];var Zr=(e=>(e[e.ETHEREUM_MAINNET=1]="ETHEREUM_MAINNET",e[e.ETHEREUM_GOERLI=5]="ETHEREUM_GOERLI",e[e.ETHEREUM_SEPOLIA=11155111]="ETHEREUM_SEPOLIA",e[e.ARBITRUM_ONE=42161]="ARBITRUM_ONE",e[e.ARBITRUM_GOERLI=421613]="ARBITRUM_GOERLI",e[e.AVALANCHE_C_CHAIN=43114]="AVALANCHE_C_CHAIN",e[e.BSC=56]="BSC",e[e.BASE=8453]="BASE",e[e.BASE_GOERLI=84531]="BASE_GOERLI",e[e.BLAST=23888]="BLAST",e[e.OPTIMISM=10]="OPTIMISM",e[e.OPTIMISM_GOERLI=420]="OPTIMISM_GOERLI",e[e.POLYGON=137]="POLYGON",e[e.POLYGON_MUMBAI=80001]="POLYGON_MUMBAI",e))(Zr||{}),Oa={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",5:"0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6",11155111:"0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",421613:"0xe39Ab88f8A4777030A534146A9Ca3B52bd5D43A3",43114:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",56:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",8453:"0x4200000000000000000000000000000000000006",84531:"0x44D627f900da8AdaC7561bD73aA745F132450798",23888:"0x4300000000000000000000000000000000000004",10:"0x4200000000000000000000000000000000000006",420:"0x4200000000000000000000000000000000000006",137:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",80001:"0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889"};var dc=Object.defineProperty,pc=Object.getOwnPropertyDescriptor,uc=(e,t,r,o)=>{for(var a=o>1?void 0:o?pc(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&dc(t,r,a),a},fc=(e,t)=>(r,o)=>t(r,o,e),Qr=40,La=6,_r=class{constructor(e){this.abiDecoder=e}decode(e,t,r){switch(e){case Q.V2_SWAP_EXACT_IN:return this._decodeSwapV2(t);case Q.V2_SWAP_EXACT_OUT:return this._decodeSwapV2(t);case Q.V3_SWAP_EXACT_IN:return this._decodeSwapV3(t);case Q.V3_SWAP_EXACT_OUT:return this._decodeSwapV3(t);case Q.WRAP_ETH:return this._decodeWrappedEth(t,r);case Q.UNWRAP_ETH:return this._decodeWrappedEth(t,r);case Q.SWEEP:return this._decodeSweep(t);case Q.PERMIT2_PERMIT:case Q.PERMIT2_TRANSFER_FROM:case Q.PERMIT2_PERMIT_BATCH:case Q.PERMIT2_TRANSFER_FROM_BATCH:case Q.PAY_PORTION:return[];default:return[]}}_decodeSwapV2(e){let[,,,t]=this.abiDecoder.decode(["address","uint256","uint256","address[]","bool"],e);return!Array.isArray(t)||!t.every(N)?[]:t.map(r=>r.toLowerCase())}_decodeSwapV3(e){let[,,,t]=this.abiDecoder.decode(["address","uint256","uint256","bytes","bool"],e);if(typeof t!="string"||!N(t)||t.length<2+Qr*2+La)return[];let r=[];for(let o=2;o<t.length;o+=Qr+La)r.push(t.slice(o,o+Qr));return r.map(o=>o.toLowerCase()).map(o=>`0x${o}`)}_isSupportedChainId(e){return Object.values(Zr).includes(e)}_decodeWrappedEth(e,t){return this._isSupportedChainId(t)?[Oa[t].toLowerCase()]:[]}_decodeSweep=e=>{let[t]=this.abiDecoder.decode(["address","address","uint256"],e);return typeof t!="string"||!N(t)?[]:[t.toLowerCase()]}};_r=uc([y(),fc(0,p(gt.AbiDecoderDataSource))],_r);var mc=Object.defineProperty,hc=Object.getOwnPropertyDescriptor,yc=(e,t,r,o)=>{for(var a=o>1?void 0:o?hc(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&mc(t,r,a),a},vr=class{decode(e,t){try{return bt.defaultAbiCoder().decode(e,t)}catch{return[]}}};vr=yc([y()],vr);var gc=Object.defineProperty,xc=Object.getOwnPropertyDescriptor,Ec=(e,t,r,o)=>{for(var a=o>1?void 0:o?xc(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(a=(o?i(t,r,a):i(a))||a);return o&&a&&gc(t,r,a),a},to=(e,t)=>(r,o)=>t(r,o,e),Tc=[f.TOKEN],br=class{constructor(e,t,r){this.commandDecoderDataSource=e,this.tokenDataSource=t,this.logger=r("UniswapContextLoader")}logger;canHandle(e,t){return typeof e=="object"&&e!==null&&"data"in e&&"selector"in e&&"chainId"in e&&typeof e.chainId=="number"&&N(e.data)&&e.data!=="0x"&&N(e.selector)&&e.selector===Na&&Tc.every(r=>t.includes(r))}async load(e){let{data:t,chainId:r}=e,o=await this._extractClearSignContexts(t,r);return this.logger.debug("load result",{data:{result:o}}),o}async _extractClearSignContexts(e,t){try{let r=new Ot(Ia).parseTransaction({data:e}),o=r?.args[0],a=r?.args[1];if(!N(o)||!this._isHexaStringArray(a))return[];let n=this._extractCommands(o).orDefault([]);if(o.length===0||a.length!==n.length)return[];let i=n.reduce((c,l,d)=>{let C=a[d],b=this.commandDecoderDataSource.decode(l,C,t);return c.push([l,b]),c},[]);if(!this._isChainingSwapSupported(i))return[];let s=[...new Set(i.flatMap(([,c])=>c))];return(await Promise.all(s.map(c=>this.tokenDataSource.getTokenInfosPayload({address:c,chainId:t})))).map(c=>c.caseOf({Left:l=>({type:f.ERROR,error:l}),Right:l=>({type:f.TOKEN,payload:l})}))}catch{return[]}}_extractCommands(e){return Nr.fromNullable(e.slice(2).match(/../g)).map(t=>t.map(r=>`0x${r}`)).map(t=>t.map(r=>Aa[r])).chain(t=>t.every(r=>r!==void 0)?Nr.of(t):so)}_isChainingSwapSupported(e){let t,r;for(let[o,a]of e){if(!Pa.includes(o))continue;let n=o.slice(0,2);if(t&&(t!==a[0]||r!==n))return!1;t=a[a.length-1],r=n}return!0}_isHexaStringArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&N(t))}};br=Ec([y(),to(0,p(gt.CommandDecoderDataSource)),to(1,p(K.TokenDataSource)),to(2,p(g.ContextModuleLoggerFactory))],br);var Ra=()=>new A(({bind:e})=>{e(gt.AbiDecoderDataSource).to(vr),e(gt.CommandDecoderDataSource).to(_r),e(gt.UniswapContextLoader).to(br)});var Fa=({config:e})=>{let t=new lo;return t.bind(g.ContextModuleLoggerFactory).toConstantValue(e.loggerFactory),t.loadSync(fo(e),Zo(),mo(),oa(),ia(e),ca(),ga(),uo(),Ca(e),ka(),aa(),Ra(),xa(),da(),fa(),ua()),t};var Dr=class{_container;_loaders;_typedDataLoader;_solanaLoader;_fieldLoaders;constructor(t){this._container=Fa({config:t}),this._loaders=t.defaultLoaders?this._getDefaultLoaders():[],this._loaders.push(...t.customLoaders),this._fieldLoaders=t.defaultFieldLoaders?this._getDefaultFieldLoaders():[],this._fieldLoaders.push(...t.customFieldLoaders),this._typedDataLoader=t.customTypedDataLoader??this._getDefaultTypedDataLoader(),this._solanaLoader=t.customSolanaLoader??this._getSolanaLoader()}_getDefaultFieldLoaders(){return[this._container.get(st.NftContextFieldLoader),this._container.get(K.TokenContextFieldLoader),this._container.get(ot.TrustedNameContextFieldLoader),this._container.get(at.ProxyContextFieldLoader)]}_getDefaultLoaders(){return[this._container.get(Rt.ExternalPluginContextLoader),this._container.get(ot.TrustedNameContextLoader),this._container.get(st.NftContextLoader),this._container.get(K.TokenContextLoader),this._container.get(Et.CalldataContextLoader),this._container.get(Lt.DynamicNetworkContextLoader),this._container.get(Ft.SafeAddressLoader),this._container.get(nt.TransactionCheckContextLoader),this._container.get(nt.TypedDataCheckContextLoader)]}_getDefaultTypedDataLoader(){return this._container.get(Ut.TypedDataContextLoader)}_getSolanaLoader(){try{return this._container.get(Mt.SolanaContextLoader)}catch{return{load:async t=>m(new Error("[ContextModule] - DefaultContextModule: no SolanaContextLoader bound"))}}}async getContexts(t,r){let o=Object.values(f),a=this._loaders.filter(n=>n.canHandle(t,r??o)).map(n=>n.load(t));return(await Promise.all(a)).flat()}async getFieldContext(t,r){let o=this._fieldLoaders.filter(a=>a.canHandle(t,r));if(o.length===0)return Promise.resolve({type:f.ERROR,error:new Error(`Loader not found for field: ${t} and expected type: ${r}`)});for(let a of o){let n=await a.loadField(t);if(n.type!==f.ERROR)return n}return{type:f.ERROR,error:new Error(`Loader not found for field: ${t} and expected type: ${r}`)}}async getTypedDataFilters(t){return this._typedDataLoader.load(t)}async getSolanaContext(t){return await this._solanaLoader.load(t)}};var Cc="https://crypto-assets-service.api.ledger.com/v1",Sc="https://web3checks-backend.api.ledger.com/v3",_c="https://nft.api.live.ledger.com",te={cal:{url:Cc,mode:"prod",branch:"main"},web3checks:{url:Sc},metadataServiceDomain:{url:_c},defaultLoaders:!0,customLoaders:[],defaultFieldLoaders:!0,customFieldLoaders:[],customTypedDataLoader:void 0,customSolanaLoader:void 0,loggerFactory:co},Ma=class{config;originToken;constructor({originToken:t,loggerFactory:r}){this.originToken=t,this.config={...te,cal:{...te.cal},web3checks:{...te.web3checks},metadataServiceDomain:{...te.metadataServiceDomain},customLoaders:[...te.customLoaders],customFieldLoaders:[...te.customFieldLoaders]},r&&(this.config.loggerFactory=r)}removeDefaultLoaders(){return this.config.defaultLoaders=!1,this}addLoader(t){return this.config.customLoaders.push(t),this}addTypedDataLoader(t){return this.config.customTypedDataLoader=t,this}addSolanaLoader(t){return this.config.customSolanaLoader=t,this}setCalConfig(t){return this.config.cal=t,this}setMetadataServiceConfig(t){return this.config.metadataServiceDomain=t,this}setWeb3ChecksConfig(t){return this.config.web3checks=t,this}setDatasourceConfig(t){return this.config.datasource=t,this}setTrustedNameDataSource(t){return this.config.customTrustedNameDataSource=t,this}setLoggerFactory(t){return this.config.loggerFactory=t,this}build(){let t={...this.config,originToken:this.originToken};return new Dr(t)}};var TE=ro(Ga());var vc=(e=>(e.FROM="FROM",e.TO="TO",e.VALUE="VALUE",e))(vc||{}),bc=(e=>(e.TUPLE="TUPLE",e.ARRAY="ARRAY",e.REF="REF",e.LEAF="LEAF",e.SLICE="SLICE",e))(bc||{}),Dc=(e=>(e.STATIC_LEAF="STATIC_LEAF",e.DYNAMIC_LEAF="DYNAMIC_LEAF",e.TUPLE_LEAF="TUPLE_LEAF",e.ARRAY_LEAF="ARRAY_LEAF",e))(Dc||{});var Ua=class{constructor(t,r,o=ao.isSuccessResponse){this._errors=t,this._errorFactory=r,this._isSuccessResponse=o}getError(t){let r=new oo(t).encodeToHexaString(t.statusCode);if(no(r,this._errors))return Ir({error:this._errorFactory({...this._errors[r],errorCode:r})});if(!this._isSuccessResponse(t))return Ir({error:io.handle(t)})}};var Ha=class{static PADDING=2147483648;static splitPath(t){let r=[];return t.split("/").forEach(o=>{let a=parseInt(o,10);if(isNaN(a))throw new Error("invalid number provided");o.length>1&&o[o.length-1]==="'"&&(a+=this.PADDING),r.push(a)}),r}};export{f as a,Tt as b,et as c,Wt as d,Ma as e,vc as f,bc as g,Dc as h,Ua as i,Ha as j};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
process.noDeprecation = true; import { createRequire as __createRequire } from "module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import{a as C,b as x,c as v,e as R,i as D}from"./chunk-INE4OXJA.js";import{existsSync as De,readFileSync as Ue,writeFileSync as We,renameSync as Le}from"fs";import{join as F}from"path";import{homedir as Pe}from"os";import{randomBytes as Be}from"crypto";import{execFileSync as K,execSync as ae}from"child_process";import{randomBytes as fe}from"crypto";import{existsSync as le,readFileSync as ue,writeFileSync as de}from"fs";import{homedir as pe,platform as B}from"os";import{join as ye}from"path";import*as o from"fs";import*as W from"os";import*as g from"path";import{readFileSync as X}from"fs";import{join as G}from"path";import{homedir as q}from"os";var z="0.12.0",Q="X-CLI-Version",Z="X-Agent-Id",u;function ee(){if(u!==void 0)return u;try{u=JSON.parse(X(G(q(),".config","moonpay","consent.json"),"utf-8")).agentId??null}catch{u=null}return u??null}function U(){let e={"Content-Type":"application/json",[Q]:z},r=ee();return r&&(e[Z]=r),e}var p=g.join(W.homedir(),".config","moonpay"),b=g.join(p,"config.json"),y=g.join(p,"credentials.json"),d=g.join(p,".credentials.lock"),A={baseUrl:"https://agents.moonpay.com"};function a(){o.existsSync(p)||o.mkdirSync(p,{recursive:!0,mode:448})}function L(e,r,n){let t=e+`.tmp.${process.pid}`;o.writeFileSync(t,r,{encoding:"utf-8",mode:n}),o.renameSync(t,e)}var re=3e4;function ne(){a();try{let e=o.openSync(d,o.constants.O_CREAT|o.constants.O_EXCL|o.constants.O_WRONLY,384);o.writeSync(e,JSON.stringify({pid:process.pid,ts:Date.now()})),o.closeSync(e)}catch(e){if(e.code!=="EEXIST")throw e;try{let r=JSON.parse(o.readFileSync(d,"utf-8"));if(Date.now()-r.ts<re)return null}catch{}try{o.unlinkSync(d)}catch{}try{let r=o.openSync(d,o.constants.O_CREAT|o.constants.O_EXCL|o.constants.O_WRONLY,384);o.writeSync(r,JSON.stringify({pid:process.pid,ts:Date.now()})),o.closeSync(r)}catch{return null}}return()=>{try{o.unlinkSync(d)}catch{}}}function P(){if(!o.existsSync(b))return null;try{let e=JSON.parse(o.readFileSync(b,"utf-8"));return e.baseUrl?e:null}catch{return null}}function Qe(){let e=P();return e||(oe(A),A)}function w(){if(!o.existsSync(y))return null;let e=m();if(!e)return null;try{let r=JSON.parse(o.readFileSync(y,"utf-8")),n=C.parse(r),t=v(n,e),s=JSON.parse(t);return!s.accessToken||!s.baseUrl?null:s}catch{return null}}function te(e){let r=E(),n=x(JSON.stringify(e),r);a(),L(y,JSON.stringify(n,null,2),384)}function oe(e){a(),L(b,JSON.stringify(e,null,2),384)}function Ze(){o.existsSync(y)&&o.unlinkSync(y)}function er(){let e=P(),r=w();return e?.baseUrl??r?.baseUrl??A.baseUrl}async function se(e,r,n){let t=await fetch(`${e}/api/tools/${encodeURIComponent(r)}`,{method:"POST",signal:AbortSignal.timeout(15e3),headers:U(),body:JSON.stringify(n)}),s=await t.json();if(!t.ok){let i=s;throw new Error(i?.error??`${r} failed (${t.status})`)}return s}async function ie(e){if(!e.refreshToken)throw new Error("No refresh token available");let r=ne();if(!r){await new Promise(t=>setTimeout(t,2e3));let n=w();if(n&&n.expiresAt>Date.now())return n;throw new Error("Token refresh failed (concurrent refresh in progress)")}try{let n=w();if(n&&n.expiresAt>Date.now()+6e4)return n;let t=await se(e.baseUrl,"refresh",{refreshToken:e.refreshToken}),s={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt*1e3,baseUrl:e.baseUrl};return te(s),s}finally{r()}}var ce=300*1e3;async function rr(){let e=w();if(!e)return null;if(Date.now()>=e.expiresAt-ce){if(e.refreshToken)try{return(await ie(e)).accessToken}catch{return null}return null}return e.accessToken}var f="moonpay-cli",h="encryption-key",k=ye(pe(),".config","moonpay",".encryption-key");function me(e){try{K("security",["delete-generic-password","-s",f,"-a",h],{stdio:"ignore"})}catch{}K("security",["add-generic-password","-s",f,"-a",h,"-w",e],{stdio:"ignore"})}function ge(){try{return K("security",["find-generic-password","-s",f,"-a",h,"-w"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function he(e){ae(`printf '%s' | secret-tool store --label="${f}" service "${f}" account "${h}"`,{input:e,stdio:["pipe","ignore","ignore"]})}function Se(){try{return K("secret-tool",["lookup","service",f,"account",h],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function Ce(e){a(),de(k,e,{encoding:"utf-8",mode:384})}function xe(){try{return le(k)&&ue(k,"utf-8").trim()||null}catch{return null}}function ve(e){try{let r=B();return r==="darwin"?(me(e),!0):r==="linux"?(he(e),!0):!1}catch{return!1}}function we(){let e=B();return e==="darwin"?ge():e==="linux"?Se():null}function m(){let e=process.env.MOONPAY_ENCRYPTION_KEY;return e||(we()??xe())}function E(){let e=m();if(e)return e;let r=fe(32).toString("hex");return ve(r)||(Ce(r),process.stderr.write("Note: Keychain unavailable. Encryption key stored in "+k+`
|
|
3
|
+
`)),r}import{createHash as $}from"crypto";import{HDKey as N}from"@scure/bip32";import{mnemonicToSeedSync as _}from"@scure/bip39";import{keccak_256 as J}from"@noble/hashes/sha3";import{derivePath as Ee}from"ed25519-hd-key";import*as j from"bitcoinjs-lib";import Ke from"ecpair";import*as O from"tiny-secp256k1";import{Keypair as ke}from"@solana/web3.js";import _e from"bs58";var Oe=Ke(O);function T(e,r=0){switch(e){case"solana":return`m/44'/501'/${r}'/0'`;case"ethereum":return`m/44'/60'/${r}'/0/0`;case"bitcoin":return`m/84'/0'/${r}'/0/0`;case"tron":return`m/44'/195'/${r}'/0/0`}}function l(e,r,n=0){switch(r){case"solana":return Te(e,n);case"ethereum":return be(e,n);case"bitcoin":return Ie(e,n);case"tron":return Fe(e,n)}}function Sr(e,r=0){return{solana:l(e,"solana",r).address,ethereum:l(e,"ethereum",r).address,bitcoin:l(e,"bitcoin",r).address,tron:l(e,"tron",r).address}}function Te(e,r){let n=_(e),t=T("solana",r),{key:s}=Ee(t,Buffer.from(n).toString("hex")),i=ke.fromSeed(Uint8Array.from(s));return{privateKey:i.secretKey,address:i.publicKey.toBase58()}}function be(e,r){let n=_(e),t=N.fromMasterSeed(n),s=T("ethereum",r),i=t.derive(s);if(!i.privateKey)throw new Error("Failed to derive EVM private key");let c=Ae(i.publicKey);return{privateKey:i.privateKey,address:c}}function Ae(e){let r=O.pointCompress(e,!1),t=H(r.slice(1)).slice(-20),s="0x"+Buffer.from(t).toString("hex");return Ne(s)}function H(e){return J(e)}function Ne(e){let r=e.toLowerCase().replace("0x",""),n=Buffer.from(J(Buffer.from(r,"utf8"))).toString("hex"),t="0x";for(let s=0;s<r.length;s++)t+=parseInt(n[s],16)>=8?r[s].toUpperCase():r[s];return t}function Ie(e,r){let n=_(e),t=N.fromMasterSeed(n),s=T("bitcoin",r),i=t.derive(s);if(!i.privateKey)throw new Error("Failed to derive Bitcoin private key");let c=Oe.fromPrivateKey(Buffer.from(i.privateKey)),{address:S}=j.payments.p2wpkh({pubkey:Buffer.from(c.publicKey)});if(!S)throw new Error("Failed to derive Bitcoin address");return{privateKey:i.privateKey,address:S}}function Fe(e,r){let n=_(e),t=N.fromMasterSeed(n),s=T("tron",r),i=t.derive(s);if(!i.privateKey)throw new Error("Failed to derive Tron private key");let c=Re(i.publicKey);return{privateKey:i.privateKey,address:c}}function Re(e){let r=O.pointCompress(e,!1),t=H(r.slice(1)).slice(-20),s=Buffer.concat([Buffer.from([65]),Buffer.from(t)]),i=$("sha256").update(s).digest(),c=$("sha256").update(i).digest(),S=Buffer.concat([s,c.slice(0,4)]);return _e.encode(S)}import $e from"bs58";var M=F(Pe(),".config","moonpay"),I=F(M,"wallets.json");function V(){if(!De(I))return[];let e=m();if(!e)throw new Error("Encryption key not found. Set MOONPAY_ENCRYPTION_KEY or ensure OS keychain is accessible.");let r=JSON.parse(Ue(I,"utf-8")),n=C.parse(r),t=v(n,e);return(JSON.parse(t).wallets??[]).map(i=>D.parse(i))}function Je(e){let r=E(),n=JSON.stringify({wallets:e}),t=x(n,r);a();let s=F(M,`.wallets.${Be(4).toString("hex")}.tmp`);We(s,JSON.stringify(t,null,2),{mode:384}),Le(s,I)}function Y(e){let r=V();e(r),Je(r)}function je(e){let r=V();for(let n of r){if(n.name===e)return n;for(let t of Object.values(n.addresses))if(t===e)return n}return null}function Ar(e){let r=je(e);if(!r)throw new Error(`Wallet "${e}" not found`);return r}function Nr(e){Y(r=>{if(r.some(n=>n.name===e.name))throw new Error(`Wallet "${e.name}" already exists`);r.push(e)})}function Ir(e){Y(r=>{let n=r.findIndex(t=>t.name===e);if(n===-1)throw new Error(`Wallet "${e}" not found`);r.splice(n,1)})}function Fr(e,r){if(e.type==="hardware")throw new Error(`Wallet "${e.name}" is a hardware wallet. Signing must happen on the device \u2014 use ledgerSignTransaction/ledgerSignMessage instead.`);let n=R[r];if(e.type==="imported"){if(e.chain!==n)throw new Error(`Wallet "${e.name}" was imported for ${e.chain}, cannot sign for ${r}.`);return{privateKey:He(e.privateKey,n),address:e.addresses[n]}}let t=l(e.mnemonic,n);return{privateKey:t.privateKey,address:t.address}}function He(e,r){if(r==="solana")return $e.decode(e);let n=e.startsWith("0x")?e.slice(2):e;return Uint8Array.from(Buffer.from(n,"hex"))}export{z as a,U as b,a as c,Qe as d,w as e,te as f,Ze as g,er as h,se as i,ie as j,rr as k,Sr as l,V as m,Je as n,Y as o,je as p,Ar as q,Nr as r,Ir as s,Fr as t};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
process.noDeprecation = true; import { createRequire as __createRequire } from "module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import{a as u,c as a}from"./chunk-LMDE72OE.js";var V=a((oe,F)=>{"use strict";var B=u("fs"),o=u("path"),N=u("os"),L=typeof __webpack_require__=="function"?__non_webpack_require__:u,K=process.config&&process.config.variables||{},Q=!!process.env.PREBUILDS_ONLY,j=process.versions.modules,f=Z()?"electron":X()?"node-webkit":"node",p=process.env.npm_config_arch||N.arch(),v=process.env.npm_config_platform||N.platform(),S=process.env.LIBC||(ee(v)?"musl":"glibc"),m=process.env.ARM_VERSION||(p==="arm64"?"8":K.arm_version)||"",U=(process.versions.uv||"").split(".")[0];F.exports=s;function s(r){return L(s.resolve(r))}s.resolve=s.path=function(r){r=o.resolve(r||".");try{var n=L(o.join(r,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[n+"_PREBUILD"]&&(r=process.env[n+"_PREBUILD"])}catch{}if(!Q){var e=R(o.join(r,"build/Release"),E);if(e)return e;var t=R(o.join(r,"build/Debug"),E);if(t)return t}var c=q(r);if(c)return c;var i=q(o.dirname(process.execPath));if(i)return i;var z=["platform="+v,"arch="+p,"runtime="+f,"abi="+j,"uv="+U,m?"armv="+m:"","libc="+S,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+z+`
|
|
3
|
+
loaded from: `+r+`
|
|
4
|
+
`);function q(l){var G=x(o.join(l,"prebuilds")).map(D),T=G.filter(I(v,p)).sort(O)[0];if(T){var b=o.join(l,"prebuilds",T.name),H=x(b).map(A),J=H.filter(P(f,j)),k=J.sort(C(f))[0];if(k)return o.join(b,k.file)}}};function x(r){try{return B.readdirSync(r)}catch{return[]}}function R(r,n){var e=x(r).filter(n);return e[0]&&o.join(r,e[0])}function E(r){return/\.node$/.test(r)}function D(r){var n=r.split("-");if(n.length===2){var e=n[0],t=n[1].split("+");if(e&&t.length&&t.every(Boolean))return{name:r,platform:e,architectures:t}}}function I(r,n){return function(e){return e==null||e.platform!==r?!1:e.architectures.includes(n)}}function O(r,n){return r.architectures.length-n.architectures.length}function A(r){var n=r.split("."),e=n.pop(),t={file:r,specificity:0};if(e==="node"){for(var c=0;c<n.length;c++){var i=n[c];if(i==="node"||i==="electron"||i==="node-webkit")t.runtime=i;else if(i==="napi")t.napi=!0;else if(i.slice(0,3)==="abi")t.abi=i.slice(3);else if(i.slice(0,2)==="uv")t.uv=i.slice(2);else if(i.slice(0,4)==="armv")t.armv=i.slice(4);else if(i==="glibc"||i==="musl")t.libc=i;else continue;t.specificity++}return t}}function P(r,n){return function(e){return!(e==null||e.runtime&&e.runtime!==r&&!W(e)||e.abi&&e.abi!==n&&!e.napi||e.uv&&e.uv!==U||e.armv&&e.armv!==m||e.libc&&e.libc!==S)}}function W(r){return r.runtime==="node"&&r.napi}function C(r){return function(n,e){return n.runtime!==e.runtime?n.runtime===r?-1:1:n.abi!==e.abi?n.abi?-1:1:n.specificity!==e.specificity?n.specificity>e.specificity?-1:1:0}}function X(){return!!(process.versions&&process.versions.nw)}function Z(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}function ee(r){return r==="linux"&&B.existsSync("/etc/alpine-release")}s.parseTags=A;s.matchTags=P;s.compareTags=C;s.parseTuple=D;s.matchTuple=I;s.compareTuples=O});var h=a((ue,d)=>{"use strict";var _=typeof __webpack_require__=="function"?__non_webpack_require__:u;typeof _.addon=="function"?d.exports=_.addon.bind(_):d.exports=V()});var Y=a((le,M)=>{"use strict";var re=(r,n,e,t,c)=>{for(var i=0;i<c;i++)e[t+i]=r[i]^n[i&3]},ne=(r,n)=>{let e=r.length;for(var t=0;t<e;t++)r[t]^=n[t&3]};M.exports={mask:re,unmask:ne}});var ie=a((fe,y)=>{"use strict";try{y.exports=h()(__dirname)}catch{y.exports=Y()}});var g=a((pe,$)=>{"use strict";function te(r){let n=r.length,e=0;for(;e<n;)if((r[e]&128)===0)e++;else if((r[e]&224)===192){if(e+1===n||(r[e+1]&192)!==128||(r[e]&254)===192)return!1;e+=2}else if((r[e]&240)===224){if(e+2>=n||(r[e+1]&192)!==128||(r[e+2]&192)!==128||r[e]===224&&(r[e+1]&224)===128||r[e]===237&&(r[e+1]&224)===160)return!1;e+=3}else if((r[e]&248)===240){if(e+3>=n||(r[e+1]&192)!==128||(r[e+2]&192)!==128||(r[e+3]&192)!==128||r[e]===240&&(r[e+1]&240)===128||r[e]===244&&r[e+1]>143||r[e]>244)return!1;e+=4}else return!1;return!0}$.exports=te});var se=a((ve,w)=>{"use strict";try{w.exports=h()(__dirname)}catch{w.exports=g()}});export{h as a,ie as b,se as c};
|