@vleap/warps 3.0.0-alpha.9 → 3.0.0-alpha.90

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/index.js CHANGED
@@ -1,12 +1,2 @@
1
- "use strict";var Et=Object.create;var it=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Ut=Object.prototype.hasOwnProperty;var Nt=(i,t)=>()=>(i&&(t=i(i=0)),t);var ht=(i,t)=>{for(var e in t)it(i,e,{get:t[e],enumerable:!0})},yt=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pt(t))!Ut.call(i,n)&&n!==e&&it(i,n,{get:()=>t[n],enumerable:!(r=Rt(t,n))||r.enumerable});return i};var pt=(i,t,e)=>(e=i!=null?Et(Vt(i)):{},yt(t||!i||!i.__esModule?it(e,"default",{value:i,enumerable:!0}):e,i)),Ot=i=>yt(it({},"__esModule",{value:!0}),i);var bt={};ht(bt,{runInVm:()=>ne});var ne,vt=Nt(()=>{"use strict";ne=async(i,t)=>{if(typeof window>"u"){let e;try{e=require("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save. This is not required for browser usage.')}let r=new e({timeout:1e3,sandbox:{result:t},eval:!1,wasm:!1});return i.trim().startsWith("(")&&i.includes("=>")?r.run(`(${i})(result)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
2
- self.onmessage = function(e) {
3
- try {
4
- const result = e.data;
5
- const output = (${i})(result);
6
- self.postMessage({ result: output });
7
- } catch (error) {
8
- self.postMessage({ error: error.toString() });
9
- }
10
- };
11
- `],{type:"application/javascript"}),a=URL.createObjectURL(n),s=new Worker(a);s.onmessage=function(o){o.data.error?r(new Error(o.data.error)):e(o.data.result),s.terminate(),URL.revokeObjectURL(a)},s.onerror=function(o){r(new Error(`Error in transform: ${o.message}`)),s.terminate(),URL.revokeObjectURL(a)},s.postMessage(t)}catch(n){return r(n)}})}});var ce={};ht(ce,{BrandBuilder:()=>ft,CacheKey:()=>S,CacheTtl:()=>Y,WarpAbiBuilder:()=>rt,WarpActionExecutor:()=>gt,WarpArgSerializer:()=>k,WarpBuilder:()=>tt,WarpCache:()=>V,WarpConfig:()=>x,WarpConstants:()=>f,WarpContractLoader:()=>nt,WarpIndex:()=>mt,WarpInterpolator:()=>N,WarpLink:()=>et,WarpProtocolVersions:()=>$,WarpRegistry:()=>q,WarpUtils:()=>T,WarpValidator:()=>Z,address:()=>Xt,biguint:()=>Kt,boolean:()=>Jt,codemeta:()=>ee,composite:()=>Dt,esdt:()=>te,getChainExplorerUrl:()=>Ft,getLatestProtocolIdentifier:()=>L,getMainChainInfo:()=>A,getWarpActionByIndex:()=>O,hex:()=>Zt,list:()=>qt,nothing:()=>re,option:()=>Lt,optional:()=>_t,replacePlaceholders:()=>K,shiftBigintBy:()=>z,string:()=>Ht,toPreviewText:()=>ut,toTypedChainInfo:()=>at,token:()=>Yt,u16:()=>Qt,u32:()=>Gt,u64:()=>zt,u8:()=>jt,variadic:()=>Mt});module.exports=Ot(ce);var M=require("@multiversx/sdk-core"),Ct=pt(require("ajv"));var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:i=>i.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:i=>i.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:i=>i.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var $={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},x={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${$.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${$.Brand}.schema.json`,DefaultClientUrl:i=>i==="devnet"?"https://devnet.usewarp.to":i==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:i=>i==="devnet"?"https://devnet-explorer.multiversx.com":i==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:i=>6e3,AddressHrp:"erd",ChainId:i=>i==="devnet"?"D":i==="testnet"?"T":"1"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",f.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var A=i=>({name:x.MainChain.Name,displayName:x.MainChain.DisplayName,chainId:x.MainChain.ChainId(i.env),blockTime:x.MainChain.BlockTime(i.env),addressHrp:x.MainChain.AddressHrp,apiUrl:x.MainChain.ApiUrl(i.env),explorerUrl:x.MainChain.ExplorerUrl(i.env)}),Ft=(i,t)=>i.explorerUrl+(t?"/"+t:""),L=i=>{if(i==="warp")return`warp:${$.Warp}`;if(i==="brand")return`brand:${$.Brand}`;if(i==="abi")return`abi:${$.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},O=(i,t)=>i?.actions[t-1],at=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString()}),z=(i,t)=>{let e=i.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let s=r+n;if(a>=s.length)return 0n;let o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ut=(i,t=100)=>{if(!i)return"";let e=i.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},K=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var H=class H{static info(...t){H.isTestEnv||console.info(...t)}static warn(...t){H.isTestEnv||console.warn(...t)}static error(...t){H.isTestEnv||console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=H;var j=require("@multiversx/sdk-core");var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;F.cache.set(t,{value:e,expiresAt:n})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var X=F;var Y={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},S={Warp:i=>`warp:${i}`,WarpAbi:i=>`warp-abi:${i}`,LastWarpExecutionInputs:(i,t)=>`warp-exec-inputs:${i}:${t}`,RegistryInfo:i=>`registry-info:${i}`,Brand:i=>`brand:${i}`,ChainInfo:i=>`chain:${i}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new X:typeof window<"u"&&window.localStorage?new J:new X}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Tt=pt(require("qr-code-styling"));var _=require("@multiversx/sdk-core");var wt=pt(require("ajv"));var Z=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),r=t.actions.some(s=>s.type==="query");if(!e&&!r)return[];let n=t.actions.some(s=>s.abi),a=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||x.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new wt.default,s=a.compile(n);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var tt=class{constructor(t){this.pendingWarp={protocol:L("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=A(this.config),r=new _.TransactionsFactoryConfig({chainID:e.chainId}),n=new _.TransferTransactionsFactory({config:r}),a=_.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),o=n.createTransactionForTransfer(a,{receiver:_.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=S.Warp(t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=A(this.config),s=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return C.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ut(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new Z(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
12
- `))}};var N=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(a,s)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([a,s])=>{if(typeof s!="string")n(a,s);else if(s.startsWith(`${f.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${f.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(a,p)}else if(s.startsWith(`${f.Vars.Env}:`)){let o=s.split(`${f.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(a,p)}else s===f.Source.UserWallet&&t.user?.wallet?n(a,t.user.wallet):n(a,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:A(e)};return Object.values(f.Globals).forEach(a=>{let s=a.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await T.getChainInfoForAction(t,e),n=JSON.stringify(e),a={config:t,chain:r};return Object.values(f.Globals).forEach(s=>{let o=s.Accessor(a);o!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var h=require("@multiversx/sdk-core/out");var lt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var st=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),Wt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var q=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let n=h.Address.newFromBech32(this.config.user.wallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,s=()=>e&&r?[h.BytesValue.fromHex(t),h.BytesValue.fromUTF8(e),h.BytesValue.fromHex(r)]:e?[h.BytesValue.fromHex(t),h.BytesValue.fromUTF8(e)]:[h.BytesValue.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:s()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[h.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[h.BytesValue.fromUTF8(t),h.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[h.BytesValue.fromHex(t),h.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[h.BytesValue.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[h.BytesValue.fromHex(t),new h.AddressValue(new h.Address(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[h.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=h.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[h.BytesValue.fromHex(t),h.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=S.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:a,function:"getInfoByAlias",arguments:[h.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),d=u?st(u):null,g=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:g},e.ttl),{registryInfo:d,brand:g}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=S.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return C.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),a=this.getController(),s=a.createQuery({contract:n,function:"getInfoByHash",arguments:[h.BytesValue.fromHex(t)]}),o=await a.runQuery(s),[p]=a.parseQueryResponse(o),u=p?st(p):null,d=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:d},e.ttl),{registryInfo:u,brand:d}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new h.AddressValue(new h.Address(e))]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s);return o.map(st)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new h.AddressValue(new h.Address(e))]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s),p=o.map(g=>g.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(g=>this.fetchBrand(g,u)))).filter(g=>g!==null)}catch{return[]}}async getChainInfos(t){let e=S.ChainInfos();if(t&&t.ttl){let u=this.cache.get(e);if(u)return C.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),u}let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s),p=o.map(at);if(t&&t.ttl){for(let u of p)this.cache.set(S.ChainInfo(u.chain),u,t.ttl);this.cache.set(e,p,t.ttl)}return p}async getChainInfo(t,e){try{let r=S.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:a,function:"getChain",arguments:[h.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),d=u?at(u):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async fetchBrand(t,e){let r=S.Brand(t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=A(this.config),o=T.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let p=await o.getTransaction(t),u=JSON.parse(p.data.toString());return u.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}catch{return null}}getRegistryContractAddress(){return h.Address.newFromBech32(this.config.registry?.contract||x.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?Wt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=A(this.config),e=new h.TransactionsFactoryConfig({chainID:t.chainId}),r=h.AbiRegistry.create(lt);return new h.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=A(this.config),e=T.getChainEntrypoint(t,this.config.env),r=h.AbiRegistry.create(lt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var et=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(f.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),s=(await Promise.all(n)).filter(u=>u.match),o=s.length>0,p=s.map(u=>({url:u.url,warp:u.warp}));return{match:o,results:p}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):T.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:a,identifierBase:s}=n,o=new tt(this.config),p=new q(this.config),u=null,d=null,g=null;if(a==="hash"){u=await o.createFromTransactionHash(s,e);let y=await p.getInfoByHash(s,e);d=y.registryInfo,g=y.brand}else if(a==="alias"){let y=await p.getInfoByAlias(s,e);d=y.registryInfo,g=y.brand,y.registryInfo&&(u=await o.createFromTransactionHash(y.registryInfo.hash,e))}let w=u?await N.apply(this.config,u):null;return w?{match:!0,url:t,warp:w,registryInfo:d,brand:g}:r}catch(a){return C.error("Error detecting warp link",a),r}}build(t,e){let r=this.config.clientUrl||x.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return x.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=T.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",a="black",s="#23F7DD"){let o=this.build(t,e);return new Tt.default({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=x.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let s=decodeURIComponent(a);return T.getInfoFromPrefixedIdentifier(s)}};var $t="https://",T=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,a]=r.split(f.IdentifierParamSeparator),s=a.split("?")[0];return{type:n,identifier:a,identifierBase:s}}static getNextInfo(t,e,r,n){let a=e.actions?.[r]?.next||e.next||null;if(!a)return null;if(a.startsWith($t))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o)return[{identifier:s,url:this.buildNextUrl(s,t)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let m=K(o,{...e.vars,...n}),W=m?`${s}?${m}`:s;return[{identifier:W,url:this.buildNextUrl(W,t)}]}let u=p[0];if(!u)return[];let d=u.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||n[g]===void 0)return[];let w=Array.isArray(n[g])?n[g]:[n[g]];if(w.length===0)return[];let y=p.filter(m=>m.includes(`{{${g}[]`)).map(m=>{let W=m.match(/\[\](\.[^}]+)?}}/),v=W&&W[1]||"";return{placeholder:m,field:v?v.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return w.map(m=>{let W=o;for(let{regex:E,field:P}of y){let b=P?this.getNestedValue(m,P):m;if(b==null)return null;W=W.replace(E,b)}if(W.includes("{{")||W.includes("}}"))return null;let v=W?`${s}?${W}`:s;return{identifier:v,url:this.buildNextUrl(v,t)}}).filter(m=>m!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),a=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new et(e).build(a.type,a.identifierBase);if(!n)return o;let p=new URL(o);return new URLSearchParams(n).forEach((u,d)=>p.searchParams.set(d,u)),p.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return A(t);let r=await new q(t).getChainInfo(e.chain,{ttl:Y.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new j.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new j.TestnetEntrypoint(t.apiUrl,n,r):new j.MainnetEntrypoint(t.apiUrl,n,r)}};var ft=class{constructor(t){this.pendingBrand={protocol:L("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=A(this.config),r=new M.TransactionsFactoryConfig({chainID:e.chainId}),n=new M.TransferTransactionsFactory({config:r}),a=M.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(a,{receiver:M.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=A(this.config),n=T.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return C.error("BrandBuilder: Error creating from transaction hash",a),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||x.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new Ct.default,s=a.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Lt=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),_t=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),qt=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new l.List(t,i)},Mt=i=>l.VariadicValue.fromItems(...i),Dt=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},Ht=i=>l.StringValue.fromUTF8(i),jt=i=>new l.U8Value(i),Qt=i=>new l.U16Value(i),Gt=i=>new l.U32Value(i),zt=i=>new l.U64Value(i),Kt=i=>new l.BigUIntValue(BigInt(i)),Jt=i=>new l.BooleanValue(i),Xt=i=>new l.AddressValue(l.Address.newFromBech32(i)),Yt=i=>new l.TokenIdentifierValue(i),Zt=i=>l.BytesValue.fromHex(i),te=i=>new l.Struct(new l.StructType("EsdtTokenPayment",[new l.FieldDefinition("token_identifier","",new l.TokenIdentifierType),new l.FieldDefinition("token_nonce","",new l.U64Type),new l.FieldDefinition("amount","",new l.BigUIntType)]),[new l.Field(new l.TokenIdentifierValue(i.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(i.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(i.amount)),"amount")]),ee=i=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),re=()=>new l.NothingValue;var Q=require("@multiversx/sdk-core");var rt=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=A(this.config),r=new Q.TransactionsFactoryConfig({chainID:e.chainId}),n=new Q.TransferTransactionsFactory({config:r}),a={protocol:L("abi"),content:t},s=Q.Address.newFromBech32(this.config.user.wallet),o=JSON.stringify(a),p=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return p.gasLimit=p.gasLimit+BigInt(2e6),p}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=S.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=A(this.config),s=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return C.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};var I=require("@multiversx/sdk-core");var G=require("@multiversx/sdk-core/out");var c=require("@multiversx/sdk-core/out");var It=new RegExp(`${f.ArgParamsSeparator}(.*)`),k=class{nativeToString(t,e){return t==="esdt"&&e instanceof c.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(c.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(c.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(c.List.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],a=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(c.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],a=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(c.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]),a=r.join(f.ArgCompositeSeparator),s=n.join(f.ArgCompositeSeparator);return`composite(${a}):${s}`}if(t.hasClassOrSuperclass(c.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(c.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(c.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new c.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new c.StringType;if(t==="uint8")return new c.U8Type;if(t==="uint16")return new c.U16Type;if(t==="uint32")return new c.U32Type;if(t==="uint64")return new c.U64Type;if(t==="biguint")return new c.BigUIntType;if(t==="bool")return new c.BooleanType;if(t==="address")return new c.AddressType;if(t==="token")return new c.TokenIdentifierType;if(t==="hex")return new c.BytesType;if(t==="codemeta")return new c.CodeMetadataType;if(t==="esdt"||t==="nft")return new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[a,s]=n.split(f.ArgParamsSeparator);return[`option:${a}`,s||null]}else if(r==="optional"){let[a,s]=n.split(f.ArgParamsSeparator);return[`optional:${a}`,s||null]}else if(r==="list"){let a=n.split(f.ArgParamsSeparator),s=a.slice(0,-1).join(f.ArgParamsSeparator),o=a[a.length-1],u=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,u]}else if(r==="variadic"){let a=n.split(f.ArgParamsSeparator),s=a.slice(0,-1).join(f.ArgParamsSeparator),o=a[a.length-1],u=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,u]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),o=n.split(f.ArgCompositeSeparator).map((p,u)=>this.stringToNative(`${a[u]}:${p}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[a,s,o]=n.split(f.ArgCompositeSeparator);return[r,new c.TokenTransfer({token:new c.Token({identifier:a,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new c.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionValue.newMissingTyped(n.getType()):c.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionalValue.newMissing():new c.OptionalValue(n.getType(),n)}if(e==="list"){let[n,a]=r.split(It,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new c.List(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(It,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new c.VariadicValue(new c.VariadicType(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(f.ArgCompositeSeparator),s=n.split(f.ArgCompositeSeparator),o=a.map((u,d)=>this.stringToTyped(`${s[d]}:${u}`)),p=o.map(u=>u.getType());return new c.CompositeValue(new c.CompositeType(...p),o)}if(e==="string")return r?c.StringValue.fromUTF8(r):new c.NothingValue;if(e==="uint8")return r?new c.U8Value(Number(r)):new c.NothingValue;if(e==="uint16")return r?new c.U16Value(Number(r)):new c.NothingValue;if(e==="uint32")return r?new c.U32Value(Number(r)):new c.NothingValue;if(e==="uint64")return r?new c.U64Value(BigInt(r)):new c.NothingValue;if(e==="biguint")return r?new c.BigUIntValue(BigInt(r)):new c.NothingValue;if(e==="bool")return r?new c.BooleanValue(typeof r=="boolean"?r:r==="true"):new c.NothingValue;if(e==="address")return r?new c.AddressValue(c.Address.newFromBech32(r)):new c.NothingValue;if(e==="token")return r?new c.TokenIdentifierValue(r):new c.NothingValue;if(e==="hex")return r?c.BytesValue.fromHex(r):new c.NothingValue;if(e==="codemeta")return new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new c.Struct(this.nativeToType("esdt"),[new c.Field(new c.TokenIdentifierValue(n[0]),"token_identifier"),new c.Field(new c.U64Value(BigInt(n[1])),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof c.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.StringType)return"string";if(t instanceof c.U8Type)return"uint8";if(t instanceof c.U16Type)return"uint16";if(t instanceof c.U32Type)return"uint32";if(t instanceof c.U64Type)return"uint64";if(t instanceof c.BigUIntType)return"biguint";if(t instanceof c.BooleanType)return"bool";if(t instanceof c.AddressType)return"address";if(t instanceof c.TokenIdentifierType)return"token";if(t instanceof c.BytesType)return"hex";if(t instanceof c.CodeMetadataType)return"codemeta";if(t instanceof c.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var dt=i=>{if(i==="out")return 1;let t=i.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(i.startsWith("out.")||i.startsWith("event."),null)},ie=(i,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,i),At=async(i,t,e,r,n,a)=>{let s=[],o={};if(!t.results||e.type!=="contract")return{values:s,results:o};if(!Object.values(t.results).some(y=>y.includes("out")||y.includes("event"))){for(let[y,B]of Object.entries(t.results))o[y]=B;return{values:s,results:await ot(t,o,n,a)}}let u=await i.getAbiForAction(e),d=new G.TransactionEventsParser({abi:u}),w=new G.SmartContractTransactionsOutcomeParser({abi:u}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[y,B]of Object.entries(t.results)){if(B.startsWith(f.Transform.Prefix))continue;if(B.startsWith("input.")){o[y]=B;continue}let m=dt(B);if(m!==null&&m!==n){o[y]=null;continue}let[W,v,E]=B.split(".");if(W==="event"){if(!v||isNaN(Number(E)))continue;let P=Number(E),b=(0,G.findEventsByFirstTopic)(r,v),D=d.parseEvents({events:b})[0],U=Object.values(D)[P]||null;s.push(U),o[y]=U&&U.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!v)continue;let P=Number(v),b=w.values[P-1]||null;E&&(b=b[E]||null),b&&typeof b=="object"&&(b="toFixed"in b?b.toFixed():b.valueOf()),s.push(b),o[y]=b&&b.valueOf()}else o[y]=B}return{values:s,results:await ot(t,o,n,a)}},xt=async(i,t,e,r)=>{let n=new k,a=t.map(u=>n.typedToString(u)),s=t.map(u=>n.typedToNative(u)[1]),o={};if(!i.results)return{values:a,results:o};let p=u=>{let d=u.split(".").slice(1).map(w=>parseInt(w)-1);if(d.length===0)return;let g=s[d[0]];for(let w=1;w<d.length;w++){if(g==null)return;g=g[d[w]]}return g};for(let[u,d]of Object.entries(i.results)){if(d.startsWith(f.Transform.Prefix))continue;let g=dt(d);if(g!==null&&g!==e){o[u]=null;continue}d.startsWith("out.")||d==="out"||d.startsWith("out[")?o[u]=p(d)||null:o[u]=d}return{values:a,results:await ot(i,o,e,r)}},Bt=async(i,t,e,r)=>{let n=[],a={};for(let[s,o]of Object.entries(i.results||{})){if(o.startsWith(f.Transform.Prefix))continue;let p=dt(o);if(p!==null&&p!==e){a[s]=null;continue}let[u,...d]=o.split(".");if(u==="out"||u.startsWith("out[")){let g=d.length===0?t?.data||t:ie(t,d);n.push(g),a[s]=g}else a[s]=o}return{values:n,results:await ot(i,a,e,r)}};var ot=async(i,t,e,r)=>{if(!i.results)return t;let n={...t};return n=ae(n,i,e,r),n=await se(i,n),n},ae=(i,t,e,r)=>{let n={...i},a=O(t,e)?.inputs||[],s=new k;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let u=p.split(".")[1],d=a.findIndex(w=>w.as===u||w.name===u),g=d!==-1?r[d]?.value:null;n[o]=g?s.stringToNative(g)[1]:null}return n},se=async(i,t)=>{if(!i.results)return t;let e={...t},r=Object.entries(i.results).filter(([,n])=>n.startsWith(f.Transform.Prefix)).map(([n,a])=>({key:n,code:a.substring(f.Transform.Prefix.length)}));for(let{key:n,code:a}of r)try{let{runInVm:s}=await Promise.resolve().then(()=>(vt(),bt));e[n]=await s(a,e)}catch(s){C.error(`Transform error for result '${n}':`,s),e[n]=null}return e};var oe=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],St=i=>oe.find(t=>t.id===i)||null;var nt=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return C.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return C.error("WarpContractLoader: getVerificationInfo error",r),null}}};var gt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new k,this.contractLoader=new nt(t),this.cache=new V(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=O(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let a=I.Address.newFromBech32(this.config.user.wallet),s=await T.getChainInfoForAction(this.config,n),o=new I.TransactionsFactoryConfig({chainID:s.chainId}),{destination:p,args:u,value:d,transfers:g,data:w,resolvedInputs:y}=await this.getTxComponentsFromInputs(s,n,r,a),B=u.map(W=>this.serializer.stringToTyped(W)),m=null;if(n.type==="transfer")m=new I.TransferTransactionsFactory({config:o}).createTransactionForTransfer(a,{receiver:p,nativeAmount:d,tokenTransfers:g,data:w?new Uint8Array(w):void 0});else if(n.type==="contract"&&p.isSmartContract())m=new I.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(a,{contract:p,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:B,tokenTransfers:g,nativeTransferAmount:d});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!m)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(S.LastWarpExecutionInputs(t.meta?.hash||"",e),y,Y.OneWeek),m}async getTransactionExecutionResults(t,e,r){let n=await N.apply(this.config,t),a=O(n,e),s=this.cache.get(S.LastWarpExecutionInputs(t.meta?.hash||"",e))??[],{values:o,results:p}=await At(this,n,a,r,e,s),u=T.getNextInfo(this.config,n,e,p),d=this.getPreparedMessages(n,p);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:u,values:o,results:p,messages:d}}async executeQuery(t,e,r){let n=O(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let a=await T.getChainInfoForAction(this.config,n),s=await N.apply(this.config,t),o=await this.getAbiForAction(n),{args:p,resolvedInputs:u}=await this.getTxComponentsFromInputs(a,n,r),d=p.map(ct=>this.serializer.stringToTyped(ct)),g=T.getChainEntrypoint(a,this.config.env),w=I.Address.newFromBech32(n.address),y=g.createSmartContractController(o),B=y.createQuery({contract:w,function:n.func,arguments:d}),m=await y.runQuery(B),W=m.returnCode==="ok",v=new I.ArgSerializer,E=o.getEndpoint(m.function),P=m.returnDataParts.map(ct=>Buffer.from(ct)),b=v.buffersToValues(P,E.output),{values:D,results:U}=await xt(s,b,e,u),R=T.getNextInfo(this.config,s,e,U);return{success:W,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:D,results:U,messages:this.getPreparedMessages(s,U)}}async executeCollect(t,e,r,n){let a=O(t,e);if(!a)throw new Error("WarpActionExecutor: Action not found");let s=await T.getChainInfoForAction(this.config,a),o=await N.apply(this.config,t),p=await this.getResolvedInputs(s,a,r),u=this.getModifiedInputs(p),d=m=>{if(!m.value)return null;let W=this.serializer.stringToNative(m.value)[1];if(m.input.type==="biguint")return W.toString();if(m.input.type==="esdt"){let v=W;return{token:v.token.identifier,nonce:v.token.nonce.toString(),amount:v.amount.toString()}}else return W},g=new Headers;g.set("Content-Type","application/json"),g.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([m,W])=>{g.set(m,W)});let w=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),y=a.destination.method||"GET",B=y==="GET"?void 0:JSON.stringify({inputs:w,meta:n});try{let m=await fetch(a.destination.url,{method:y,headers:g,body:B}),W=await m.json(),{values:v,results:E}=await Bt(o,W,e,u),P=T.getNextInfo(this.config,o,e,E);return{success:m.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:P,values:v,results:{...E,_DATA:W},messages:this.getPreparedMessages(o,E)}}catch(m){return C.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let a=await this.getResolvedInputs(t,e,r),s=this.getModifiedInputs(a),o=s.find(R=>R.input.position==="receiver")?.value,p="address"in e?e.address:null,u=o?.split(":")[1]||p||n?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let d=I.Address.newFromBech32(u),g=this.getPreparedArgs(e,s),w=s.find(R=>R.input.position==="value")?.value||null,y="value"in e?e.value:null,B=BigInt(w?.split(":")[1]||y||0),m=s.filter(R=>R.input.position==="transfer"&&R.value).map(R=>R.value),v=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...m?.map(R=>this.serializer.stringToNative(R)[1])||[]],E=s.find(R=>R.input.position==="data")?.value,P="data"in e?e.data||"":null,b=E||P||null,D=b?this.serializer.stringToTyped(b).valueOf():null,U=D?Buffer.from(D):null;return{destination:d,args:g,value:B,transfers:v,data:U,resolvedInputs:s}}async getResolvedInputs(t,e,r){let n=e.inputs||[],a=await Promise.all(r.map(o=>this.preprocessInput(t,o))),s=(o,p)=>{if(o.source==="query"){let u=this.url.searchParams.get(o.name);return u?this.serializer.nativeToString(o.type,u):null}else return o.source===f.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[p]||null};return n.map((o,p)=>({input:o,value:s(o,p)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let a=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(s,+a);return{...e,value:`${e.input.type}:${o}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let s=z(a,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(f.ArgParamsSeparator,2);if(r==="esdt"){let[a,s,o,p]=n.split(f.ArgCompositeSeparator);if(p)return e;let u=new I.Token({identifier:a,nonce:BigInt(s)});if(!new I.TokenComputer().isFungible(u))return e;let w=St(a)?.decimals;if(w||(w=(await(await fetch(`${t.apiUrl}/tokens/${a}`)).json()).decimals),!w)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let y=new I.TokenTransfer({token:u,amount:z(o,w)});return this.serializer.nativeToString(r,y)+f.ArgCompositeSeparator+w}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=A(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return I.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;r.splice(s,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,K(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(f.IdentifierType.Hash)){let e=new rt(this.config),r=t.abi.split(f.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return I.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return I.AbiRegistry.create(r)}}toTypedTransfer(t){return new I.TokenTransfer({token:new I.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var mt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,CacheTtl,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConfig,WarpConstants,WarpContractLoader,WarpIndex,WarpInterpolator,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getWarpActionByIndex,hex,list,nothing,option,optional,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,token,u16,u32,u64,u8,variadic});
1
+ "use strict";var Sr=Object.create;var K=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var Br=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var Ur=(n,r)=>{for(var e in r)K(n,e,{get:r[e],enumerable:!0})},yr=(n,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Rr(r))!$r.call(n,a)&&a!==e&&K(n,a,{get:()=>r[a],enumerable:!(t=Er(r,a))||t.enumerable});return n};var Z=(n,r,e)=>(e=n!=null?Sr(Br(n)):{},yr(r||!n||!n.__esModule?K(e,"default",{value:n,enumerable:!0}):e,n)),Nr=n=>yr(K({},"__esModule",{value:!0}),n);var se={};Ur(se,{BrowserCryptoProvider:()=>_,CacheTtl:()=>hr,NodeCryptoProvider:()=>Y,WarpBrandBuilder:()=>fr,WarpBuilder:()=>gr,WarpCache:()=>q,WarpCacheKey:()=>mr,WarpChainName:()=>xr,WarpClient:()=>Wr,WarpConfig:()=>I,WarpConstants:()=>p,WarpExecutor:()=>k,WarpFactory:()=>H,WarpIndex:()=>z,WarpInputTypes:()=>v,WarpInterpolator:()=>V,WarpLinkBuilder:()=>N,WarpLinkDetecter:()=>J,WarpLogger:()=>A,WarpProtocolVersions:()=>$,WarpSerializer:()=>P,WarpTypeRegistryImpl:()=>G,WarpValidator:()=>D,address:()=>ne,applyResultsToMessages:()=>cr,asset:()=>ae,biguint:()=>ee,boolean:()=>te,bytesToBase64:()=>Vr,bytesToHex:()=>vr,createAuthHeaders:()=>nr,createAuthMessage:()=>tr,createCryptoProvider:()=>Lr,createHttpAuthHeaders:()=>Jr,createSignableMessage:()=>br,evaluateResultsCommon:()=>Cr,extractCollectResults:()=>dr,extractIdentifierInfoFromUrl:()=>O,findWarpAdapterByPrefix:()=>S,findWarpAdapterForChain:()=>g,findWarpExecutableAction:()=>or,getCryptoProvider:()=>ar,getLatestProtocolIdentifier:()=>F,getNextInfo:()=>ur,getProviderConfig:()=>Gr,getProviderUrl:()=>qr,getRandomBytes:()=>ir,getRandomHex:()=>sr,getWarpActionByIndex:()=>R,getWarpInfoFromIdentifier:()=>b,hex:()=>ie,parseResultsOutIndex:()=>Ir,parseSignedMessage:()=>Xr,replacePlaceholders:()=>er,setCryptoProvider:()=>Hr,shiftBigintBy:()=>rr,string:()=>Kr,testCryptoAvailability:()=>Or,toPreviewText:()=>pr,u16:()=>_r,u32:()=>Yr,u64:()=>re,u8:()=>Zr,validateSignedMessage:()=>Qr});module.exports=Nr(se);var xr=(o=>(o.Multiversx="multiversx",o.Vibechain="vibechain",o.Sui="sui",o.Ethereum="ethereum",o.Base="base",o.Arbitrum="arbitrum",o.Fastset="fastset",o))(xr||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},v={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var $={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},I={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${$.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${$.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",p.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var _=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(r);return window.crypto.getRandomValues(e),e}},Y=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(r))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},U=null;function ar(){if(U)return U;if(typeof window<"u"&&window.crypto)return U=new _,U;if(typeof process<"u"&&process.versions?.node)return U=new Y,U;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Hr(n){U=n}async function ir(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||ar()).getRandomBytes(n)}function vr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let e=0;e<n.length;e++){let t=n[e];r[e*2]=(t>>>4).toString(16),r[e*2+1]=(t&15).toString(16)}return r.join("")}function Vr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function sr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await ir(n/2,r);return vr(e)}async function Or(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ir(16),n.randomBytes=!0}catch{}return n}function Lr(){return ar()}var g=(n,r)=>{let e=r.find(t=>t.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},S=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},F=n=>{if(n==="warp")return`warp:${$.Warp}`;if(n==="brand")return`brand:${$.Brand}`;if(n==="abi")return`abi:${$.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},R=(n,r)=>n?.actions[r-1],or=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:R(n,1),actionIndex:1}),rr=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),i=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(i,"0"));if(r<0){let s=t+a;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},pr=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},er=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),cr=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,er(a,r)]);return Object.fromEntries(e)};var Fr=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Dr=n=>{let r=p.IdentifierParamSeparator,e=-1,t="";for(let a of r){let i=n.indexOf(a);i!==-1&&(e===-1||i<e)&&(e=i,t=a)}return e!==-1?{separator:t,index:e}:null},Ar=n=>{let r=Dr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),i=n.substring(t+e.length),s=Ar(i);return[a,...s]},b=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=Ar(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,i,s]=t;if(i===p.IdentifierType.Alias||i===p.IdentifierType.Hash){let o=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:i,identifier:o,identifierBase:s}}}if(t.length===2){let[a,i]=t;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:p.IdentifierChainDefault,type:a,identifier:s,identifierBase:i}}}if(t.length===2){let[a,i]=t;if(a!==p.IdentifierType.Alias&&a!==p.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i,o=Fr(i,a)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chainPrefix:a,type:o,identifier:s,identifierBase:i}}}return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},O=n=>{let r=new URL(n),t=r.searchParams.get(p.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return b(a)};var wr=Z(require("qr-code-styling"),1);var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!O(r):!1}build(r,e,t){let a=this.config.clientUrl||I.DefaultClientUrl(this.config.env),i=g(r,this.adapters),s=e===p.IdentifierType.Alias?t:e+p.IdentifierParamSeparatorDefault+t,o=i.prefix+p.IdentifierParamSeparatorDefault+s,c=encodeURIComponent(o);return I.SuperClientUrls.includes(a)?`${a}/${c}`:`${a}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(r){let e=b(r);if(!e)return null;let t=S(e.chainPrefix,this.adapters);return t?this.build(t.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,i="white",s="black",o="#23F7DD"){let c=g(r,this.adapters),l=this.build(c.chainInfo.name,e,t);return new wr.default({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var jr="https://",ur=(n,r,e,t,a)=>{let i=e.actions?.[t]?.next||e.next||null;if(!i)return null;if(i.startsWith(jr))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:lr(r,s,n)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let h=er(o,{...e.vars,...a}),u=h?`${s}?${h}`:s;return[{identifier:u,url:lr(r,u,n)}]}let l=c[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),m=d?d[1]:null;if(!m||a[m]===void 0)return[];let f=Array.isArray(a[m])?a[m]:[a[m]];if(f.length===0)return[];let w=c.filter(h=>h.includes(`{{${m}[]`)).map(h=>{let u=h.match(/\[\](\.[^}]+)?}}/),W=u&&u[1]||"";return{placeholder:h,field:W?W.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let u=o;for(let{regex:C,field:x}of w){let T=x?Mr(h,x):h;if(T==null)return null;u=u.replace(C,T)}if(u.includes("{{")||u.includes("}}"))return null;let W=u?`${s}?${u}`:s;return{identifier:W,url:lr(r,W,n)}}).filter(h=>h!==null)},lr=(n,r,e)=>{let[t,a]=r.split("?"),i=b(t)||{chainPrefix:I.DefaultChainPrefix,type:"alias",identifier:t,identifierBase:t},s=S(i.chainPrefix,n);if(!s)throw new Error(`Adapter not found for chain ${i.chainPrefix}`);let o=new N(e,n).build(s.chainInfo.name,i.type,i.identifierBase);if(!a)return o;let c=new URL(o);return new URLSearchParams(a).forEach((l,d)=>c.searchParams.set(d,l)),c.toString().replace(/\/\?/,"?")},Mr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var qr=(n,r,e,t)=>{let a=n.providers?.[r];return a?.[e]?a[e]:t},Gr=(n,r)=>n.providers?.[r];var L=class L{static info(...r){L.isTestEnv||console.info(...r)}static warn(...r){L.isTestEnv||console.warn(...r)}static error(...r){L.isTestEnv||console.error(...r)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=L;var P=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,e){if(r==="asset"&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return`${r}:${e.identifier}|${e.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let t=this.typeRegistry.getHandler(r);if(t)return t.nativeToString(e)}return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(p.ArgParamsSeparator),t=e[0],a=e.slice(1).join(p.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[i,s]=a.split(p.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(t==="optional"){let[i,s]=a.split(p.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(t==="list"){let i=a.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,l]}else if(t==="variadic"){let i=a.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,l]}else if(t.startsWith("composite")){let i=t.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${i[l]}:${c}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="token")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="asset"){let[i,s]=a.split(p.ArgCompositeSeparator),o={identifier:i,amount:BigInt(s)};return[t,o]}}if(this.typeRegistry?.hasType(t)){let i=this.typeRegistry.getHandler(t);if(i){let s=i.stringToNative(a);return[t,s]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var dr=async(n,r,e,t,a)=>{let i=[],s={};for(let[o,c]of Object.entries(n.results||{})){if(c.startsWith(p.Transform.Prefix))continue;let l=Ir(c);if(l!==null&&l!==e){s[o]=null;continue}let[d,...m]=c.split("."),f=(w,E)=>E.reduce((h,u)=>h&&h[u]!==void 0?h[u]:null,w);if(d==="out"||d.startsWith("out[")){let w=m.length===0?r?.data||r:f(r,m);i.push(w),s[o]=w}else s[o]=c}return{values:i,results:await Cr(n,s,e,t,a)}},Cr=async(n,r,e,t,a)=>{if(!n.results)return r;let i={...r};return i=kr(i,n,e,t),i=await zr(n,i,a),i},kr=(n,r,e,t)=>{let a={...n},i=R(r,e)?.inputs||[],s=new P;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],d=i.findIndex(f=>f.as===l||f.name===l),m=d!==-1?t[d]?.value:null;a[o]=m?s.stringToNative(m)[1]:null}return a},zr=async(n,r,e)=>{if(!n.results)return r;let t={...r},a=Object.entries(n.results).filter(([,i])=>i.startsWith(p.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(p.Transform.Prefix.length)}));if(a.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:i,code:s}of a)try{t[i]=await e.run(s,t)}catch(o){A.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Ir=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function br(n,r,e,t=5){let a=await sr(64,e),i=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:i,purpose:r}),nonce:a,expiresAt:i}}async function tr(n,r,e,t){let a=t||`prove-wallet-ownership for app "${r}"`;return br(n,a,e,5)}function nr(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function Jr(n,r,e,t){let{message:a,nonce:i,expiresAt:s}=await tr(n,e,t),o=await r(a);return nr(n,o,i,s)}function Qr(n){let r=new Date(n).getTime();return Date.now()<r}function Xr(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Kr=n=>v.String+p.ArgParamsSeparator+n,Zr=n=>v.U8+p.ArgParamsSeparator+n,_r=n=>v.U16+p.ArgParamsSeparator+n,Yr=n=>v.U32+p.ArgParamsSeparator+n,re=n=>v.U64+p.ArgParamsSeparator+n,ee=n=>v.Biguint+p.ArgParamsSeparator+n,te=n=>v.Boolean+p.ArgParamsSeparator+n,ne=n=>v.Address+p.ArgParamsSeparator+n,ae=n=>{let r=p.ArgParamsSeparator,e=v.Asset+r+n.identifier+r+n.amount;return n.decimals?e+r+n.decimals:e},ie=n=>v.Hex+p.ArgParamsSeparator+n;var Pr=Z(require("ajv"),1);var fr=class{constructor(r){this.pendingBrand={protocol:F("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||I.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),i=new Pr.default,s=i.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var Tr=Z(require("ajv"),1);var D=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,i)=>{a&&Object.keys(a).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(s=>s.type==="contract"),t=r.actions.some(s=>s.type==="query");if(!e&&!t)return[];let a=r.actions.some(s=>s.abi),i=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return r.results&&!a&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||I.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),i=new Tr.default({strict:!1}),s=i.compile(a);return s(r)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var gr=class{constructor(r){this.config=r;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}async createFromUrl(r){return await(await fetch(r)).json()}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,e=100){return pr(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new D(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
2
+ `))}};var j=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var B=class B{get(r){let e=B.cache.get(r);return e?Date.now()>e.expiresAt?(B.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;B.cache.set(r,{value:e,expiresAt:a})}forget(r){B.cache.delete(r)}clear(){B.cache.clear()}};B.cache=new Map;var M=B;var hr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},mr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`},q=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new j:r==="memory"?new M:typeof window<"u"&&window.localStorage?new j:new M}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var G=class{constructor(){this.typeHandlers=new Map}registerType(r,e){this.typeHandlers.set(r,e)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var H=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new P,this.cache=new q(r.cache?.type);let t=new G;this.serializer.setTypeRegistry(t);for(let a of e)a.registerTypes&&a.registerTypes(t)}async createExecutable(r,e,t){let a=R(r,e);if(!a)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(a,t),s=await this.getResolvedInputs(i.name,a,t),o=this.getModifiedInputs(s),c=o.find(y=>y.input.position==="receiver")?.value,l="address"in a?a.address:null,d=c?this.serializer.stringToNative(c)[1]:l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(a,o),f=o.find(y=>y.input.position==="value")?.value||null,w="value"in a?a.value:null,E=BigInt(f?.split(":")[1]||w||0),h=o.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),C=[...("transfers"in a?a.transfers:[])||[],...h||[]].map(y=>this.serializer.stringToNative(y)[1]),x=o.find(y=>y.input.position==="data")?.value,T="data"in a?a.data||"":null,X={warp:r,chain:i,action:e,destination:d,args:m,value:E,transfers:C,data:x||T||null,resolvedInputs:o};return this.cache.set(mr.WarpExecutable(this.config.env,r.meta?.hash||"",e),X.resolvedInputs,hr.OneWeek),X}async getChainInfoForAction(r,e){if(r.chain)return g(r.chain,this.adapters).chainInfo;if(e){let a=await this.tryGetChainFromInputs(r,e);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,e,t){let a=e.inputs||[],i=await Promise.all(t.map(o=>this.preprocessInput(r,o))),s=(o,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:i[c]||null};return a.map((o,c)=>{let l=s(o,c);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let i=Number(r.find(c=>c.input.name===a)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=rr(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=rr(i,+a);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(p.ArgParamsSeparator,2),i=g(r,this.adapters);return i.executor.preprocessInput(i.chainInfo,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:i})=>{if(!i||!a.position?.startsWith("arg:"))return;let s=Number(a.position.split(":")[1])-1;t.splice(s,0,i)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(c=>c.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("Chain input not found");let s=new P().stringToNative(a)[1];return g(s,this.adapters).chainInfo}};var V=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(i,s)=>{t=t.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")a(i,s);else if(s.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&a(i,c)}else if(s.startsWith(`${p.Vars.Env}:`)){let o=s.split(`${p.Vars.Env}:`)[1],c=r.vars?.[o];c&&a(i,c)}else if(s===p.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let o=r.user.wallets[this.adapter.chainInfo.name];o&&a(i,o)}else a(i,s)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:e};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var k=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new H(r,e),this.serializer=new P}async execute(r,e){let{action:t,actionIndex:a}=or(r);if(t.type==="collect"){let c=await this.executeCollect(r,a,e);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(r,a,e),s=g(i.chain.name,this.adapters);if(t.type==="query"){let c=await s.executor.executeQuery(i);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:i.chain}}return{tx:await s.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,e,t){let a=await g(e,this.adapters).results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(a)}async executeCollect(r,e,t,a){let i=R(r,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=g(s.name,this.adapters),c=await new V(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(s.name,i,t),d=this.factory.getModifiedInputs(l),m=u=>{if(!u.value)return null;let W=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return W.toString();if(u.input.type==="asset"){let{identifier:C,amount:x}=W;return{identifier:C,amount:x.toString()}}else return W},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[s.name];if(!u)throw new Error(`No wallet configured for chain ${s.name}`);let{message:W,nonce:C,expiresAt:x}=await tr(u,`${s.name}-adapter`),T=await this.handlers.onSignRequest({message:W,chain:s}),Q=nr(u,T,C,x);Object.entries(Q).forEach(([X,y])=>f.set(X,y))}Object.entries(i.destination.headers||{}).forEach(([u,W])=>{f.set(u,W)});let w=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,m(u)])),E=i.destination.method||"GET",h=E==="GET"?void 0:JSON.stringify({...w,...a});A.info("Executing collect",{url:i.destination.url,method:E,headers:f,body:h});try{let u=await fetch(i.destination.url,{method:E,headers:f,body:h}),W=await u.json(),{values:C,results:x}=await dr(c,W,e,d,this.config.transform?.runner),T=ur(this.config,this.adapters,c,e,x);return{success:u.ok,warp:c,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:T,values:C,valuesRaw:C.map(Q=>this.serializer.stringToNative(Q)[1]),results:{...x,_DATA:W},messages:cr(c,x)}}catch(u){return A.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:c,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var z=class{constructor(r){this.config=r}async search(r,e,t){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw A.error("WarpIndex: Error searching for warps: ",a),a}}};var J=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),s=(await Promise.all(a)).filter(l=>l.match),o=s.length>0,c=s.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?O(r):b(r);if(!a)return t;try{let{type:i,identifierBase:s}=a,o=null,c=null,l=null,d=S(a.chainPrefix,this.adapters);if(i==="hash"){o=await d.builder().createFromTransactionHash(s,e);let f=await d.registry.getInfoByHash(s,e);c=f.registryInfo,l=f.brand}else if(i==="alias"){let f=await d.registry.getInfoByAlias(s,e);c=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let m=o?await new V(this.config,d).apply(this.config,o):null;return m?{match:!0,url:r,warp:m,chain:d.chainInfo.name,registryInfo:c,brand:l}:t}catch(i){return A.error("Error detecting warp link",i),t}}};var Wr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new k(this.config,this.adapters,r)}async detectWarp(r,e){return new J(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let i=r.startsWith("http")&&r.endsWith(".json")?await(await fetch(r)).json():(await this.detectWarp(r,a.cache)).warp;if(!i)throw new Error("Warp not found");let s=this.createExecutor(t),{tx:o,chain:c}=await s.execute(i,e);return{tx:o,chain:c,evaluateResults:async d=>{if(!c||!o||!i)throw new Error("Warp not found");await s.evaluateResults(i,c.name,d)}}}createInscriptionTransaction(r,e){return g(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return g(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=b(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return S(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return g(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return g(r,this.adapters).explorer}getResults(r){return g(r,this.adapters).results}async getRegistry(r){let e=g(r,this.adapters).registry;return await e.init(),e}getDataLoader(r){return g(r,this.adapters).dataLoader}get factory(){return new H(this.config,this.adapters)}get index(){return new z(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return g(r,this.adapters).builder()}createAbiBuilder(r){return g(r,this.adapters).abiBuilder()}createBrandBuilder(r){return g(r,this.adapters).brandBuilder()}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistryImpl,WarpValidator,address,applyResultsToMessages,asset,biguint,boolean,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpExecutableAction,getCryptoProvider,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getProviderUrl,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,setCryptoProvider,shiftBigintBy,string,testCryptoAvailability,toPreviewText,u16,u32,u64,u8,validateSignedMessage});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-3SAEGOMQ.mjs";import{Address as At,TransactionsFactoryConfig as We,TransferTransactionsFactory as Te}from"@multiversx/sdk-core";import Ce from"ajv";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:s=>s.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var $={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},v={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${$.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${$.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:s=>s==="devnet"?"https://devnet-explorer.multiversx.com":s==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:s=>6e3,AddressHrp:"erd",ChainId:s=>s==="devnet"?"D":s==="testnet"?"T":"1"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var C=s=>({name:v.MainChain.Name,displayName:v.MainChain.DisplayName,chainId:v.MainChain.ChainId(s.env),blockTime:v.MainChain.BlockTime(s.env),addressHrp:v.MainChain.AddressHrp,apiUrl:v.MainChain.ApiUrl(s.env),explorerUrl:v.MainChain.ExplorerUrl(s.env)}),gr=(s,t)=>s.explorerUrl+(t?"/"+t:""),L=s=>{if(s==="warp")return`warp:${$.Warp}`;if(s==="brand")return`brand:${$.Brand}`;if(s==="abi")return`abi:${$.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},F=(s,t)=>s?.actions[t-1],et=s=>({name:s.name.toString(),displayName:s.display_name.toString(),chainId:s.chain_id.toString(),blockTime:s.block_time.toNumber(),addressHrp:s.address_hrp.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString()}),M=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let a=r+n;if(i>=a.length)return 0n;let o=a.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Ct=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},j=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var _=class _{static info(...t){_.isTestEnv||console.info(...t)}static warn(...t){_.isTestEnv||console.warn(...t)}static error(...t){_.isTestEnv||console.error(...t)}};_.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=_;import{DevnetEntrypoint as me,MainnetEntrypoint as he,TestnetEntrypoint as ye}from"@multiversx/sdk-core";var D=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var N=class N{get(t){let e=N.cache.get(t);return e?Date.now()>e.expiresAt?(N.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;N.cache.set(t,{value:e,expiresAt:n})}forget(t){N.cache.delete(t)}clear(){N.cache.clear()}};N.cache=new Map;var H=N;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},B={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,LastWarpExecutionInputs:(s,t)=>`warp-exec-inputs:${s}:${t}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new D:t==="memory"?new H:typeof window<"u"&&window.localStorage?new D:new H}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};import ge from"qr-code-styling";import{Address as It,TransactionsFactoryConfig as pe,TransferTransactionsFactory as ue}from"@multiversx/sdk-core";import ce from"ajv";var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,i)=>{n&&Object.keys(n).forEach(a=>{a!==a.toUpperCase()&&e.push(`${i} name '${a}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi),i=Object.values(t.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||v.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new ce,a=i.compile(n);return a(t)?[]:[`Schema validation failed: ${i.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var z=class{constructor(t){this.pendingWarp={protocol:L("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=C(this.config),r=new pe({chainID:e.chainId}),n=new ue({config:r}),i=It.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=n.createTransactionForTransfer(i,{receiver:It.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.Warp(t);if(e){let o=this.cache.get(r);if(o)return w.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=C(this.config),a=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return w.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Ct(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new G(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
- `))}};var U=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(i,a)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(e.vars).forEach(([i,a])=>{if(typeof a!="string")n(i,a);else if(a.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&n(i,c)}else if(a.startsWith(`${l.Vars.Env}:`)){let o=a.split(`${l.Vars.Env}:`)[1],c=t.vars?.[o];c&&n(i,c)}else a===l.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,a)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:C(e)};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await y.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as vt,Address as R,AddressValue as nt,BytesValue as I,SmartContractTransactionsFactory as fe,TransactionsFactoryConfig as de}from"@multiversx/sdk-core/out";var rt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var K=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),owner:s.owner.toString(),createdAt:s.created_at.toNumber(),upgradedAt:s.upgraded_at?.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),bt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});var q=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let n=R.newFromBech32(this.config.user.wallet),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,a=()=>e&&r?[I.fromHex(t),I.fromUTF8(e),I.fromHex(r)]:e?[I.fromHex(t),I.fromUTF8(e)]:[I.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:a()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[I.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromUTF8(t),I.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t),I.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[I.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[I.fromHex(t),new nt(new R(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=R.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t),I.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getInfoByAlias",arguments:[I.fromUTF8(t)]}),c=await a.runQuery(o),[p]=a.parseQueryResponse(c),u=p?K(p):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=B.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return w.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[I.fromHex(t)]}),o=await i.runQuery(a),[c]=i.parseQueryResponse(o),p=c?K(c):null,u=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:u},e.ttl),{registryInfo:p,brand:u}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new nt(new R(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a);return o.map(K)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new nt(new R(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a),c=o.map(f=>f.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,p)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=B.ChainInfos();if(t&&t.ttl){let p=this.cache.get(e);if(p)return w.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a),c=o.map(et);if(t&&t.ttl){for(let p of c)this.cache.set(B.ChainInfo(p.chain),p,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getChain",arguments:[I.fromUTF8(t)]}),c=await a.runQuery(o),[p]=a.parseQueryResponse(c),u=p?et(p):null;return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch{return null}}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=C(this.config),o=y.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),p=JSON.parse(c.data.toString());return p.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return R.newFromBech32(this.config.registry?.contract||v.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?bt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=C(this.config),e=new de({chainID:t.chainId}),r=vt.create(rt);return new fe({config:e,abi:r})}getController(){let t=C(this.config),e=y.getChainEntrypoint(t,this.config.env),r=vt.create(rt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var J=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(n)).filter(p=>p.match),o=a.length>0,c=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:a}=n,o=new z(this.config),c=new q(this.config),p=null,u=null,f=null;if(i==="hash"){p=await o.createFromTransactionHash(a,e);let g=await c.getInfoByHash(a,e);u=g.registryInfo,f=g.brand}else if(i==="alias"){let g=await c.getInfoByAlias(a,e);u=g.registryInfo,f=g.brand,g.registryInfo&&(p=await o.createFromTransactionHash(g.registryInfo.hash,e))}let m=p?await U.apply(this.config,p):null;return m?{match:!0,url:t,warp:m,registryInfo:u,brand:f}:r}catch(i){return w.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||v.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return v.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=y.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",a="#23F7DD"){let o=this.build(t,e);return new ge({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=v.SuperClientUrls.includes(e.origin),n=e.searchParams.get(l.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return y.getInfoFromPrefixedIdentifier(a)}};var we="https://",y=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(l.IdentifierParamSeparator)?e:`${l.IdentifierType.Alias}${l.IdentifierParamSeparator}${e}`,[n,i]=r.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(we))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:this.buildNextUrl(a,t)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let d=j(o,{...e.vars,...n}),h=d?`${a}?${d}`:a;return[{identifier:h,url:this.buildNextUrl(h,t)}]}let p=c[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||n[f]===void 0)return[];let m=Array.isArray(n[f])?n[f]:[n[f]];if(m.length===0)return[];let g=c.filter(d=>d.includes(`{{${f}[]`)).map(d=>{let h=d.match(/\[\](\.[^}]+)?}}/),T=h&&h[1]||"";return{placeholder:d,field:T?T.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(d=>{let h=o;for(let{regex:A,field:E}of g){let W=E?this.getNestedValue(d,E):d;if(W==null)return null;h=h.replace(A,W)}if(h.includes("{{")||h.includes("}}"))return null;let T=h?`${a}?${h}`:a;return{identifier:T,url:this.buildNextUrl(T,t)}}).filter(d=>d!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new J(e).build(i.type,i.identifierBase);if(!n)return o;let c=new URL(o);return new URLSearchParams(n).forEach((p,u)=>c.searchParams.set(u,p)),c.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return C(t);let r=await new q(t).getChainInfo(e.chain,{ttl:Q.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new me(t.apiUrl,n,r):e==="testnet"?new ye(t.apiUrl,n,r):new he(t.apiUrl,n,r)}};var xt=class{constructor(t){this.pendingBrand={protocol:L("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=C(this.config),r=new We({chainID:e.chainId}),n=new Te({config:r}),i=At.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:At.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=C(this.config),n=y.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return w.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||v.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new Ce,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};import{Address as Ie,AddressValue as be,BigUIntType as ve,BigUIntValue as Bt,BooleanValue as Ae,BytesValue as xe,CodeMetadata as Be,CodeMetadataValue as Se,CompositeType as Ee,CompositeValue as Re,Field as it,FieldDefinition as at,List as Pe,NothingValue as Ve,OptionalValue as st,OptionValue as ot,StringValue as Ne,Struct as Ue,StructType as Fe,TokenIdentifierType as Oe,TokenIdentifierValue as St,U16Value as ke,U32Value as $e,U64Type as Le,U64Value as Et,U8Value as _e,VariadicValue as qe}from"@multiversx/sdk-core/out";var Fn=(s,t)=>s?ot.newProvided(s):t?ot.newMissingTyped(t):ot.newMissing(),On=(s,t)=>s?new st(s.getType(),s):t?new st(t):st.newMissing(),kn=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Pe(t,s)},$n=s=>qe.fromItems(...s),Ln=s=>{let t=s.map(e=>e.getType());return new Re(new Ee(...t),s)},_n=s=>Ne.fromUTF8(s),qn=s=>new _e(s),Dn=s=>new ke(s),Hn=s=>new $e(s),Mn=s=>new Et(s),jn=s=>new Bt(BigInt(s)),Qn=s=>new Ae(s),Gn=s=>new be(Ie.newFromBech32(s)),zn=s=>new St(s),Kn=s=>xe.fromHex(s),Jn=s=>new Ue(new Fe("EsdtTokenPayment",[new at("token_identifier","",new Oe),new at("token_nonce","",new Le),new at("amount","",new ve)]),[new it(new St(s.token.identifier),"token_identifier"),new it(new Et(BigInt(s.token.nonce)),"token_nonce"),new it(new Bt(BigInt(s.amount)),"amount")]),Xn=s=>new Se(Be.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Yn=()=>new Ve;import{Address as De,TransactionsFactoryConfig as He,TransferTransactionsFactory as Me}from"@multiversx/sdk-core";var X=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=C(this.config),r=new He({chainID:e.chainId}),n=new Me({config:r}),i={protocol:L("abi"),content:t},a=De.newFromBech32(this.config.user.wallet),o=JSON.stringify(i),c=n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=B.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return w.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=C(this.config),a=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return w.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as Wt,Address as Tt,ArgSerializer as ar,SmartContractTransactionsFactory as sr,Token as ie,TokenComputer as or,TokenTransfer as ae,TransactionsFactoryConfig as cr,TransferTransactionsFactory as pr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Ye,TransactionEventsParser as Ze,findEventsByFirstTopic as tr}from"@multiversx/sdk-core/out";import{Address as je,AddressType as Rt,AddressValue as Pt,BigUIntType as ct,BigUIntValue as pt,BooleanType as Vt,BooleanValue as Nt,BytesType as Ut,BytesValue as Ft,CodeMetadata as Qe,CodeMetadataType as Ot,CodeMetadataValue as kt,CompositeType as $t,CompositeValue as Lt,Field as ut,FieldDefinition as lt,List as _t,ListType as Ge,NothingValue as S,OptionalType as ze,OptionalValue as ft,OptionType as Ke,OptionValue as dt,StringType as qt,StringValue as Dt,Struct as Je,StructType as Ht,Token as Xe,TokenIdentifierType as gt,TokenIdentifierValue as mt,TokenTransfer as Mt,U16Type as jt,U16Value as Qt,U32Type as Gt,U32Value as zt,U64Type as ht,U64Value as yt,U8Type as Kt,U8Value as Jt,VariadicType as Xt,VariadicValue as Yt}from"@multiversx/sdk-core/out";var Zt=new RegExp(`${l.ArgParamsSeparator}(.*)`),O=class{nativeToString(t,e){return t==="esdt"&&e instanceof Mt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(dt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(ft.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(_t.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(l.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(l.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Yt.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(l.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(l.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Lt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[1]),i=r.join(l.ArgCompositeSeparator),a=n.join(l.ArgCompositeSeparator);return`composite(${i}):${a}`}if(t.hasClassOrSuperclass(pt.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Jt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Qt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(zt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(yt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Dt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(mt.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ft.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(kt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new $t(...e.split(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new qt;if(t==="uint8")return new Kt;if(t==="uint16")return new jt;if(t==="uint32")return new Gt;if(t==="uint64")return new ht;if(t==="biguint")return new ct;if(t==="bool")return new Vt;if(t==="address")return new Rt;if(t==="token")return new gt;if(t==="hex")return new Ut;if(t==="codemeta")return new Ot;if(t==="esdt"||t==="nft")return new Ht("EsdtTokenPayment",[new lt("token_identifier","",new gt),new lt("token_nonce","",new ht),new lt("amount","",new ct)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(l.ArgParamsSeparator),r=e[0],n=e.slice(1).join(l.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,a]=n.split(l.ArgParamsSeparator);return[`option:${i}`,a||null]}else if(r==="optional"){let[i,a]=n.split(l.ArgParamsSeparator);return[`optional:${i}`,a||null]}else if(r==="list"){let i=n.split(l.ArgParamsSeparator),a=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let i=n.split(l.ArgParamsSeparator),a=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${i[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,a,o]=n.split(l.ArgCompositeSeparator);return[r,new Mt({token:new Xe({identifier:i,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new S;if(e==="option"){let n=this.stringToTyped(r);return n instanceof S?dt.newMissingTyped(n.getType()):dt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof S?ft.newMissing():new ft(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Zt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new _t(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Zt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Yt(new Xt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(l.ArgCompositeSeparator),a=n.split(l.ArgCompositeSeparator),o=i.map((p,u)=>this.stringToTyped(`${a[u]}:${p}`)),c=o.map(p=>p.getType());return new Lt(new $t(...c),o)}if(e==="string")return r?Dt.fromUTF8(r):new S;if(e==="uint8")return r?new Jt(Number(r)):new S;if(e==="uint16")return r?new Qt(Number(r)):new S;if(e==="uint32")return r?new zt(Number(r)):new S;if(e==="uint64")return r?new yt(BigInt(r)):new S;if(e==="biguint")return r?new pt(BigInt(r)):new S;if(e==="bool")return r?new Nt(typeof r=="boolean"?r:r==="true"):new S;if(e==="address")return r?new Pt(je.newFromBech32(r)):new S;if(e==="token")return r?new mt(r):new S;if(e==="hex")return r?Ft.fromHex(r):new S;if(e==="codemeta")return new kt(Qe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new Je(this.nativeToType("esdt"),[new ut(new mt(n[0]),"token_identifier"),new ut(new yt(BigInt(n[1])),"token_nonce"),new ut(new pt(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Ke)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ze)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ge)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Xt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof qt)return"string";if(t instanceof Kt)return"uint8";if(t instanceof jt)return"uint16";if(t instanceof Gt)return"uint32";if(t instanceof ht)return"uint64";if(t instanceof ct)return"biguint";if(t instanceof Vt)return"bool";if(t instanceof Rt)return"address";if(t instanceof gt)return"token";if(t instanceof Ut)return"hex";if(t instanceof Ot)return"codemeta";if(t instanceof Ht&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var wt=s=>{if(s==="out")return 1;let t=s.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(s.startsWith("out.")||s.startsWith("event."),null)},er=(s,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,s),te=async(s,t,e,r,n,i)=>{let a=[],o={};if(!t.results||e.type!=="contract")return{values:a,results:o};if(!Object.values(t.results).some(g=>g.includes("out")||g.includes("event"))){for(let[g,b]of Object.entries(t.results))o[g]=b;return{values:a,results:await Y(t,o,n,i)}}let p=await s.getAbiForAction(e),u=new Ze({abi:p}),m=new Ye({abi:p}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[g,b]of Object.entries(t.results)){if(b.startsWith(l.Transform.Prefix))continue;if(b.startsWith("input.")){o[g]=b;continue}let d=wt(b);if(d!==null&&d!==n){o[g]=null;continue}let[h,T,A]=b.split(".");if(h==="event"){if(!T||isNaN(Number(A)))continue;let E=Number(A),W=tr(r,T),k=u.parseEvents({events:W})[0],P=Object.values(k)[E]||null;a.push(P),o[g]=P&&P.valueOf()}else if(h==="out"||h.startsWith("out[")){if(!T)continue;let E=Number(T),W=m.values[E-1]||null;A&&(W=W[A]||null),W&&typeof W=="object"&&(W="toFixed"in W?W.toFixed():W.valueOf()),a.push(W),o[g]=W&&W.valueOf()}else o[g]=b}return{values:a,results:await Y(t,o,n,i)}},ee=async(s,t,e,r)=>{let n=new O,i=t.map(p=>n.typedToString(p)),a=t.map(p=>n.typedToNative(p)[1]),o={};if(!s.results)return{values:i,results:o};let c=p=>{let u=p.split(".").slice(1).map(m=>parseInt(m)-1);if(u.length===0)return;let f=a[u[0]];for(let m=1;m<u.length;m++){if(f==null)return;f=f[u[m]]}return f};for(let[p,u]of Object.entries(s.results)){if(u.startsWith(l.Transform.Prefix))continue;let f=wt(u);if(f!==null&&f!==e){o[p]=null;continue}u.startsWith("out.")||u==="out"||u.startsWith("out[")?o[p]=c(u)||null:o[p]=u}return{values:i,results:await Y(s,o,e,r)}},re=async(s,t,e,r)=>{let n=[],i={};for(let[a,o]of Object.entries(s.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let c=wt(o);if(c!==null&&c!==e){i[a]=null;continue}let[p,...u]=o.split(".");if(p==="out"||p.startsWith("out[")){let f=u.length===0?t?.data||t:er(t,u);n.push(f),i[a]=f}else i[a]=o}return{values:n,results:await Y(s,i,e,r)}};var Y=async(s,t,e,r)=>{if(!s.results)return t;let n={...t};return n=rr(n,s,e,r),n=await nr(s,n),n},rr=(s,t,e,r)=>{let n={...s},i=F(t,e)?.inputs||[],a=new O;for(let[o,c]of Object.entries(n))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=i.findIndex(m=>m.as===p||m.name===p),f=u!==-1?r[u]?.value:null;n[o]=f?a.stringToNative(f)[1]:null}return n},nr=async(s,t)=>{if(!s.results)return t;let e={...t},r=Object.entries(s.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of r)try{let{runInVm:a}=await import("./vm-JCVDACTR.mjs");e[n]=await a(i,e)}catch(a){w.error(`Transform error for result '${n}':`,a),e[n]=null}return e};var ir=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ne=s=>ir.find(t=>t.id===s)||null;var Z=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return w.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return w.error("WarpContractLoader: getVerificationInfo error",r),null}}};var se=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new O,this.contractLoader=new Z(t),this.cache=new V(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=F(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let i=Tt.newFromBech32(this.config.user.wallet),a=await y.getChainInfoForAction(this.config,n),o=new cr({chainID:a.chainId}),{destination:c,args:p,value:u,transfers:f,data:m,resolvedInputs:g}=await this.getTxComponentsFromInputs(a,n,r,i),b=p.map(h=>this.serializer.stringToTyped(h)),d=null;if(n.type==="transfer")d=new pr({config:o}).createTransactionForTransfer(i,{receiver:c,nativeAmount:u,tokenTransfers:f,data:m?new Uint8Array(m):void 0});else if(n.type==="contract"&&c.isSmartContract())d=new sr({config:o}).createTransactionForExecute(i,{contract:c,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:b,tokenTransfers:f,nativeTransferAmount:u});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!d)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(B.LastWarpExecutionInputs(t.meta?.hash||"",e),g,Q.OneWeek),d}async getTransactionExecutionResults(t,e,r){let n=await U.apply(this.config,t),i=F(n,e),a=this.cache.get(B.LastWarpExecutionInputs(t.meta?.hash||"",e))??[],{values:o,results:c}=await te(this,n,i,r,e,a),p=y.getNextInfo(this.config,n,e,c),u=this.getPreparedMessages(n,c);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:p,values:o,results:c,messages:u}}async executeQuery(t,e,r){let n=F(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await y.getChainInfoForAction(this.config,n),a=await U.apply(this.config,t),o=await this.getAbiForAction(n),{args:c,resolvedInputs:p}=await this.getTxComponentsFromInputs(i,n,r),u=c.map(tt=>this.serializer.stringToTyped(tt)),f=y.getChainEntrypoint(i,this.config.env),m=Tt.newFromBech32(n.address),g=f.createSmartContractController(o),b=g.createQuery({contract:m,function:n.func,arguments:u}),d=await g.runQuery(b),h=d.returnCode==="ok",T=new ar,A=o.getEndpoint(d.function),E=d.returnDataParts.map(tt=>Buffer.from(tt)),W=T.buffersToValues(E,A.output),{values:k,results:P}=await ee(a,W,e,p),x=y.getNextInfo(this.config,a,e,P);return{success:h,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:x,values:k,results:P,messages:this.getPreparedMessages(a,P)}}async executeCollect(t,e,r,n){let i=F(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let a=await y.getChainInfoForAction(this.config,i),o=await U.apply(this.config,t),c=await this.getResolvedInputs(a,i,r),p=this.getModifiedInputs(c),u=d=>{if(!d.value)return null;let h=this.serializer.stringToNative(d.value)[1];if(d.input.type==="biguint")return h.toString();if(d.input.type==="esdt"){let T=h;return{token:T.token.identifier,nonce:T.token.nonce.toString(),amount:T.amount.toString()}}else return h},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,h])=>{f.set(d,h)});let m=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,u(d)])),g=i.destination.method||"GET",b=g==="GET"?void 0:JSON.stringify({inputs:m,meta:n});try{let d=await fetch(i.destination.url,{method:g,headers:f,body:b}),h=await d.json(),{values:T,results:A}=await re(o,h,e,p),E=y.getNextInfo(this.config,o,e,A);return{success:d.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:E,values:T,results:{...A,_DATA:h},messages:this.getPreparedMessages(o,A)}}catch(d){return w.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let i=await this.getResolvedInputs(t,e,r),a=this.getModifiedInputs(i),o=a.find(x=>x.input.position==="receiver")?.value,c="address"in e?e.address:null,p=o?.split(":")[1]||c||n?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let u=Tt.newFromBech32(p),f=this.getPreparedArgs(e,a),m=a.find(x=>x.input.position==="value")?.value||null,g="value"in e?e.value:null,b=BigInt(m?.split(":")[1]||g||0),d=a.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),T=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...d?.map(x=>this.serializer.stringToNative(x)[1])||[]],A=a.find(x=>x.input.position==="data")?.value,E="data"in e?e.data||"":null,W=A||E||null,k=W?this.serializer.stringToTyped(W).valueOf():null,P=k?Buffer.from(k):null;return{destination:u,args:f,value:b,transfers:T,data:P,resolvedInputs:a}}async getResolvedInputs(t,e,r){let n=e.inputs||[],i=await Promise.all(r.map(o=>this.preprocessInput(t,o))),a=(o,c)=>{if(o.source==="query"){let p=this.url.searchParams.get(o.name);return p?this.serializer.nativeToString(o.type,p):null}else return o.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:i[c]||null};return n.map((o,c)=>({input:o,value:a(o,c)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(i,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(l.ArgParamsSeparator,2);if(r==="esdt"){let[i,a,o,c]=n.split(l.ArgCompositeSeparator);if(c)return e;let p=new ie({identifier:i,nonce:BigInt(a)});if(!new or().isFungible(p))return e;let m=ne(i)?.decimals;if(m||(m=(await(await fetch(`${t.apiUrl}/tokens/${i}`)).json()).decimals),!m)throw new Error(`WarpActionExecutor: Decimals not found for token ${i}`);let g=new ae({token:p,amount:M(o,m)});return this.serializer.nativeToString(r,g)+l.ArgCompositeSeparator+m}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=C(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return Wt.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let a=Number(n.position.split(":")[1])-1;r.splice(a,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,j(i,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(l.IdentifierType.Hash)){let e=new X(this.config),r=t.abi.split(l.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return Wt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return Wt.create(r)}}toTypedTransfer(t){return new ae({token:new ie({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var oe=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw w.error("WarpIndex: Error searching for warps: ",n),n}}};export{xt as BrandBuilder,B as CacheKey,Q as CacheTtl,X as WarpAbiBuilder,se as WarpActionExecutor,O as WarpArgSerializer,z as WarpBuilder,V as WarpCache,v as WarpConfig,l as WarpConstants,Z as WarpContractLoader,oe as WarpIndex,U as WarpInterpolator,J as WarpLink,$ as WarpProtocolVersions,q as WarpRegistry,y as WarpUtils,G as WarpValidator,Gn as address,jn as biguint,Qn as boolean,Xn as codemeta,Ln as composite,Jn as esdt,gr as getChainExplorerUrl,L as getLatestProtocolIdentifier,C as getMainChainInfo,F as getWarpActionByIndex,Kn as hex,kn as list,Yn as nothing,Fn as option,On as optional,j as replacePlaceholders,M as shiftBigintBy,_n as string,Ct as toPreviewText,et as toTypedChainInfo,zn as token,Dn as u16,Hn as u32,Mn as u64,qn as u8,$n as variadic};
1
+ var Wr=(o=>(o.Multiversx="multiversx",o.Vibechain="vibechain",o.Sui="sui",o.Ethereum="ethereum",o.Base="base",o.Arbitrum="arbitrum",o.Fastset="fastset",o))(Wr||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},v={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var U={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},b={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",c.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var K=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(r);return window.crypto.getRandomValues(e),e}},Z=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(r))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},B=null;function nr(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new K,B;if(typeof process<"u"&&process.versions?.node)return B=new Z,B;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Nr(n){B=n}async function ar(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||nr()).getRandomBytes(n)}function yr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let e=0;e<n.length;e++){let t=n[e];r[e*2]=(t>>>4).toString(16),r[e*2+1]=(t&15).toString(16)}return r.join("")}function Hr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function ir(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await ar(n/2,r);return yr(e)}async function Vr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ar(16),n.randomBytes=!0}catch{}return n}function Or(){return nr()}var h=(n,r)=>{let e=r.find(t=>t.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},E=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},q=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},$=(n,r)=>n?.actions[r-1],sr=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:$(n,1),actionIndex:1}),_=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),i=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(i,"0"));if(r<0){let s=t+a;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},or=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},Y=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),pr=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,Y(a,r)]);return Object.fromEntries(e)};var xr=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,vr=n=>{let r=c.IdentifierParamSeparator,e=-1,t="";for(let a of r){let i=n.indexOf(a);i!==-1&&(e===-1||i<e)&&(e=i,t=a)}return e!==-1?{separator:t,index:e}:null},cr=n=>{let r=vr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),i=n.substring(t+e.length),s=cr(i);return[a,...s]},P=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=cr(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,i,s]=t;if(i===c.IdentifierType.Alias||i===c.IdentifierType.Hash){let o=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:i,identifier:o,identifierBase:s}}}if(t.length===2){let[a,i]=t;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:c.IdentifierChainDefault,type:a,identifier:s,identifierBase:i}}}if(t.length===2){let[a,i]=t;if(a!==c.IdentifierType.Alias&&a!==c.IdentifierType.Hash){let s=r.includes("?")?i+r.substring(r.indexOf("?")):i,o=xr(i,a)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chainPrefix:a,type:o,identifier:s,identifierBase:i}}}return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},L=n=>{let r=new URL(n),t=r.searchParams.get(c.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return P(a)};import Ar from"qr-code-styling";var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!L(r):!1}build(r,e,t){let a=this.config.clientUrl||b.DefaultClientUrl(this.config.env),i=h(r,this.adapters),s=e===c.IdentifierType.Alias?t:e+c.IdentifierParamSeparatorDefault+t,o=i.prefix+c.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return b.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let e=P(r);if(!e)return null;let t=E(e.chainPrefix,this.adapters);return t?this.build(t.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,i="white",s="black",o="#23F7DD"){let p=h(r,this.adapters),l=this.build(p.chainInfo.name,e,t);return new Ar({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var wr="https://",lr=(n,r,e,t,a)=>{let i=e.actions?.[t]?.next||e.next||null;if(!i)return null;if(i.startsWith(wr))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:rr(r,s,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=Y(o,{...e.vars,...a}),u=g?`${s}?${g}`:s;return[{identifier:u,url:rr(r,u,n)}]}let l=p[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),m=d?d[1]:null;if(!m||a[m]===void 0)return[];let f=Array.isArray(a[m])?a[m]:[a[m]];if(f.length===0)return[];let w=p.filter(g=>g.includes(`{{${m}[]`)).map(g=>{let u=g.match(/\[\](\.[^}]+)?}}/),W=u&&u[1]||"";return{placeholder:g,field:W?W.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let u=o;for(let{regex:C,field:x}of w){let I=x?Cr(g,x):g;if(I==null)return null;u=u.replace(C,I)}if(u.includes("{{")||u.includes("}}"))return null;let W=u?`${s}?${u}`:s;return{identifier:W,url:rr(r,W,n)}}).filter(g=>g!==null)},rr=(n,r,e)=>{let[t,a]=r.split("?"),i=P(t)||{chainPrefix:b.DefaultChainPrefix,type:"alias",identifier:t,identifierBase:t},s=E(i.chainPrefix,n);if(!s)throw new Error(`Adapter not found for chain ${i.chainPrefix}`);let o=new N(e,n).build(s.chainInfo.name,i.type,i.identifierBase);if(!a)return o;let p=new URL(o);return new URLSearchParams(a).forEach((l,d)=>p.searchParams.set(d,l)),p.toString().replace(/\/\?/,"?")},Cr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var re=(n,r,e,t)=>{let a=n.providers?.[r];return a?.[e]?a[e]:t},ee=(n,r)=>n.providers?.[r];var H=class H{static info(...r){H.isTestEnv||console.info(...r)}static warn(...r){H.isTestEnv||console.warn(...r)}static error(...r){H.isTestEnv||console.error(...r)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=H;var T=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,e){if(r==="asset"&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return`${r}:${e.identifier}|${e.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let t=this.typeRegistry.getHandler(r);if(t)return t.nativeToString(e)}return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(c.ArgParamsSeparator),t=e[0],a=e.slice(1).join(c.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[i,s]=a.split(c.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(t==="optional"){let[i,s]=a.split(c.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(t==="list"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,l]}else if(t==="variadic"){let i=a.split(c.ArgParamsSeparator),s=i.slice(0,-1).join(c.ArgParamsSeparator),o=i[i.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,l]}else if(t.startsWith("composite")){let i=t.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=a.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${i[l]}:${p}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="token")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="asset"){let[i,s]=a.split(c.ArgCompositeSeparator),o={identifier:i,amount:BigInt(s)};return[t,o]}}if(this.typeRegistry?.hasType(t)){let i=this.typeRegistry.getHandler(t);if(i){let s=i.stringToNative(a);return[t,s]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var ur=async(n,r,e,t,a)=>{let i=[],s={};for(let[o,p]of Object.entries(n.results||{})){if(p.startsWith(c.Transform.Prefix))continue;let l=Tr(p);if(l!==null&&l!==e){s[o]=null;continue}let[d,...m]=p.split("."),f=(w,S)=>S.reduce((g,u)=>g&&g[u]!==void 0?g[u]:null,w);if(d==="out"||d.startsWith("out[")){let w=m.length===0?r?.data||r:f(r,m);i.push(w),s[o]=w}else s[o]=p}return{values:i,results:await Ir(n,s,e,t,a)}},Ir=async(n,r,e,t,a)=>{if(!n.results)return r;let i={...r};return i=br(i,n,e,t),i=await Pr(n,i,a),i},br=(n,r,e,t)=>{let a={...n},i=$(r,e)?.inputs||[],s=new T;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let l=p.split(".")[1],d=i.findIndex(f=>f.as===l||f.name===l),m=d!==-1?t[d]?.value:null;a[o]=m?s.stringToNative(m)[1]:null}return a},Pr=async(n,r,e)=>{if(!n.results)return r;let t={...r},a=Object.entries(n.results).filter(([,i])=>i.startsWith(c.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(c.Transform.Prefix.length)}));if(a.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:i,code:s}of a)try{t[i]=await e.run(s,t)}catch(o){A.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Tr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Sr(n,r,e,t=5){let a=await ir(64,e),i=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:i,purpose:r}),nonce:a,expiresAt:i}}async function er(n,r,e,t){let a=t||`prove-wallet-ownership for app "${r}"`;return Sr(n,a,e,5)}function tr(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function fe(n,r,e,t){let{message:a,nonce:i,expiresAt:s}=await er(n,e,t),o=await r(a);return tr(n,o,i,s)}function ge(n){let r=new Date(n).getTime();return Date.now()<r}function he(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var ye=n=>v.String+c.ArgParamsSeparator+n,xe=n=>v.U8+c.ArgParamsSeparator+n,ve=n=>v.U16+c.ArgParamsSeparator+n,Ae=n=>v.U32+c.ArgParamsSeparator+n,we=n=>v.U64+c.ArgParamsSeparator+n,Ce=n=>v.Biguint+c.ArgParamsSeparator+n,Ie=n=>v.Boolean+c.ArgParamsSeparator+n,be=n=>v.Address+c.ArgParamsSeparator+n,Pe=n=>{let r=c.ArgParamsSeparator,e=v.Asset+r+n.identifier+r+n.amount;return n.decimals?e+r+n.decimals:e},Te=n=>v.Hex+c.ArgParamsSeparator+n;import Er from"ajv";var dr=class{constructor(r){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||b.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),i=new Er,s=i.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import Rr from"ajv";var G=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,i)=>{a&&Object.keys(a).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(s=>s.type==="contract"),t=r.actions.some(s=>s.type==="query");if(!e&&!t)return[];let a=r.actions.some(s=>s.abi),i=Object.values(r.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return r.results&&!a&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||b.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),i=new Rr({strict:!1}),s=i.compile(a);return s(r)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var fr=class{constructor(r){this.config=r;this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}async createFromUrl(r){return await(await fetch(r)).json()}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,e=100){return or(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new G(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
2
+ `))}};var F=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var R=class R{get(r){let e=R.cache.get(r);return e?Date.now()>e.expiresAt?(R.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;R.cache.set(r,{value:e,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var D=R;var gr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},hr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`},k=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new F:r==="memory"?new D:typeof window<"u"&&window.localStorage?new F:new D}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var z=class{constructor(){this.typeHandlers=new Map}registerType(r,e){this.typeHandlers.set(r,e)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var V=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new T,this.cache=new k(r.cache?.type);let t=new z;this.serializer.setTypeRegistry(t);for(let a of e)a.registerTypes&&a.registerTypes(t)}async createExecutable(r,e,t){let a=$(r,e);if(!a)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(a,t),s=await this.getResolvedInputs(i.name,a,t),o=this.getModifiedInputs(s),p=o.find(y=>y.input.position==="receiver")?.value,l="address"in a?a.address:null,d=p?this.serializer.stringToNative(p)[1]:l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(a,o),f=o.find(y=>y.input.position==="value")?.value||null,w="value"in a?a.value:null,S=BigInt(f?.split(":")[1]||w||0),g=o.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),C=[...("transfers"in a?a.transfers:[])||[],...g||[]].map(y=>this.serializer.stringToNative(y)[1]),x=o.find(y=>y.input.position==="data")?.value,I="data"in a?a.data||"":null,M={warp:r,chain:i,action:e,destination:d,args:m,value:S,transfers:C,data:x||I||null,resolvedInputs:o};return this.cache.set(hr.WarpExecutable(this.config.env,r.meta?.hash||"",e),M.resolvedInputs,gr.OneWeek),M}async getChainInfoForAction(r,e){if(r.chain)return h(r.chain,this.adapters).chainInfo;if(e){let a=await this.tryGetChainFromInputs(r,e);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,e,t){let a=e.inputs||[],i=await Promise.all(t.map(o=>this.preprocessInput(r,o))),s=(o,p)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===c.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:i[p]||null};return a.map((o,p)=>{let l=s(o,p);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let i=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=_(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=_(i,+a);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(c.ArgParamsSeparator,2),i=h(r,this.adapters);return i.executor.preprocessInput(i.chainInfo,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:i})=>{if(!i||!a.position?.startsWith("arg:"))return;let s=Number(a.position.split(":")[1])-1;t.splice(s,0,i)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(p=>p.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("Chain input not found");let s=new T().stringToNative(a)[1];return h(s,this.adapters).chainInfo}};var O=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(i,s)=>{t=t.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")a(i,s);else if(s.startsWith(`${c.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${c.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(i,p)}else if(s.startsWith(`${c.Vars.Env}:`)){let o=s.split(`${c.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(i,p)}else if(s===c.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let o=r.user.wallets[this.adapter.chainInfo.name];o&&a(i,o)}else a(i,s)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:e};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(a);s!=null&&(t=t.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(t)}};var J=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new V(r,e),this.serializer=new T}async execute(r,e){let{action:t,actionIndex:a}=sr(r);if(t.type==="collect"){let p=await this.executeCollect(r,a,e);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(r,a,e),s=h(i.chain.name,this.adapters);if(t.type==="query"){let p=await s.executor.executeQuery(i);return p.success?this.handlers?.onExecuted?.(p):this.handlers?.onError?.({message:JSON.stringify(p.values)}),{tx:null,chain:i.chain}}return{tx:await s.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,e,t){let a=await h(e,this.adapters).results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(a)}async executeCollect(r,e,t,a){let i=$(r,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=h(s.name,this.adapters),p=await new O(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(s.name,i,t),d=this.factory.getModifiedInputs(l),m=u=>{if(!u.value)return null;let W=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return W.toString();if(u.input.type==="asset"){let{identifier:C,amount:x}=W;return{identifier:C,amount:x.toString()}}else return W},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[s.name];if(!u)throw new Error(`No wallet configured for chain ${s.name}`);let{message:W,nonce:C,expiresAt:x}=await er(u,`${s.name}-adapter`),I=await this.handlers.onSignRequest({message:W,chain:s}),j=tr(u,I,C,x);Object.entries(j).forEach(([M,y])=>f.set(M,y))}Object.entries(i.destination.headers||{}).forEach(([u,W])=>{f.set(u,W)});let w=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,m(u)])),S=i.destination.method||"GET",g=S==="GET"?void 0:JSON.stringify({...w,...a});A.info("Executing collect",{url:i.destination.url,method:S,headers:f,body:g});try{let u=await fetch(i.destination.url,{method:S,headers:f,body:g}),W=await u.json(),{values:C,results:x}=await ur(p,W,e,d,this.config.transform?.runner),I=lr(this.config,this.adapters,p,e,x);return{success:u.ok,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:I,values:C,valuesRaw:C.map(j=>this.serializer.stringToNative(j)[1]),results:{...x,_DATA:W},messages:pr(p,x)}}catch(u){return A.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:p,action:e,user:this.config.user?.wallets?.[s.name]||null,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var Q=class{constructor(r){this.config=r}async search(r,e,t){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw A.error("WarpIndex: Error searching for warps: ",a),a}}};var X=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!L(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),s=(await Promise.all(a)).filter(l=>l.match),o=s.length>0,p=s.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:p}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(c.HttpProtocolPrefix)?L(r):P(r);if(!a)return t;try{let{type:i,identifierBase:s}=a,o=null,p=null,l=null,d=E(a.chainPrefix,this.adapters);if(i==="hash"){o=await d.builder().createFromTransactionHash(s,e);let f=await d.registry.getInfoByHash(s,e);p=f.registryInfo,l=f.brand}else if(i==="alias"){let f=await d.registry.getInfoByAlias(s,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let m=o?await new O(this.config,d).apply(this.config,o):null;return m?{match:!0,url:r,warp:m,chain:d.chainInfo.name,registryInfo:p,brand:l}:t}catch(i){return A.error("Error detecting warp link",i),t}}};var mr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new J(this.config,this.adapters,r)}async detectWarp(r,e){return new X(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let i=r.startsWith("http")&&r.endsWith(".json")?await(await fetch(r)).json():(await this.detectWarp(r,a.cache)).warp;if(!i)throw new Error("Warp not found");let s=this.createExecutor(t),{tx:o,chain:p}=await s.execute(i,e);return{tx:o,chain:p,evaluateResults:async d=>{if(!p||!o||!i)throw new Error("Warp not found");await s.evaluateResults(i,p.name,d)}}}createInscriptionTransaction(r,e){return h(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return h(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=P(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return E(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return h(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return h(r,this.adapters).explorer}getResults(r){return h(r,this.adapters).results}async getRegistry(r){let e=h(r,this.adapters).registry;return await e.init(),e}getDataLoader(r){return h(r,this.adapters).dataLoader}get factory(){return new V(this.config,this.adapters)}get index(){return new Q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return h(r,this.adapters).builder()}createAbiBuilder(r){return h(r,this.adapters).abiBuilder()}createBrandBuilder(r){return h(r,this.adapters).brandBuilder()}};export{K as BrowserCryptoProvider,gr as CacheTtl,Z as NodeCryptoProvider,dr as WarpBrandBuilder,fr as WarpBuilder,k as WarpCache,hr as WarpCacheKey,Wr as WarpChainName,mr as WarpClient,b as WarpConfig,c as WarpConstants,J as WarpExecutor,V as WarpFactory,Q as WarpIndex,v as WarpInputTypes,O as WarpInterpolator,N as WarpLinkBuilder,X as WarpLinkDetecter,A as WarpLogger,U as WarpProtocolVersions,T as WarpSerializer,z as WarpTypeRegistryImpl,G as WarpValidator,be as address,pr as applyResultsToMessages,Pe as asset,Ce as biguint,Ie as boolean,Hr as bytesToBase64,yr as bytesToHex,tr as createAuthHeaders,er as createAuthMessage,Or as createCryptoProvider,fe as createHttpAuthHeaders,Sr as createSignableMessage,Ir as evaluateResultsCommon,ur as extractCollectResults,L as extractIdentifierInfoFromUrl,E as findWarpAdapterByPrefix,h as findWarpAdapterForChain,sr as findWarpExecutableAction,nr as getCryptoProvider,q as getLatestProtocolIdentifier,lr as getNextInfo,ee as getProviderConfig,re as getProviderUrl,ar as getRandomBytes,ir as getRandomHex,$ as getWarpActionByIndex,P as getWarpInfoFromIdentifier,Te as hex,Tr as parseResultsOutIndex,he as parseSignedMessage,Y as replacePlaceholders,Nr as setCryptoProvider,_ as shiftBigintBy,ye as string,Vr as testCryptoAvailability,or as toPreviewText,ve as u16,Ae as u32,we as u64,xe as u8,ge as validateSignedMessage};
package/package.json CHANGED
@@ -1,13 +1,21 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.9",
3
+ "version": "3.0.0-alpha.90",
4
4
  "description": "",
5
- "main": "./dist/index.js",
5
+ "type": "module",
6
6
  "types": "./dist/index.d.ts",
7
- "module": "./dist/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
12
+ "default": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "sideEffects": false,
8
16
  "scripts": {
9
- "build": "tsup src/index.ts --dts --format cjs,esm --minify --clean",
10
- "test": "jest --config jest.config.js",
17
+ "build": "tsup",
18
+ "test": "jest --config jest.config.mjs",
11
19
  "lint": "tsc --noEmit",
12
20
  "prepare": "npm run build",
13
21
  "preversion": "npm run lint && npm run build"
@@ -17,26 +25,21 @@
17
25
  "files": [
18
26
  "dist"
19
27
  ],
20
- "peerDependencies": {
21
- "@multiversx/sdk-core": "^14.0.2",
22
- "vm2": "^3.9.17"
23
- },
24
28
  "devDependencies": {
25
- "@multiversx/sdk-core": "^14.2.1",
26
- "@types/jest": "^29.5.14",
27
- "jest": "^30.0.0",
28
- "jest-environment-jsdom": "^30.0.0",
29
+ "@types/jest": "^30.0.0",
30
+ "jest": "^30.0.5",
31
+ "jest-environment-jsdom": "^30.0.5",
29
32
  "jest-fetch-mock": "^3.0.3",
30
- "ts-jest": "^29.4.0",
33
+ "ts-jest": "^29.4.1",
31
34
  "tsup": "^8.5.0",
32
- "typescript": "^5.8.3",
33
- "vm2": "^3.9.19"
35
+ "typescript": "^5.9.2"
34
36
  },
35
37
  "publishConfig": {
36
38
  "access": "public"
37
39
  },
38
40
  "dependencies": {
39
41
  "ajv": "^8.17.1",
42
+ "protobufjs": "^7.5.4",
40
43
  "qr-code-styling": "^1.9.2"
41
44
  }
42
45
  }
@@ -1 +0,0 @@
1
- var d=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});export{d as a};