@vleap/warps 3.0.0-alpha.15 → 3.0.0-alpha.151
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.d.cts +1086 -0
- package/dist/index.d.ts +845 -359
- package/dist/index.js +2 -12
- package/dist/index.mjs +2 -2
- package/package.json +19 -16
- package/dist/chunk-3SAEGOMQ.mjs +0 -1
- package/dist/index.d.mts +0 -600
- package/dist/vm-JCVDACTR.mjs +0 -11
package/dist/index.js
CHANGED
|
@@ -1,12 +1,2 @@
|
|
|
1
|
-
"use strict";var Pt=Object.create;var at=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var kt=(i,t)=>()=>(i&&(t=i(i=0)),t);var wt=(i,t)=>{for(var e in t)at(i,e,{get:t[e],enumerable:!0})},Wt=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ut(t))!Ft.call(i,n)&&n!==e&&at(i,n,{get:()=>t[n],enumerable:!(r=Vt(t,n))||r.enumerable});return i};var ut=(i,t,e)=>(e=i!=null?Pt(Nt(i)):{},Wt(t||!i||!i.__esModule?at(e,"default",{value:i,enumerable:!0}):e,i)),Ot=i=>Wt(at({},"__esModule",{value:!0}),i);var At={};wt(At,{runInVm:()=>ne});var ne,xt=kt(()=>{"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={};wt(ce,{BrandBuilder:()=>gt,CacheKey:()=>S,CacheTtl:()=>Z,WarpAbiBuilder:()=>nt,WarpActionExecutor:()=>ht,WarpArgSerializer:()=>$,WarpBuilder:()=>et,WarpCache:()=>V,WarpConfig:()=>A,WarpConstants:()=>f,WarpContractLoader:()=>it,WarpIndex:()=>yt,WarpInterpolator:()=>F,WarpLink:()=>rt,WarpProtocolVersions:()=>L,WarpRegistry:()=>M,WarpUtils:()=>T,WarpValidator:()=>tt,address:()=>Jt,biguint:()=>zt,boolean:()=>Kt,codemeta:()=>te,composite:()=>Ht,esdt:()=>Zt,getChainExplorerUrl:()=>$t,getLatestProtocolIdentifier:()=>_,getMainChainInfo:()=>x,getWarpActionByIndex:()=>k,hex:()=>Yt,list:()=>Mt,nothing:()=>ee,option:()=>_t,optional:()=>qt,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>U,toPreviewText:()=>lt,toTypedChainInfo:()=>st,token:()=>Xt,u16:()=>Qt,u32:()=>dt,u64:()=>Gt,u8:()=>jt,variadic:()=>Dt});module.exports=Ot(ce);var D=require("@multiversx/sdk-core"),bt=ut(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 L={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},A={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${L.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${L.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",NativeToken:"EGLD"},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 x=i=>({name:A.MainChain.Name,displayName:A.MainChain.DisplayName,chainId:A.MainChain.ChainId(i.env),blockTime:A.MainChain.BlockTime(i.env),addressHrp:A.MainChain.AddressHrp,apiUrl:A.MainChain.ApiUrl(i.env),explorerUrl:A.MainChain.ExplorerUrl(i.env),nativeToken:A.MainChain.NativeToken}),$t=(i,t)=>i.explorerUrl+(t?"/"+t:""),_=i=>{if(i==="warp")return`warp:${L.Warp}`;if(i==="brand")return`brand:${L.Brand}`;if(i==="abi")return`abi:${L.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},k=(i,t)=>i?.actions[t-1],st=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(),nativeToken:i.native_token.toString()}),K=(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)},lt=(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},J=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var j=class j{static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;var Q=require("@multiversx/sdk-core");var X=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 O=class O{get(t){let e=O.cache.get(t);return e?Date.now()>e.expiresAt?(O.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;O.cache.set(t,{value:e,expiresAt:n})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var Y=O;var Z={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,t)=>`warp:${i}:${t}`,WarpAbi:(i,t)=>`warp-abi:${i}:${t}`,LastWarpExecutionInputs:(i,t,e)=>`warp-exec-inputs:${i}:${t}:${e}`,RegistryInfo:(i,t)=>`registry-info:${i}:${t}`,Brand:(i,t)=>`brand:${i}:${t}`,ChainInfo:(i,t)=>`chain:${i}:${t}`,ChainInfos:i=>`chains:${i}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new X:t==="memory"?new Y:typeof window<"u"&&window.localStorage?new X:new Y}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 It=ut(require("qr-code-styling"));var q=require("@multiversx/sdk-core");var Tt=ut(require("ajv"));var tt=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||A.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new Tt.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 et=class{constructor(t){this.pendingWarp={protocol:_("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=x(this.config),r=new q.TransactionsFactoryConfig({chainID:e.chainId}),n=new q.TransferTransactionsFactory({config:r}),a=q.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),o=n.createTransactionForTransfer(a,{receiver:q.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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=x(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 lt(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new tt(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
|
|
12
|
-
`))}};var F=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:x(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 m=require("@multiversx/sdk-core/out");var ft={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"},{name:"native_token",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"},{name:"native_token",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 ot=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}),Ct=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var l=require("@multiversx/sdk-core/out"),_t=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),qt=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),Mt=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)},Dt=i=>l.VariadicValue.fromItems(...i),Ht=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},U=i=>l.StringValue.fromUTF8(i),jt=i=>new l.U8Value(i),Qt=i=>new l.U16Value(i),dt=i=>new l.U32Value(i),Gt=i=>new l.U64Value(i),zt=i=>new l.BigUIntValue(BigInt(i)),Kt=i=>new l.BooleanValue(i),Jt=i=>new l.AddressValue(l.Address.newFromBech32(i)),Xt=i=>new l.TokenIdentifierValue(i),Yt=i=>l.BytesValue.fromHex(i),Zt=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")]),te=i=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),ee=()=>new l.NothingValue;var M=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=m.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?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(r)]:e?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]:[m.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=m.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.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=m.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:[m.BytesValue.fromUTF8(t),m.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.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:[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t),new m.AddressValue(new m.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=m.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:[m.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.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:[m.BytesValue.fromHex(t),m.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=S.RegistryInfo(this.config.env,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:[m.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),d=u?ot(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(this.config.env,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:[m.BytesValue.fromHex(t)]}),o=await a.runQuery(s),[p]=a.parseQueryResponse(o),u=p?ot(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 m.AddressValue(new m.Address(e))]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s);return o.map(ot)}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 m.AddressValue(new m.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(this.config.env);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(st);if(t&&t.ttl){for(let u of p)this.cache.set(S.ChainInfo(this.config.env,u.chain),u,t.ttl);this.cache.set(e,p,t.ttl)}return p}async getChainInfo(t,e){try{let r=S.ChainInfo(this.config.env,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:[m.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),d=u?st(u):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async setChain(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(5e6),arguments:[U(t),U(e.name),U(e.displayName),U(e.chainId),dt(e.blockTime),U(e.addressHrp),U(e.apiUrl),U(e.explorerUrl),U(e.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(5e6),arguments:[U(t)]})}async fetchBrand(t,e){let r=S.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=x(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 m.Address.newFromBech32(this.config.registry?.contract||A.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?Ct(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=x(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(ft);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=x(this.config),e=T.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(ft);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var rt=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 et(this.config),p=new M(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 F.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||A.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return A.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 It.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=A.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 re="https://",T=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(f.IdentifierParamSeparator)){let[n,a]=e.split(f.IdentifierParamSeparator),s=a.split("?")[0];return{type:n,identifier:a,identifierBase:s}}let r=e.split("?")[0];return r.length===64?{type:f.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:f.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let a=e.actions?.[r]?.next||e.next||null;if(!a)return null;if(a.startsWith(re))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 h=J(o,{...e.vars,...n}),W=h?`${s}?${h}`: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(h=>h.includes(`{{${g}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),v=W&&W[1]||"";return{placeholder:h,field:v?v.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return w.map(h=>{let W=o;for(let{regex:E,field:P}of y){let b=P?this.getNestedValue(h,P):h;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(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),a=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new rt(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 x(t);let r=await new M(t).getChainInfo(e.chain,{ttl:Z.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 Q.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new Q.TestnetEntrypoint(t.apiUrl,n,r):new Q.MainnetEntrypoint(t.apiUrl,n,r)}};var gt=class{constructor(t){this.pendingBrand={protocol:_("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=x(this.config),r=new D.TransactionsFactoryConfig({chainID:e.chainId}),n=new D.TransferTransactionsFactory({config:r}),a=D.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(a,{receiver:D.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=x(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||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new bt.default,s=a.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var G=require("@multiversx/sdk-core");var nt=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=x(this.config),r=new G.TransactionsFactoryConfig({chainID:e.chainId}),n=new G.TransferTransactionsFactory({config:r}),a={protocol:_("abi"),content:t},s=G.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(this.config.env,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=x(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 z=require("@multiversx/sdk-core/out");var c=require("@multiversx/sdk-core/out");var vt=new RegExp(`${f.ArgParamsSeparator}(.*)`),$=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(vt,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(vt,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 mt=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),Bt=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 ct(t,o,n,a)}}let u=await i.getAbiForAction(e),d=new z.TransactionEventsParser({abi:u}),w=new z.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 h=mt(B);if(h!==null&&h!==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,z.findEventsByFirstTopic)(r,v),H=d.parseEvents({events:b})[0],N=Object.values(H)[P]||null;s.push(N),o[y]=N&&N.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 ct(t,o,n,a)}},St=async(i,t,e,r)=>{let n=new $,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=mt(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 ct(i,o,e,r)}},Et=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=mt(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 ct(i,a,e,r)}};var ct=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=k(t,e)?.inputs||[],s=new $;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(()=>(xt(),At));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}],Rt=i=>oe.find(t=>t.id===i)||null;var it=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 ht=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 $,this.contractLoader=new it(t),this.cache=new V(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=k(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)),h=null;if(n.type==="transfer")h=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())h=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(!h)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(S.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),y,Z.OneWeek),h}async getTransactionExecutionResults(t,e,r){let n=await F.apply(this.config,t),a=k(n,e),s=this.cache.get(S.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:p}=await Bt(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=k(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 F.apply(this.config,t),o=await this.getAbiForAction(n),{args:p,resolvedInputs:u}=await this.getTxComponentsFromInputs(a,n,r),d=p.map(pt=>this.serializer.stringToTyped(pt)),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}),h=await y.runQuery(B),W=h.returnCode==="ok",v=new I.ArgSerializer,E=o.getEndpoint(h.function),P=h.returnDataParts.map(pt=>Buffer.from(pt)),b=v.buffersToValues(P,E.output),{values:H,results:N}=await St(s,b,e,u),R=T.getNextInfo(this.config,s,e,N);return{success:W,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:H,results:N,messages:this.getPreparedMessages(s,N)}}async executeCollect(t,e,r,n){let a=k(t,e);if(!a)throw new Error("WarpActionExecutor: Action not found");let s=await T.getChainInfoForAction(this.config,a),o=await F.apply(this.config,t),p=await this.getResolvedInputs(s,a,r),u=this.getModifiedInputs(p),d=h=>{if(!h.value)return null;let W=this.serializer.stringToNative(h.value)[1];if(h.input.type==="biguint")return W.toString();if(h.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(([h,W])=>{g.set(h,W)});let w=Object.fromEntries(u.map(h=>[h.input.as||h.input.name,d(h)])),y=a.destination.method||"GET",B=y==="GET"?void 0:JSON.stringify({...w,...n});C.info("Executing collect",{url:a.destination.url,method:y,headers:g,body:B});try{let h=await fetch(a.destination.url,{method:y,headers:g,body:B}),W=await h.json(),{values:v,results:E}=await Et(o,W,e,u),P=T.getNextInfo(this.config,o,e,E);return{success:h.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(h){return C.error("WarpActionExecutor: Error executing collect",h),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:h},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),h=s.filter(R=>R.input.position==="transfer"&&R.value).map(R=>R.value),v=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...h?.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,H=b?this.serializer.stringToTyped(b).valueOf():null,N=H?Buffer.from(H):null;return{destination:d,args:g,value:B,transfers:v,data:N,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=K(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=K(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=Rt(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:K(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=x(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,J(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 nt(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 yt=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 _t=Object.create;var K=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Yt=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var rr=(e,t)=>{for(var r in t)K(e,r,{get:t[r],enumerable:!0})},Pt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zt(t))!tr.call(e,i)&&i!==r&&K(e,i,{get:()=>t[i],enumerable:!(n=Xt(t,i))||n.enumerable});return e};var _=(e,t,r)=>(r=e!=null?_t(Yt(e)):{},Pt(t||!e||!e.__esModule?K(r,"default",{value:e,enumerable:!0}):r,e)),er=e=>Pt(K({},"__esModule",{value:!0}),e);var qr={};rr(qr,{BrowserCryptoProvider:()=>X,CacheTtl:()=>Ct,NodeCryptoProvider:()=>Z,WARP_LANGUAGES:()=>lr,WarpBrandBuilder:()=>xt,WarpBuilder:()=>vt,WarpCache:()=>k,WarpCacheKey:()=>wt,WarpChainName:()=>Et,WarpClient:()=>St,WarpConfig:()=>P,WarpConstants:()=>o,WarpExecutor:()=>z,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>d,WarpInterpolator:()=>b,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>J,WarpLogger:()=>x,WarpProtocolVersions:()=>R,WarpSerializer:()=>A,WarpTypeRegistry:()=>It,WarpValidator:()=>D,address:()=>$r,applyOutputToMessages:()=>dt,asset:()=>At,biguint:()=>Br,bool:()=>Vr,buildNestedPayload:()=>yt,bytesToBase64:()=>sr,bytesToHex:()=>Rt,createAuthHeaders:()=>st,createAuthMessage:()=>at,createCryptoProvider:()=>pr,createHttpAuthHeaders:()=>vr,createSignableMessage:()=>Ut,createWarpI18nText:()=>dr,createWarpIdentifier:()=>rt,evaluateOutputCommon:()=>$t,extractCollectOutput:()=>it,extractIdentifierInfoFromUrl:()=>H,extractQueryStringFromIdentifier:()=>ht,extractQueryStringFromUrl:()=>gt,extractWarpSecrets:()=>cr,findWarpAdapterForChain:()=>h,getCryptoProvider:()=>pt,getEventNameFromWarp:()=>nr,getLatestProtocolIdentifier:()=>L,getNextInfo:()=>Wt,getProviderConfig:()=>yr,getRandomBytes:()=>ct,getRandomHex:()=>lt,getWarpActionByIndex:()=>I,getWarpBrandLogoUrl:()=>ir,getWarpInfoFromIdentifier:()=>T,getWarpPrimaryAction:()=>Y,getWarpWalletAddress:()=>Ot,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>Ft,getWarpWalletMnemonicFromConfig:()=>Ir,getWarpWalletPrivateKey:()=>Ht,getWarpWalletPrivateKeyFromConfig:()=>Sr,hasInputPrefix:()=>hr,hex:()=>Nr,isWarpActionAutoExecute:()=>tt,isWarpI18nText:()=>ur,mergeNestedPayload:()=>nt,option:()=>Ur,parseOutputOutIndex:()=>Nt,parseSignedMessage:()=>wr,replacePlaceholders:()=>V,resolveWarpText:()=>ft,safeWindow:()=>ot,setCryptoProvider:()=>ar,shiftBigintBy:()=>j,splitInput:()=>et,string:()=>Tr,struct:()=>Hr,testCryptoAvailability:()=>or,toPreviewText:()=>ut,tuple:()=>Or,uint16:()=>Pr,uint32:()=>Er,uint64:()=>Rr,uint8:()=>br,validateSignedMessage:()=>Cr,vector:()=>Fr});module.exports=er(qr);var Et=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(Et||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallets?.[e.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:e=>e.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},ot=typeof window<"u"?window:{open:()=>{}};var R={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},P={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:e=>e==="devnet"?"https://devnet.usewarp.to":e==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",o.Source.UserWallet,"hidden"],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 nr=(e,t)=>{let r=e.alerts?.[t];if(!r)return null;let n=o.Alerts.TriggerEventPrefix+o.ArgParamsSeparator;if(!r.trigger.startsWith(n))return null;let i=r.trigger.replace(n,"");return i||null};var ir=(e,t)=>typeof e.logo=="string"?e.logo:e.logo[t?.scheme??"light"];var X=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},Z=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},B=null;function pt(){if(B)return B;if(typeof window<"u"&&window.crypto)return B=new X,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 ar(e){B=e}async function ct(e,t){if(e<=0||!Number.isInteger(e))throw new Error("Size must be a positive integer");return(t||pt()).getRandomBytes(e)}function Rt(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(e.length*2);for(let r=0;r<e.length;r++){let n=e[r];t[r*2]=(n>>>4).toString(16),t[r*2+1]=(n&15).toString(16)}return t.join("")}function sr(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(e).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(e));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function lt(e,t){if(e<=0||e%2!==0)throw new Error("Length must be a positive even number");let r=await ct(e/2,t);return Rt(r)}async function or(){let e={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?e.environment="browser":typeof process<"u"&&process.versions?.node&&(e.environment="nodejs"),await ct(16),e.randomBytes=!0}catch{}return e}function pr(){return pt()}var cr=e=>Object.values(e.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[n,i]=r.split(o.ArgCompositeSeparator);return{key:n,description:i||null}});var h=(e,t)=>{let r=t.find(n=>n.chainInfo.name.toLowerCase()===e.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${e}`);return r},L=e=>{if(e==="warp")return`warp:${R.Warp}`;if(e==="brand")return`brand:${R.Brand}`;if(e==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},I=(e,t)=>e?.actions[t-1],Y=e=>{if(e.actions.length===0)throw new Error(`Warp has no primary action: ${e.meta?.identifier}`);let t=e.actions.find(s=>s.primary===!0);if(t)return{action:t,index:e.actions.indexOf(t)};let r=["transfer","contract","query","collect"],n=e.actions.find(s=>r.includes(s.type));return n?{action:n,index:e.actions.indexOf(n)}:{action:e.actions[0],index:0}},tt=(e,t)=>{if(e.auto===!1)return!1;if(e.type==="link"){if(e.auto===!0)return!0;let{action:r}=Y(t);return e===r}return!0},j=(e,t)=>{let r=e.toString(),[n,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},ut=(e,t=100)=>{if(!e)return"";let r=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},V=(e,t)=>e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>t[n]||""),dt=(e,t)=>{let r=Object.entries(e.messages||{}).map(([n,i])=>[n,V(i,t)]);return Object.fromEntries(r)};var lr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},ft=(e,t)=>{let r=t?.preferences?.locale||"en";if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){if(r in e)return e[r];if("en"in e)return e.en;let n=Object.keys(e);if(n.length>0)return e[n[0]]}return""},ur=e=>typeof e=="object"&&e!==null&&Object.keys(e).length>0,dr=e=>e;var rt=(e,t,r)=>{let n=r.startsWith(o.IdentifierAliasMarker)?r.replace(o.IdentifierAliasMarker,""):r;return t===o.IdentifierType.Alias?o.IdentifierAliasMarker+e+o.IdentifierParamSeparator+n:e+o.IdentifierParamSeparator+t+o.IdentifierParamSeparator+n},T=e=>{let r=decodeURIComponent(e).trim().replace(o.IdentifierAliasMarker,""),n=r.split("?")[0],i=Bt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,p]=i;if(a===o.IdentifierType.Alias||a===o.IdentifierType.Hash){let l=r.includes("?")?p+r.substring(r.indexOf("?")):p;return{chain:s,type:a,identifier:l,identifierBase:p}}}if(i.length===2){let[s,a]=i;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:o.IdentifierChainDefault,type:s,identifier:p,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==o.IdentifierType.Alias&&s!==o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a,l=fr(a,s)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chain:s,type:l,identifier:p,identifierBase:a}}}return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:n}},H=e=>{let t=new URL(e),n=t.searchParams.get(o.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return T(i)},fr=(e,t)=>/^[a-fA-F0-9]+$/.test(e)&&e.length>32,gr=e=>{let t=o.IdentifierParamSeparator,r=e.indexOf(t);return r!==-1?{separator:t,index:r}:null},Bt=e=>{let t=gr(e);if(!t)return[e];let{separator:r,index:n}=t,i=e.substring(0,n),s=e.substring(n+r.length),a=Bt(s);return[i,...a]},gt=e=>{try{let t=new URL(e),r=new URLSearchParams(t.search);return r.delete(o.IdentifierParamName),r.toString()||null}catch{return null}},ht=e=>{let t=e.indexOf("?");if(t===-1||t===e.length-1)return null;let r=e.substring(t+1);return r.length>0?r:null};var et=e=>{let[t,...r]=e.split(/:(.*)/,2);return[t,r[0]||""]},hr=e=>{let t=new Set(Object.values(d));if(!e.includes(o.ArgParamsSeparator))return!1;let r=et(e)[0];return t.has(r)};var Vt=_(require("qr-code-styling"),1);var $=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!H(t):!1}build(t,r,n){let i=this.config.clientUrl||P.DefaultClientUrl(this.config.env),s=h(t,this.adapters),a=r===o.IdentifierType.Alias?n:r+o.IdentifierParamSeparator+n,p=s.chainInfo.name+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return P.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let n=h(r.chain,this.adapters);return n?this.build(n.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,n,i=512,s="white",a="black",p="#23F7DD"){let l=h(t,this.adapters),c=this.build(l.chainInfo.name,r,n);return new Vt.default({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},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(p)}" 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 mr="https://",Wt=(e,t,r,n,i)=>{let s=r.actions?.[n-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(mr))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p){let W=V(a,{...r.vars,...i});return[{identifier:W,url:mt(t,W,e)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=V(p,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:mt(t,y,e)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let m=Array.isArray(i[f])?i[f]:[i[f]];if(m.length===0)return[];let g=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:W,field:v?v.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(W=>{let y=p;for(let{regex:O,field:Q}of g){let F=Q?Wr(W,Q):W;if(F==null)return null;y=y.replace(O,F)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:mt(t,v,e)}}).filter(W=>W!==null)},mt=(e,t,r)=>{let[n,i]=t.split("?"),s=T(n)||{chain:o.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=h(s.chain,e);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let p=new $(r,e).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Wr=(e,t)=>t.split(".").reduce((r,n)=>r?.[n],e);function yt(e,t,r){return e.startsWith(o.Position.Payload)?e.slice(o.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:n}),{}):{[t]:r}}function nt(e,t){if(!e)return{...t};if(!t)return{...e};let r={...e};return Object.keys(t).forEach(n=>{r[n]&&typeof r[n]=="object"&&typeof t[n]=="object"?r[n]=nt(r[n],t[n]):r[n]=t[n]}),r}var yr=(e,t,r,n)=>{let i=e.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:n}};var N=class N{static debug(...t){N.isTestEnv||console.debug(...t)}static info(...t){N.isTestEnv||console.info(...t)}static warn(...t){N.isTestEnv||console.warn(...t)}static error(...t){N.isTestEnv||console.error(...t)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=N;var it=async(e,t,r,n,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(e.output||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Nt(u);if(f!==null&&f!==r){l[c]=null;continue}let[m,...g]=u.split("."),w=(W,y)=>y.reduce((v,O)=>v&&v[O]!==void 0?v[O]:null,W);if(m==="out"||m.startsWith("out[")){let W=g.length===0?t?.data||t:w(t,g);a.push(String(W)),p.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:p},output:await $t(e,l,r,n,i,s)}},$t=async(e,t,r,n,i,s)=>{if(!e.output)return t;let a={...t};return a=Ar(a,e,r,n,i),a=await xr(e,a,s.transform?.runner||null),a},Ar=(e,t,r,n,i)=>{let s={...e},a=I(t,r)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let c=l.split(".")[1],u=a.findIndex(m=>m.as===c||m.name===c),f=u!==-1?n[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},xr=async(e,t,r)=>{if(!e.output)return t;let n={...t},i=Object.entries(e.output).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await r.run(a,n)}catch(p){x.error(`Transform error for output '${s}':`,p),n[s]=null}return n},Nt=e=>{if(e==="out")return 1;let t=e.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};async function Ut(e,t,r,n=5){let i=await lt(64,r),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:e,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function at(e,t,r,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ut(e,i,r,5)}function st(e,t,r,n){return{"X-Signer-Wallet":e,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":n}}async function vr(e,t,r,n){let{message:i,nonce:s,expiresAt:a}=await at(e,r,n),p=await t(i);return st(e,p,s,a)}function Cr(e){let t=new Date(e).getTime();return Date.now()<t}function wr(e){try{let t=JSON.parse(e);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Ot=e=>e?typeof e=="string"?e:e.address:null,S=(e,t)=>Ot(e.user?.wallets?.[t]||null),Ht=e=>e?typeof e=="string"?e:e.privateKey:null,Ft=e=>e?typeof e=="string"?e:e.mnemonic:null,Sr=(e,t)=>Ht(e.user?.wallets?.[t]||null)?.trim()||null,Ir=(e,t)=>Ft(e.user?.wallets?.[t]||null)?.trim()||null;var A=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(n=>typeof n=="string"&&n.includes(o.ArgParamsSeparator))){let n=r.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(p=>p!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(n[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(n=>typeof n=="string"&&n.includes(o.ArgParamsSeparator))){let n=r[0],i=n.indexOf(o.ArgParamsSeparator),s=n.substring(0,i),a=r.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),n=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(n==="null")return[n,null];if(n===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(n===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(n.startsWith(d.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(d.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,m]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${m}`)[1]}}),[n,p]}else{if(n===d.String)return[n,i];if(n===d.Uint8||n===d.Uint16||n===d.Uint32)return[n,Number(i)];if(n===d.Uint64||n===d.Uint128||n===d.Uint256||n===d.Biguint)return[n,BigInt(i||0)];if(n===d.Bool)return[n,i==="true"];if(n===d.Address)return[n,i];if(n===d.Hex)return[n,i];if(n===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[n,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let p=s.stringToNative(i);return[n,p]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[p,l]=this.stringToNative(`${a}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(o.ArgParamsSeparator)){let[r,n]=t.split(o.ArgParamsSeparator);return[r,n]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Tr=e=>new A().nativeToString(d.String,e),br=e=>new A().nativeToString(d.Uint8,e),Pr=e=>new A().nativeToString(d.Uint16,e),Er=e=>new A().nativeToString(d.Uint32,e),Rr=e=>new A().nativeToString(d.Uint64,e),Br=e=>new A().nativeToString(d.Biguint,e),Vr=e=>new A().nativeToString(d.Bool,e),$r=e=>new A().nativeToString(d.Address,e),At=e=>new A().nativeToString(d.Asset,e),Nr=e=>new A().nativeToString(d.Hex,e),Ur=(e,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=e(t),n=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,n),s=r.substring(n+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},Or=(...e)=>new A().nativeToString(d.Tuple,e),Hr=e=>new A().nativeToString(d.Struct,e),Fr=e=>new A().nativeToString(d.Vector,e);var Lt=_(require("ajv"),1);var xt=class{constructor(t){this.pendingBrand={protocol:L("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.ensureValidSchema(n),n}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.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||P.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Lt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var jt=_(require("ajv"),1);var D=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=Y(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!r&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||P.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new jt.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var vt=class{constructor(t){this.config=t;this.pendingWarp={protocol:L("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}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.ensureWarpText(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,r=100){return ut(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let n=await new D(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let n=JSON.parse(r,jr);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,r,n){let i={value:r,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Lr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Dt=new A,Lr=(e,t)=>typeof t=="bigint"?Dt.nativeToString("biguint",t):t,jr=(e,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Dt.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,n){let i=Date.now()+n*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var M=E;var Ct={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(e,t)=>`warp:${e}:${t}`,WarpAbi:(e,t)=>`warp-abi:${e}:${t}`,WarpExecutable:(e,t,r)=>`warp-exec:${e}:${t}:${r}`,RegistryInfo:(e,t)=>`registry-info:${e}:${t}`,Brand:(e,t)=>`brand:${e}:${t}`,Asset:(e,t,r)=>`asset:${e}:${t}:${r}`},k=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new q:t==="memory"?new M:typeof window<"u"&&window.localStorage?new q:new M}set(t,r,n){this.strategy.set(t,r,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var b=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,n={}){let i=this.applyVars(t,r,n);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let n={...r};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,t),n}applyVars(t,r,n={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),m=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=n.queries?.[u]||null||m;w&&a(p,w)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g={...t.vars,...n.envs}?.[u];g&&a(p,g)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let n=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}async applyActionGlobals(t){let r=JSON.stringify(t),n={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,n){if(!t||typeof t!="string")return t;let i={};return r.forEach(s=>{if(!s.value||!s.input.as)return;let a=s.input.as;if(a!==a.toUpperCase())return;let[,p]=n.stringToNative(s.value);i[a]=String(p)}),V(t,i)}};var U=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new A,this.cache=new k(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,n,i={}){if(!I(t,r))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),p=h(a.name,this.adapters),l=new b(this.config,p),c=await l.apply(this.config,t,i),u=I(c,r),f=this.getStringTypedInputs(u,n),m=await this.getResolvedInputs(a.name,u,f),g=this.getModifiedInputs(m),w=g.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,W=this.getDestinationFromAction(u),y=w?this.serializer.stringToNative(w)[1]:W;if(y&&(y=l.applyInputs(y,g,this.serializer)),!y)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(u,g);v=v.map(C=>l.applyInputs(C,g,this.serializer));let O=g.find(C=>C.input.position==="value")?.value||null,Q="value"in u?u.value:null,F=O?.split(o.ArgParamsSeparator)[1]||Q||"0",qt=l.applyInputs(F,g,this.serializer),Mt=BigInt(qt),kt=g.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),zt=[...("transfers"in u?u.transfers:[])||[],...kt||[]].map(C=>{let Kt=l.applyInputs(C,g,this.serializer);return this.serializer.stringToNative(Kt)[1]}),Gt=g.find(C=>C.input.position==="data")?.value,Jt="data"in u?u.data||"":null,Tt=Gt||Jt||null,Qt=Tt?l.applyInputs(Tt,g,this.serializer):null,bt={warp:c,chain:a,action:r,destination:y,args:v,value:Mt,transfers:zt,data:Qt,resolvedInputs:g};return this.cache.set(wt.WarpExecutable(this.config.env,c.meta?.hash||"",r),bt.resolvedInputs,Ct.OneWeek),bt}async getChainInfoForWarp(t,r){if(t.chain)return h(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let n=t.inputs||[];return r.map((i,s)=>{let a=n[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,n){let i=r.inputs||[],s=await Promise.all(n.map(p=>this.preprocessInput(t,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=S(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(t){return t.map((r,n)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=j(a,+s);return{...r,value:`${r.input.type}:${p}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=j(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[n,i]=et(r),s=h(t,this.adapters);if(n==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=j(p,c.decimals);return At({...c,amount:u})}else return r}catch(n){throw x.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let n="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;n.splice(a,0,s)}),n}async tryGetChainFromInputs(t,r){let n=t.actions.find(l=>l.inputs?.some(c=>c.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return h(a,this.adapters).chainInfo}};var z=class{constructor(t,r,n){this.config=t;this.adapters=r;this.handlers=n;this.handlers=n,this.factory=new U(t,r)}async execute(t,r,n={}){let i=[],s=null,a=[];for(let p=1;p<=t.actions.length;p++){let l=I(t,p);if(!tt(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,p,r,n);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,n,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):ot.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,n,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=h(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=h(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!tt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[p],c=p+1,u=await i.output.getActionExecution(t,c,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:n,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let n=S(this.config,t.chain.name),i=I(t.warp,t.action),s=c=>{if(!c.value)return null;let u=this.factory.getSerializer().stringToNative(c.value)[1];if(c.input.type==="biguint")return u.toString();if(c.input.type==="asset"){let{identifier:f,amount:m}=u;return{identifier:f,amount:m.toString()}}else return u},a={};if(t.resolvedInputs.forEach(c=>{let u=c.input.as||c.input.name,f=s(c);if(c.input.position&&c.input.position.startsWith(o.Position.Payload)){let m=yt(c.input.position,u,f);a=nt(a,m)}else a[u]=f}),i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,r);let{values:p,output:l}=await it(t.warp,a,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,r,n,i,s){let a=new b(this.config,h(t.chain.name,this.adapters)),p=new Headers;if(p.set("Content-Type","application/json"),p.set("Accept","application/json"),this.handlers?.onSignRequest){if(!n)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:m,expiresAt:g}=await at(n,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=st(n,w,m,g);Object.entries(W).forEach(([y,v])=>p.set(y,v))}}r.headers&&Object.entries(r.headers).forEach(([f,m])=>{let g=a.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());p.set(f,g)});let l=r.method||"GET",c=l==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());x.debug("WarpExecutor: Executing HTTP collect",{url:u,method:l,headers:p,body:c});try{let f=await fetch(u,{method:l,headers:p,body:c});x.debug("Collect response status",{status:f.status});let m=await f.json();x.debug("Collect response content",{content:m});let{values:g,output:w}=await it(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",g,w,m)}catch(f){return x.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[]},output:{_DATA:f},messages:{}}}}buildCollectResult(t,r,n,i,s,a){let p=Wt(this.config,this.adapters,t.warp,t.action,s);return{status:n,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:a?{...s,_DATA:a}:s,messages:dt(t.warp,s)}}async callHandler(t){if(t)return await t()}};var G=class{constructor(t){this.config=t}async search(t,r,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var J=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!H(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,output:l}}async detect(t,r){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?H(t):T(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=h(i.chain,this.adapters),f=t.startsWith(o.HttpProtocolPrefix)?gt(t):ht(i.identifier);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}p&&p.meta&&(Dr(p,u.chainInfo.name,l,i.identifier),p.meta.query=f);let m=p?await new b(this.config,u).apply(this.config,p):null;return m?{match:!0,url:t,warp:m,chain:u.chainInfo.name,registryInfo:l,brand:c}:n}catch(s){return x.error("Error detecting warp link",s),n}}},Dr=(e,t,r,n)=>{e.meta&&(e.meta.identifier=r?.alias?rt(t,"alias",r.alias):rt(t,"hash",r?.hash??n))};var St=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new z(this.config,this.adapters,t)}async detectWarp(t,r){return new J(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),p=s?t:null;if(!p&&a){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateOutput:async g=>{await l.evaluateOutput(p,g)}}}async createInscriptionTransaction(t,r){return await h(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,n=!1){return h(t,this.adapters).builder().createFromTransaction(r,n)}async createFromTransactionHash(t,r){let n=T(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return h(n.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return h(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,n=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return h(t,this.adapters).explorer}getOutput(t){return h(t,this.adapters).output}async getRegistry(t){let r=h(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return h(t,this.adapters).dataLoader}getWallet(t){return h(t,this.adapters).wallet}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(t){return h(t,this.adapters).builder()}createAbiBuilder(t){return h(t,this.adapters).abiBuilder()}createBrandBuilder(t){return h(t,this.adapters).brandBuilder()}createSerializer(t){return h(t,this.adapters).serializer}resolveText(t){return ft(t,this.config)}};var It=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildNestedPayload,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-3SAEGOMQ.mjs";import{Address as Rt,TransactionsFactoryConfig as qe,TransferTransactionsFactory as De}from"@multiversx/sdk-core";import He 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 L={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},I={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${L.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${L.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",NativeToken:"EGLD"},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 b=s=>({name:I.MainChain.Name,displayName:I.MainChain.DisplayName,chainId:I.MainChain.ChainId(s.env),blockTime:I.MainChain.BlockTime(s.env),addressHrp:I.MainChain.AddressHrp,apiUrl:I.MainChain.ApiUrl(s.env),explorerUrl:I.MainChain.ExplorerUrl(s.env),nativeToken:I.MainChain.NativeToken}),hr=(s,t)=>s.explorerUrl+(t?"/"+t:""),_=s=>{if(s==="warp")return`warp:${L.Warp}`;if(s==="brand")return`brand:${L.Brand}`;if(s==="abi")return`abi:${L.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},k=(s,t)=>s?.actions[t-1],rt=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(),nativeToken:s.native_token.toString()}),j=(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)},It=(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},Q=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var q=class q{static info(...t){q.isTestEnv||console.info(...t)}static warn(...t){q.isTestEnv||console.warn(...t)}static error(...t){q.isTestEnv||console.error(...t)}};q.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=q;import{DevnetEntrypoint as Oe,MainnetEntrypoint as $e,TestnetEntrypoint as Le}from"@multiversx/sdk-core";var H=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 U=class U{get(t){let e=U.cache.get(t);return e?Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;U.cache.set(t,{value:e,expiresAt:n})}forget(t){U.cache.delete(t)}clear(){U.cache.clear()}};U.cache=new Map;var M=U;var G={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,t)=>`warp:${s}:${t}`,WarpAbi:(s,t)=>`warp-abi:${s}:${t}`,LastWarpExecutionInputs:(s,t,e)=>`warp-exec-inputs:${s}:${t}:${e}`,RegistryInfo:(s,t)=>`registry-info:${s}:${t}`,Brand:(s,t)=>`brand:${s}:${t}`,ChainInfo:(s,t)=>`chain:${s}:${t}`,ChainInfos:s=>`chains:${s}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new H:t==="memory"?new M:typeof window<"u"&&window.localStorage?new H:new M}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 ke from"qr-code-styling";import{Address as bt,TransactionsFactoryConfig as le,TransferTransactionsFactory as fe}from"@multiversx/sdk-core";import ue from"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,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||I.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new ue,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 K=class{constructor(t){this.pendingWarp={protocol:_("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=b(this.config),r=new le({chainID:e.chainId}),n=new fe({config:r}),i=bt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=n.createTransactionForTransfer(i,{receiver:bt.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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=b(this.config),a=w.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 y.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 It(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(`
|
|
2
|
-
`))}};var F=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:b(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 w.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 Et,Address as S,AddressValue as ct,BytesValue as v,SmartContractTransactionsFactory as Ue,TransactionsFactoryConfig as Fe}from"@multiversx/sdk-core/out";var nt={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"},{name:"native_token",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"},{name:"native_token",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 J=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}),vt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});import{Address as de,AddressValue as me,BigUIntType as he,BigUIntValue as At,BooleanValue as ye,BytesValue as we,CodeMetadata as We,CodeMetadataValue as Te,CompositeType as Ce,CompositeValue as Ie,Field as it,FieldDefinition as at,List as be,NothingValue as ve,OptionalValue as st,OptionValue as ot,StringValue as Ae,Struct as xe,StructType as Be,TokenIdentifierType as Se,TokenIdentifierValue as xt,U16Value as Ee,U32Value as Re,U64Type as Pe,U64Value as Bt,U8Value as Ve,VariadicValue as Ne}from"@multiversx/sdk-core/out";var Qr=(s,t)=>s?ot.newProvided(s):t?ot.newMissingTyped(t):ot.newMissing(),Gr=(s,t)=>s?new st(s.getType(),s):t?new st(t):st.newMissing(),zr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new be(t,s)},Kr=s=>Ne.fromItems(...s),Jr=s=>{let t=s.map(e=>e.getType());return new Ie(new Ce(...t),s)},N=s=>Ae.fromUTF8(s),Xr=s=>new Ve(s),Yr=s=>new Ee(s),St=s=>new Re(s),Zr=s=>new Bt(s),tn=s=>new At(BigInt(s)),en=s=>new ye(s),rn=s=>new me(de.newFromBech32(s)),nn=s=>new xt(s),an=s=>we.fromHex(s),sn=s=>new xe(new Be("EsdtTokenPayment",[new at("token_identifier","",new Se),new at("token_nonce","",new Pe),new at("amount","",new he)]),[new it(new xt(s.token.identifier),"token_identifier"),new it(new Bt(BigInt(s.token.nonce)),"token_nonce"),new it(new At(BigInt(s.amount)),"amount")]),on=s=>new Te(We.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),cn=()=>new ve;var D=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=S.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?[v.fromHex(t),v.fromUTF8(e),v.fromHex(r)]:e?[v.fromHex(t),v.fromUTF8(e)]:[v.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=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[v.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=S.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:[v.fromUTF8(t),v.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.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:[v.fromHex(t),v.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[v.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[v.fromHex(t),new ct(new S(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=S.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:[v.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.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:[v.fromHex(t),v.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=B.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getInfoByAlias",arguments:[v.fromUTF8(t)]}),c=await a.runQuery(o),[p]=a.parseQueryResponse(c),u=p?J(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(this.config.env,t);if(e){let f=this.cache.get(r);if(f)return y.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[v.fromHex(t)]}),o=await i.runQuery(a),[c]=i.parseQueryResponse(o),p=c?J(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 ct(new S(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a);return o.map(J)}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 ct(new S(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(this.config.env);if(t&&t.ttl){let p=this.cache.get(e);if(p)return y.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(rt);if(t&&t.ttl){for(let p of c)this.cache.set(B.ChainInfo(this.config.env,p.chain),p,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=B.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getChain",arguments:[v.fromUTF8(t)]}),c=await a.runQuery(o),[p]=a.parseQueryResponse(c),u=p?rt(p):null;return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch{return null}}async setChain(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(5e6),arguments:[N(t),N(e.name),N(e.displayName),N(e.chainId),St(e.blockTime),N(e.addressHrp),N(e.apiUrl),N(e.explorerUrl),N(e.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(5e6),arguments:[N(t)]})}async fetchBrand(t,e){let r=B.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=b(this.config),o=w.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 S.newFromBech32(this.config.registry?.contract||I.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?vt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=b(this.config),e=new Fe({chainID:t.chainId}),r=Et.create(nt);return new Ue({config:e,abi:r})}getController(){let t=b(this.config),e=w.getChainEntrypoint(t,this.config.env),r=Et.create(nt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var X=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):w.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:a}=n,o=new K(this.config),c=new D(this.config),p=null,u=null,f=null;if(i==="hash"){p=await o.createFromTransactionHash(a,e);let d=await c.getInfoByHash(a,e);u=d.registryInfo,f=d.brand}else if(i==="alias"){let d=await c.getInfoByAlias(a,e);u=d.registryInfo,f=d.brand,d.registryInfo&&(p=await o.createFromTransactionHash(d.registryInfo.hash,e))}let m=p?await F.apply(this.config,p):null;return m?{match:!0,url:t,warp:m,registryInfo:u,brand:f}:r}catch(i){return y.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||I.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return I.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=w.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 ke({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=I.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 w.getInfoFromPrefixedIdentifier(a)}};var _e="https://",w=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(l.IdentifierParamSeparator)){let[n,i]=e.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}let r=e.split("?")[0];return r.length===64?{type:l.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:l.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(_e))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 g=Q(o,{...e.vars,...n}),h=g?`${a}?${g}`: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 d=c.filter(g=>g.includes(`{{${f}[]`)).map(g=>{let h=g.match(/\[\](\.[^}]+)?}}/),T=h&&h[1]||"";return{placeholder:g,field:T?T.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(g=>{let h=o;for(let{regex:A,field:R}of d){let W=R?this.getNestedValue(g,R):g;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(g=>g!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new X(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 b(t);let r=await new D(t).getChainInfo(e.chain,{ttl:G.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 Oe(t.apiUrl,n,r):e==="testnet"?new Le(t.apiUrl,n,r):new $e(t.apiUrl,n,r)}};var Pt=class{constructor(t){this.pendingBrand={protocol:_("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=b(this.config),r=new qe({chainID:e.chainId}),n=new De({config:r}),i=Rt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:Rt.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=b(this.config),n=w.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return y.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||I.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new He,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};import{Address as Me,TransactionsFactoryConfig as je,TransferTransactionsFactory as Qe}from"@multiversx/sdk-core";var Y=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=b(this.config),r=new je({chainID:e.chainId}),n=new Qe({config:r}),i={protocol:_("abi"),content:t},a=Me.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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=b(this.config),a=w.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 y.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as Tt,Address as Ct,ArgSerializer as or,SmartContractTransactionsFactory as cr,Token as se,TokenComputer as pr,TokenTransfer as oe,TransactionsFactoryConfig as ur,TransferTransactionsFactory as lr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as tr,TransactionEventsParser as er,findEventsByFirstTopic as rr}from"@multiversx/sdk-core/out";import{Address as Ge,AddressType as Vt,AddressValue as Nt,BigUIntType as pt,BigUIntValue as ut,BooleanType as Ut,BooleanValue as Ft,BytesType as kt,BytesValue as Ot,CodeMetadata as ze,CodeMetadataType as $t,CodeMetadataValue as Lt,CompositeType as _t,CompositeValue as qt,Field as lt,FieldDefinition as ft,List as Dt,ListType as Ke,NothingValue as E,OptionalType as Je,OptionalValue as gt,OptionType as Xe,OptionValue as dt,StringType as Ht,StringValue as Mt,Struct as Ye,StructType as jt,Token as Ze,TokenIdentifierType as mt,TokenIdentifierValue as ht,TokenTransfer as Qt,U16Type as Gt,U16Value as zt,U32Type as Kt,U32Value as Jt,U64Type as yt,U64Value as wt,U8Type as Xt,U8Value as Yt,VariadicType as Zt,VariadicValue as te}from"@multiversx/sdk-core/out";var ee=new RegExp(`${l.ArgParamsSeparator}(.*)`),O=class{nativeToString(t,e){return t==="esdt"&&e instanceof Qt?`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(gt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Dt.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(te.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(qt.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(ut.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Yt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(zt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Jt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(wt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Mt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ft.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(ht.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Lt.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 Ht;if(t==="uint8")return new Xt;if(t==="uint16")return new Gt;if(t==="uint32")return new Kt;if(t==="uint64")return new yt;if(t==="biguint")return new pt;if(t==="bool")return new Ut;if(t==="address")return new Vt;if(t==="token")return new mt;if(t==="hex")return new kt;if(t==="codemeta")return new $t;if(t==="esdt"||t==="nft")return new jt("EsdtTokenPayment",[new ft("token_identifier","",new mt),new ft("token_nonce","",new yt),new ft("amount","",new pt)]);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 Qt({token:new Ze({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 E;if(e==="option"){let n=this.stringToTyped(r);return n instanceof E?dt.newMissingTyped(n.getType()):dt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof E?gt.newMissing():new gt(n.getType(),n)}if(e==="list"){let[n,i]=r.split(ee,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Dt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(ee,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new te(new Zt(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 qt(new _t(...c),o)}if(e==="string")return r?Mt.fromUTF8(r):new E;if(e==="uint8")return r?new Yt(Number(r)):new E;if(e==="uint16")return r?new zt(Number(r)):new E;if(e==="uint32")return r?new Jt(Number(r)):new E;if(e==="uint64")return r?new wt(BigInt(r)):new E;if(e==="biguint")return r?new ut(BigInt(r)):new E;if(e==="bool")return r?new Ft(typeof r=="boolean"?r:r==="true"):new E;if(e==="address")return r?new Nt(Ge.newFromBech32(r)):new E;if(e==="token")return r?new ht(r):new E;if(e==="hex")return r?Ot.fromHex(r):new E;if(e==="codemeta")return new Lt(ze.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new Ye(this.nativeToType("esdt"),[new lt(new ht(n[0]),"token_identifier"),new lt(new wt(BigInt(n[1])),"token_nonce"),new lt(new ut(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Xe)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Je)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ke)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Zt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"string";if(t instanceof Xt)return"uint8";if(t instanceof Gt)return"uint16";if(t instanceof Kt)return"uint32";if(t instanceof yt)return"uint64";if(t instanceof pt)return"biguint";if(t instanceof Ut)return"bool";if(t instanceof Vt)return"address";if(t instanceof mt)return"token";if(t instanceof kt)return"hex";if(t instanceof $t)return"codemeta";if(t instanceof jt&&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)},nr=(s,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,s),re=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(d=>d.includes("out")||d.includes("event"))){for(let[d,C]of Object.entries(t.results))o[d]=C;return{values:a,results:await Z(t,o,n,i)}}let p=await s.getAbiForAction(e),u=new er({abi:p}),m=new tr({abi:p}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,C]of Object.entries(t.results)){if(C.startsWith(l.Transform.Prefix))continue;if(C.startsWith("input.")){o[d]=C;continue}let g=Wt(C);if(g!==null&&g!==n){o[d]=null;continue}let[h,T,A]=C.split(".");if(h==="event"){if(!T||isNaN(Number(A)))continue;let R=Number(A),W=rr(r,T),$=u.parseEvents({events:W})[0],P=Object.values($)[R]||null;a.push(P),o[d]=P&&P.valueOf()}else if(h==="out"||h.startsWith("out[")){if(!T)continue;let R=Number(T),W=m.values[R-1]||null;A&&(W=W[A]||null),W&&typeof W=="object"&&(W="toFixed"in W?W.toFixed():W.valueOf()),a.push(W),o[d]=W&&W.valueOf()}else o[d]=C}return{values:a,results:await Z(t,o,n,i)}},ne=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 Z(s,o,e,r)}},ie=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:nr(t,u);n.push(f),i[a]=f}else i[a]=o}return{values:n,results:await Z(s,i,e,r)}};var Z=async(s,t,e,r)=>{if(!s.results)return t;let n={...t};return n=ir(n,s,e,r),n=await ar(s,n),n},ir=(s,t,e,r)=>{let n={...s},i=k(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},ar=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){y.error(`Transform error for result '${n}':`,a),e[n]=null}return e};var sr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ae=s=>sr.find(t=>t.id===s)||null;var tt=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return y.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return y.error("WarpContractLoader: getVerificationInfo error",r),null}}};var ce=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 tt(t),this.cache=new V(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=k(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let i=Ct.newFromBech32(this.config.user.wallet),a=await w.getChainInfoForAction(this.config,n),o=new ur({chainID:a.chainId}),{destination:c,args:p,value:u,transfers:f,data:m,resolvedInputs:d}=await this.getTxComponentsFromInputs(a,n,r,i),C=p.map(h=>this.serializer.stringToTyped(h)),g=null;if(n.type==="transfer")g=new lr({config:o}).createTransactionForTransfer(i,{receiver:c,nativeAmount:u,tokenTransfers:f,data:m?new Uint8Array(m):void 0});else if(n.type==="contract"&&c.isSmartContract())g=new cr({config:o}).createTransactionForExecute(i,{contract:c,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:C,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(!g)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),d,G.OneWeek),g}async getTransactionExecutionResults(t,e,r){let n=await F.apply(this.config,t),i=k(n,e),a=this.cache.get(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:c}=await re(this,n,i,r,e,a),p=w.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=k(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await w.getChainInfoForAction(this.config,n),a=await F.apply(this.config,t),o=await this.getAbiForAction(n),{args:c,resolvedInputs:p}=await this.getTxComponentsFromInputs(i,n,r),u=c.map(et=>this.serializer.stringToTyped(et)),f=w.getChainEntrypoint(i,this.config.env),m=Ct.newFromBech32(n.address),d=f.createSmartContractController(o),C=d.createQuery({contract:m,function:n.func,arguments:u}),g=await d.runQuery(C),h=g.returnCode==="ok",T=new or,A=o.getEndpoint(g.function),R=g.returnDataParts.map(et=>Buffer.from(et)),W=T.buffersToValues(R,A.output),{values:$,results:P}=await ne(a,W,e,p),x=w.getNextInfo(this.config,a,e,P);return{success:h,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:x,values:$,results:P,messages:this.getPreparedMessages(a,P)}}async executeCollect(t,e,r,n){let i=k(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let a=await w.getChainInfoForAction(this.config,i),o=await F.apply(this.config,t),c=await this.getResolvedInputs(a,i,r),p=this.getModifiedInputs(c),u=g=>{if(!g.value)return null;let h=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return h.toString();if(g.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(([g,h])=>{f.set(g,h)});let m=Object.fromEntries(p.map(g=>[g.input.as||g.input.name,u(g)])),d=i.destination.method||"GET",C=d==="GET"?void 0:JSON.stringify({...m,...n});y.info("Executing collect",{url:i.destination.url,method:d,headers:f,body:C});try{let g=await fetch(i.destination.url,{method:d,headers:f,body:C}),h=await g.json(),{values:T,results:A}=await ie(o,h,e,p),R=w.getNextInfo(this.config,o,e,A);return{success:g.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:T,results:{...A,_DATA:h},messages:this.getPreparedMessages(o,A)}}catch(g){return y.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:g},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=Ct.newFromBech32(p),f=this.getPreparedArgs(e,a),m=a.find(x=>x.input.position==="value")?.value||null,d="value"in e?e.value:null,C=BigInt(m?.split(":")[1]||d||0),g=a.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),T=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...g?.map(x=>this.serializer.stringToNative(x)[1])||[]],A=a.find(x=>x.input.position==="data")?.value,R="data"in e?e.data||"":null,W=A||R||null,$=W?this.serializer.stringToTyped(W).valueOf():null,P=$?Buffer.from($):null;return{destination:u,args:f,value:C,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=j(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=j(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 se({identifier:i,nonce:BigInt(a)});if(!new pr().isFungible(p))return e;let m=ae(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 d=new oe({token:p,amount:j(o,m)});return this.serializer.nativeToString(r,d)+l.ArgCompositeSeparator+m}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=b(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return Tt.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,Q(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 Y(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 Tt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return Tt.create(r)}}toTypedTransfer(t){return new oe({token:new se({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var pe=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 y.error("WarpIndex: Error searching for warps: ",n),n}}};export{Pt as BrandBuilder,B as CacheKey,G as CacheTtl,Y as WarpAbiBuilder,ce as WarpActionExecutor,O as WarpArgSerializer,K as WarpBuilder,V as WarpCache,I as WarpConfig,l as WarpConstants,tt as WarpContractLoader,pe as WarpIndex,F as WarpInterpolator,X as WarpLink,L as WarpProtocolVersions,D as WarpRegistry,w as WarpUtils,z as WarpValidator,rn as address,tn as biguint,en as boolean,on as codemeta,Jr as composite,sn as esdt,hr as getChainExplorerUrl,_ as getLatestProtocolIdentifier,b as getMainChainInfo,k as getWarpActionByIndex,an as hex,zr as list,cn as nothing,Qr as option,Gr as optional,Q as replacePlaceholders,j as shiftBigintBy,N as string,It as toPreviewText,rt as toTypedChainInfo,nn as token,Yr as u16,St as u32,Zr as u64,Xr as u8,Kr as variadic};
|
|
1
|
+
var Ot=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(Ot||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},pt=typeof window<"u"?window:{open:()=>{}};var $={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},E={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",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",p.Source.UserWallet,"hidden"],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 pr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var lr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var K=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},_=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},R=null;function ct(){if(R)return R;if(typeof window<"u"&&window.crypto)return R=new K,R;if(typeof process<"u"&&process.versions?.node)return R=new _,R;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function dr(n){R=n}async function lt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ct()).getRandomBytes(n)}function Ht(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function fr(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 t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function ut(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await lt(n/2,t);return Ht(r)}async function gr(){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 lt(16),n.randomBytes=!0}catch{}return n}function hr(){return ct()}var yr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},q=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}`)},I=(n,t)=>n?.actions[t-1],X=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},Z=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=X(t);return n===r}return!0},M=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},dt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},N=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),ft=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,N(i,t)]);return Object.fromEntries(r)};var Cr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},gt=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},wr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Sr=n=>n;var Y=(n,t,r)=>{let e=r.startsWith(p.IdentifierAliasMarker)?r.replace(p.IdentifierAliasMarker,""):r;return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},T=n=>{let r=decodeURIComponent(n).trim().replace(p.IdentifierAliasMarker,""),e=r.split("?")[0],i=ht(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let l=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:l,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,l=Ft(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:l,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},F=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return T(i)},Ft=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Lt=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},ht=n=>{let t=Lt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=ht(s);return[i,...a]},mt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},Wt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var tt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Er=n=>{let t=new Set(Object.values(d));if(!n.includes(p.ArgParamsSeparator))return!1;let r=tt(n)[0];return t.has(r)};import jt from"qr-code-styling";var U=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!F(t):!1}build(t,r,e){let i=this.config.clientUrl||E.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,l=encodeURIComponent(o);return E.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${p.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let l=m(t,this.adapters),c=this.build(l.chainInfo.name,r,e);return new jt({type:"svg",width:i,height:i,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},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(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 Dt="https://",yt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Dt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let W=N(a,{...r.vars,...i});return[{identifier:W,url:rt(t,W,n)}]}let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=N(o,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:rt(t,y,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let h=Array.isArray(i[f])?i[f]:[i[f]];if(h.length===0)return[];let g=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),x=y&&y[1]||"";return{placeholder:W,field:x?x.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(W=>{let y=o;for(let{regex:V,field:D}of g){let H=D?qt(W,D):W;if(H==null)return null;y=y.replace(V,H)}if(y.includes("{{")||y.includes("}}"))return null;let x=y?`${a}?${y}`:a;return{identifier:x,url:rt(t,x,n)}}).filter(W=>W!==null)},rt=(n,t,r)=>{let[e,i]=t.split("?"),s=T(e)||{chain:p.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new U(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let l=new URL(o);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},qt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function At(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function et(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=et(r[e],t[e]):r[e]=t[e]}),r}var kr=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var B=class B{static debug(...t){B.isTestEnv||console.debug(...t)}static info(...t){B.isTestEnv||console.info(...t)}static warn(...t){B.isTestEnv||console.warn(...t)}static error(...t){B.isTestEnv||console.error(...t)}};B.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=B;var nt=async(n,t,r,e,i,s)=>{let a=[],o=[],l={};for(let[c,u]of Object.entries(n.output||{})){if(u.startsWith(p.Transform.Prefix))continue;let f=Gt(u);if(f!==null&&f!==r){l[c]=null;continue}let[h,...g]=u.split("."),w=(W,y)=>y.reduce((x,V)=>x&&x[V]!==void 0?x[V]:null,W);if(h==="out"||h.startsWith("out[")){let W=g.length===0?t?.data||t:w(t,g);a.push(String(W)),o.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:o},output:await Mt(n,l,r,e,i,s)}},Mt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=kt(a,n,r,e,i),a=await zt(n,a,s.transform?.runner||null),a},kt=(n,t,r,e,i)=>{let s={...n},a=I(t,r)?.inputs||[];for(let[o,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let c=l.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},zt=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){C.error(`Transform error for output '${s}':`,o),e[s]=null}return e},Gt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Jt(n,t,r,e=5){let i=await ut(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function it(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Jt(n,i,r,5)}function at(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Yr(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await it(n,r,e),o=await t(i);return at(n,o,s,a)}function te(n){let t=new Date(n).getTime();return Date.now()<t}function re(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Qt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Qt(n.user?.wallets?.[t]||null),Kt=n=>n?typeof n=="string"?n:n.privateKey:null,_t=n=>n?typeof n=="string"?n:n.mnemonic:null,ne=(n,t)=>Kt(n.user?.wallets?.[t]||null)?.trim()||null,ie=(n,t)=>_t(n.user?.wallets?.[t]||null)?.trim()||null;var A=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[l,c]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${l})${c}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(l=>{let c=l.indexOf(p.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[d.Option+p.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),l=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(l):[]).map(f=>this.stringToNative(a+p.ArgParamsSeparator+f)[1]);return[d.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${p.IdentifierParamSeparator}${l}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(p.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,h]=c;o[u]=this.stringToNative(`${f}${p.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var le=n=>new A().nativeToString(d.String,n),ue=n=>new A().nativeToString(d.Uint8,n),de=n=>new A().nativeToString(d.Uint16,n),fe=n=>new A().nativeToString(d.Uint32,n),ge=n=>new A().nativeToString(d.Uint64,n),he=n=>new A().nativeToString(d.Biguint,n),me=n=>new A().nativeToString(d.Bool,n),We=n=>new A().nativeToString(d.Address,n),xt=n=>new A().nativeToString(d.Asset,n),ye=n=>new A().nativeToString(d.Hex,n),Ae=(n,t)=>{if(t===null)return d.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},xe=(...n)=>new A().nativeToString(d.Tuple,n),ve=n=>new A().nativeToString(d.Struct,n),Ce=n=>new A().nativeToString(d.Vector,n);import Xt from"ajv";var vt=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||E.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Xt,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import Zt from"ajv";var k=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=X(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||E.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Zt({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var Ct=class{constructor(t){this.config=t;this.pendingWarp={protocol:q("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}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.ensureWarpText(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,r=100){return dt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new k(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
+
`))}};var L=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,tr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Yt))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},wt=new A,Yt=(n,t)=>typeof t=="bigint"?wt.nativeToString("biguint",t):t,tr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?wt.stringToNative(t)[1]:t;var b=class b{get(t){let r=b.cache.get(t);return r?Date.now()>r.expiresAt?(b.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:i})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var j=b;var St={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},z=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new L:t==="memory"?new j:typeof window<"u"&&window.localStorage?new L:new j}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var P=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(o,l)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([o,l])=>{if(typeof l!="string")a(o,l);else if(l.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let c=l.slice(p.Vars.Query.length+1),[u,f]=c.split(p.ArgCompositeSeparator),h=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=e.queries?.[u]||null||h;w&&a(o,w)}else if(l.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=l.slice(p.Vars.Env.length+1),[u,f]=c.split(p.ArgCompositeSeparator),g={...t.vars,...e.envs}?.[u];g&&a(o,g)}else l===p.Source.UserWallet&&i?a(o,i):a(o,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e){if(!t||typeof t!="string")return t;let i={};return r.forEach(s=>{if(!s.value||!s.input.as)return;let a=s.input.as;if(a!==a.toUpperCase())return;let[,o]=e.stringToNative(s.value);i[a]=String(o)}),N(t,i)}};var O=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new A,this.cache=new z(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){if(!I(t,r))throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),l=new P(this.config,o),c=await l.apply(this.config,t,i),u=I(c,r),f=this.getStringTypedInputs(u,e),h=await this.getResolvedInputs(a.name,u,f),g=this.getModifiedInputs(h),w=g.find(v=>v.input.position==="receiver"||v.input.position==="destination")?.value,W=this.getDestinationFromAction(u),y=w?this.serializer.stringToNative(w)[1]:W;if(y&&(y=l.applyInputs(y,g,this.serializer)),!y)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let x=this.getPreparedArgs(u,g);x=x.map(v=>l.applyInputs(v,g,this.serializer));let V=g.find(v=>v.input.position==="value")?.value||null,D="value"in u?u.value:null,H=V?.split(p.ArgParamsSeparator)[1]||D||"0",Pt=l.applyInputs(H,g,this.serializer),Et=BigInt(Pt),Rt=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Bt=[...("transfers"in u?u.transfers:[])||[],...Rt||[]].map(v=>{let Ut=l.applyInputs(v,g,this.serializer);return this.serializer.stringToNative(Ut)[1]}),Vt=g.find(v=>v.input.position==="data")?.value,$t="data"in u?u.data||"":null,st=Vt||$t||null,Nt=st?l.applyInputs(st,g,this.serializer):null,ot={warp:c,chain:a,action:r,destination:y,args:x,value:Et,transfers:Bt,data:Nt,resolvedInputs:g};return this.cache.set(It.WarpExecutable(this.config.env,c.meta?.hash||"",r),ot.resolvedInputs,St.OneWeek),ot}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e){let i=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),a=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else if(o.source===p.Source.UserWallet){let c=S(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[l]||null};return i.map((o,l)=>{let c=a(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=tt(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,l]=i.split(p.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(o,c.decimals);return xt({...c,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.actions.find(l=>l.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var G=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new O(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[];for(let o=1;o<=t.actions.length;o++){let l=I(t,o);if(!Z(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,o,r,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let o=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(o))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,e,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):pt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!Z(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[o],c=o+1,u=await i.output.getActionExecution(t,c,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=I(t.warp,t.action),s=c=>{if(!c.value)return null;let u=this.factory.getSerializer().stringToNative(c.value)[1];if(c.input.type==="biguint")return u.toString();if(c.input.type==="asset"){let{identifier:f,amount:h}=u;return{identifier:f,amount:h.toString()}}else return u},a={};if(t.resolvedInputs.forEach(c=>{let u=c.input.as||c.input.name,f=s(c);if(c.input.position&&c.input.position.startsWith(p.Position.Payload)){let h=At(c.input.position,u,f);a=et(a,h)}else a[u]=f}),i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:l}=await nt(t.warp,a,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,e,"unhandled",o,l)}async doHttpRequest(t,r,e,i,s){let a=new P(this.config,m(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:h,expiresAt:g}=await it(e,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=at(e,w,h,g);Object.entries(W).forEach(([y,x])=>o.set(y,x))}}r.headers&&Object.entries(r.headers).forEach(([f,h])=>{let g=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(f,g)});let l=r.method||"GET",c=l==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:l,headers:o,body:c});try{let f=await fetch(u,{method:l,headers:o,body:c});C.debug("Collect response status",{status:f.status});let h=await f.json();C.debug("Collect response content",{content:h});let{values:g,output:w}=await nt(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",g,w,h)}catch(f){return C.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},output:{_DATA:f},messages:{}}}}buildCollectResult(t,r,e,i,s,a){let o=yt(this.config,this.adapters,t.warp,t.action,s);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:ft(t.warp,s)}}async callHandler(t){if(t)return await t()}};var J=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var Q=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!F(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?F(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,l=null,c=null,u=m(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?mt(t):Wt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}o&&o.meta&&(rr(o,u.chainInfo.name,l,i.identifier),o.meta.query=f);let h=o?await new P(this.config,u).apply(this.config,o):null;return h?{match:!0,url:t,warp:h,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return C.error("Error detecting warp link",s),e}}},rr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?Y(t,"alias",r.alias):Y(t,"hash",r?.hash??e))};var Tt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new G(this.config,this.adapters,t)}async detectWarp(t,r){return new Q(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await g.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateOutput:async g=>{await l.evaluateOutput(o,g)}}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=T(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new O(this.config,this.adapters)}get index(){return new J(this.config)}get linkBuilder(){return new U(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return gt(t,this.config)}};var bt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{K as BrowserCryptoProvider,St as CacheTtl,_ as NodeCryptoProvider,Cr as WARP_LANGUAGES,vt as WarpBrandBuilder,Ct as WarpBuilder,z as WarpCache,It as WarpCacheKey,Ot as WarpChainName,Tt as WarpClient,E as WarpConfig,p as WarpConstants,G as WarpExecutor,O as WarpFactory,J as WarpIndex,d as WarpInputTypes,P as WarpInterpolator,U as WarpLinkBuilder,Q as WarpLinkDetecter,C as WarpLogger,$ as WarpProtocolVersions,A as WarpSerializer,bt as WarpTypeRegistry,k as WarpValidator,We as address,ft as applyOutputToMessages,xt as asset,he as biguint,me as bool,At as buildNestedPayload,fr as bytesToBase64,Ht as bytesToHex,at as createAuthHeaders,it as createAuthMessage,hr as createCryptoProvider,Yr as createHttpAuthHeaders,Jt as createSignableMessage,Sr as createWarpI18nText,Y as createWarpIdentifier,Mt as evaluateOutputCommon,nt as extractCollectOutput,F as extractIdentifierInfoFromUrl,Wt as extractQueryStringFromIdentifier,mt as extractQueryStringFromUrl,yr as extractWarpSecrets,m as findWarpAdapterForChain,ct as getCryptoProvider,pr as getEventNameFromWarp,q as getLatestProtocolIdentifier,yt as getNextInfo,kr as getProviderConfig,lt as getRandomBytes,ut as getRandomHex,I as getWarpActionByIndex,lr as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,X as getWarpPrimaryAction,Qt as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,_t as getWarpWalletMnemonic,ie as getWarpWalletMnemonicFromConfig,Kt as getWarpWalletPrivateKey,ne as getWarpWalletPrivateKeyFromConfig,Er as hasInputPrefix,ye as hex,Z as isWarpActionAutoExecute,wr as isWarpI18nText,et as mergeNestedPayload,Ae as option,Gt as parseOutputOutIndex,re as parseSignedMessage,N as replacePlaceholders,gt as resolveWarpText,pt as safeWindow,dr as setCryptoProvider,M as shiftBigintBy,tt as splitInput,le as string,ve as struct,gr as testCryptoAvailability,dt as toPreviewText,xe as tuple,de as uint16,fe as uint32,ge as uint64,ue as uint8,te as validateSignedMessage,Ce as vector};
|