@vleap/warps 2.3.0-alpha.3 → 2.3.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3SAEGOMQ.mjs +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +12 -12
- package/dist/index.mjs +2 -12
- package/dist/vm-JCVDACTR.mjs +11 -0
- package/package.json +5 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});export{d as a};
|
package/dist/index.d.mts
CHANGED
|
@@ -13,6 +13,7 @@ declare const CacheTtl: {
|
|
|
13
13
|
declare const CacheKey: {
|
|
14
14
|
Warp: (id: string) => string;
|
|
15
15
|
WarpAbi: (id: string) => string;
|
|
16
|
+
LastWarpExecutionInputs: (id: string, action: number) => string;
|
|
16
17
|
RegistryInfo: (id: string) => string;
|
|
17
18
|
Brand: (hash: string) => string;
|
|
18
19
|
ChainInfo: (chain: WarpChain) => string;
|
|
@@ -433,6 +434,7 @@ declare class WarpActionExecutor {
|
|
|
433
434
|
private url;
|
|
434
435
|
private serializer;
|
|
435
436
|
private contractLoader;
|
|
437
|
+
private cache;
|
|
436
438
|
constructor(config: WarpConfig);
|
|
437
439
|
createTransactionForExecute(warp: Warp, actionIndex: number, inputs: string[]): Promise<Transaction>;
|
|
438
440
|
getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecution>;
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ declare const CacheTtl: {
|
|
|
13
13
|
declare const CacheKey: {
|
|
14
14
|
Warp: (id: string) => string;
|
|
15
15
|
WarpAbi: (id: string) => string;
|
|
16
|
+
LastWarpExecutionInputs: (id: string, action: number) => string;
|
|
16
17
|
RegistryInfo: (id: string) => string;
|
|
17
18
|
Brand: (hash: string) => string;
|
|
18
19
|
ChainInfo: (chain: WarpChain) => string;
|
|
@@ -433,6 +434,7 @@ declare class WarpActionExecutor {
|
|
|
433
434
|
private url;
|
|
434
435
|
private serializer;
|
|
435
436
|
private contractLoader;
|
|
437
|
+
private cache;
|
|
436
438
|
constructor(config: WarpConfig);
|
|
437
439
|
createTransactionForExecute(warp: Warp, actionIndex: number, inputs: string[]): Promise<Transaction>;
|
|
438
440
|
getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecution>;
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var At=Object.create;var rt=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var Pt=(a,t)=>{for(var e in t)rt(a,e,{get:t[e],enumerable:!0})},mt=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bt(t))!Et.call(a,n)&&n!==e&&rt(a,n,{get:()=>t[n],enumerable:!(r=xt(t,n))||r.enumerable});return a};var st=(a,t,e)=>(e=a!=null?At(St(a)):{},mt(t||!a||!a.__esModule?rt(e,"default",{value:a,enumerable:!0}):e,a)),Rt=a=>mt(rt({},"__esModule",{value:!0}),a);var re={};Pt(re,{BrandBuilder:()=>pt,CacheKey:()=>P,CacheTtl:()=>ct,Config:()=>A,WarpAbiBuilder:()=>tt,WarpActionExecutor:()=>dt,WarpArgSerializer:()=>_,WarpBuilder:()=>Y,WarpCache:()=>V,WarpConstants:()=>f,WarpContractLoader:()=>et,WarpIndex:()=>gt,WarpInterpolator:()=>U,WarpLink:()=>Z,WarpProtocolVersions:()=>F,WarpRegistry:()=>$,WarpUtils:()=>y,WarpValidator:()=>X,address:()=>Gt,biguint:()=>jt,boolean:()=>Qt,codemeta:()=>Xt,composite:()=>Lt,esdt:()=>Jt,getChainExplorerUrl:()=>Vt,getLatestProtocolIdentifier:()=>O,getMainChainInfo:()=>v,getWarpActionByIndex:()=>M,hex:()=>Kt,list:()=>kt,nothing:()=>Yt,option:()=>Ft,optional:()=>Ot,replacePlaceholders:()=>z,shiftBigintBy:()=>G,string:()=>_t,toPreviewText:()=>ot,toTypedChainInfo:()=>nt,token:()=>zt,u16:()=>Mt,u32:()=>Ht,u64:()=>Dt,u8:()=>qt,variadic:()=>$t});module.exports=Rt(re);var L=require("@multiversx/sdk-core"),Tt=st(require("ajv"));var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var F={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${F.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${F.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="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:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="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 v=a=>({name:A.MainChain.Name,displayName:A.MainChain.DisplayName,chainId:A.MainChain.ChainId(a.env),blockTime:A.MainChain.BlockTime(a.env),addressHrp:A.MainChain.AddressHrp,apiUrl:A.MainChain.ApiUrl(a.env),explorerUrl:A.MainChain.ExplorerUrl(a.env)}),Vt=(a,t)=>a.explorerUrl+(t?"/"+t:""),O=a=>{if(a==="warp")return`warp:${F.Warp}`;if(a==="brand")return`brand:${F.Brand}`;if(a==="abi")return`abi:${F.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},M=(a,t)=>a?.actions[t-1],nt=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString()}),G=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let c=s.slice(0,-i)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ot=(a,t=100)=>{if(!a)return"";let e=a.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},z=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var D=require("@multiversx/sdk-core");var K=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var N=class N{get(t){let e=N.cache.get(t);return e?Date.now()>e.expiresAt?(N.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;N.cache.set(t,{value:e,expiresAt:n})}forget(t){N.cache.delete(t)}clear(){N.cache.clear()}};N.cache=new Map;var J=N;var ct={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},P={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new K:t==="memory"?new J:typeof window<"u"&&window.localStorage?new K:new J}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 wt=st(require("qr-code-styling"));var k=require("@multiversx/sdk-core");var H=class H{static info(...t){H.isTestEnv||console.info(...t)}static warn(...t){H.isTestEnv||console.warn(...t)}static error(...t){H.isTestEnv||console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var S=H;var ht=st(require("ajv"));var X=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(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(i=>i.type==="contract"),r=t.actions.some(i=>i.type==="query");if(!e&&!r)return[];let n=t.actions.some(i=>i.abi);return t.results&&!n?["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(),i=new ht.default,s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Y=class{constructor(t){this.pendingWarp={protocol:O("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=v(this.config),r=new k.TransactionsFactoryConfig({chainID:e.chainId}),n=new k.TransferTransactionsFactory({config:r}),i=k.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),c=n.createTransactionForTransfer(i,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}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=P.Warp(t);if(e){let c=this.cache.get(r);if(c)return S.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),c}let n=v(this.config),s=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await s.getTransaction(t),u=await this.createFromTransaction(c);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(c){return console.error("WarpBuilder: Error creating from transaction hash",c),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 ot(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new X(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
|
|
2
|
-
`))}};var U=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${f.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=s.split(`${f.Vars.Query}:`)[1],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(c);u&&n(i,u)}else if(s.startsWith(`${f.Vars.Env}:`)){let c=s.split(`${f.Vars.Env}:`)[1],u=t.vars?.[c];u&&n(i,u)}else s===f.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:v(e)};return Object.values(f.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await y.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(f.Globals).forEach(s=>{let c=s.Accessor(i);c!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),c.toString()))}),JSON.parse(n)}};var m=require("@multiversx/sdk-core/out");var ut={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var it=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),yt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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),i=()=>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:i(),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=P.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?it(p):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=P.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return S.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await i.runQuery(s),[u]=i.parseQueryResponse(c),p=u?it(u):null,d=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:d},e.ttl),{registryInfo:p,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(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s);return c.map(it)}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 m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.map(g=>g.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(u.map(g=>this.fetchBrand(g,p)))).filter(g=>g!==null)}catch{return[]}}async getChainInfos(t){let e=P.ChainInfos();if(t&&t.ttl){let p=this.cache.get(e);if(p)return S.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.map(nt);if(t&&t.ttl){for(let p of u)this.cache.set(P.ChainInfo(p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=P.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?nt(p):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async fetchBrand(t,e){let r=P.Brand(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=v(this.config),c=y.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let u=await c.getTransaction(t),p=JSON.parse(u.data.toString());return p.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}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?yt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=v(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(ut);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=v(this.config),e=y.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(ut);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var Z=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(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(n)).filter(p=>p.match),c=s.length>0,u=s.map(p=>({url:p.url,warp:p.warp}));return{match:c,results:u}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,c=new Y(this.config),u=new $(this.config),p=null,d=null,g=null;if(i==="hash"){p=await c.createFromTransactionHash(s,e);let b=await u.getInfoByHash(s,e);d=b.registryInfo,g=b.brand}else if(i==="alias"){let b=await u.getInfoByAlias(s,e);d=b.registryInfo,g=b.brand,b.registryInfo&&(p=await c.createFromTransactionHash(b.registryInfo.hash,e))}let T=p?await U.apply(this.config,p):null;return T?{match:!0,url:t,warp:T,registryInfo:d,brand:g}:r}catch(i){return S.error("Error detecting warp link",i),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=y.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let c=this.build(t,e);return new wt.default({type:"svg",width:r,height:r,data:String(c),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(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),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return y.getInfoFromPrefixedIdentifier(s)}};var Nt="https://",y=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,i]=r.split(f.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(Nt))return[{identifier:null,url:i}];let[s,c]=i.split("?");if(!c)return[{identifier:s,url:this.buildNextUrl(s,t)}];let u=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=z(c,{...e.vars,...n}),w=h?`${s}?${h}`:s;return[{identifier:w,url:this.buildNextUrl(w,t)}]}let p=u[0];if(!p)return[];let d=p.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||n[g]===void 0)return[];let T=Array.isArray(n[g])?n[g]:[n[g]];if(T.length===0)return[];let b=u.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let w=h.match(/\[\](\.[^}]+)?}}/),I=w&&w[1]||"";return{placeholder:h,field:I?I.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return T.map(h=>{let w=c;for(let{regex:C,field:R}of b){let E=R?this.getNestedValue(h,R):h;if(E==null)return null;w=w.replace(C,E)}if(w.includes("{{")||w.includes("}}"))return null;let I=w?`${s}?${w}`:s;return{identifier:I,url:this.buildNextUrl(I,t)}}).filter(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},c=new Z(e).build(i.type,i.identifierBase);if(!n)return c;let u=new URL(c);return new URLSearchParams(n).forEach((p,d)=>u.searchParams.set(d,p)),u.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return v(t);let r=await new $(t).getChainInfo(e.chain,{ttl:ct.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 D.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new D.TestnetEntrypoint(t.apiUrl,n,r):new D.MainnetEntrypoint(t.apiUrl,n,r)}};var pt=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=v(this.config),r=new L.TransactionsFactoryConfig({chainID:e.chainId}),n=new L.TransferTransactionsFactory({config:r}),i=L.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:L.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=v(this.config),n=y.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.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||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new Tt.default,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Ft=(a,t)=>a?l.OptionValue.newProvided(a):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Ot=(a,t)=>a?new l.OptionalValue(a.getType(),a):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),kt=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new l.List(t,a)},$t=a=>l.VariadicValue.fromItems(...a),Lt=a=>{let t=a.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),a)},_t=a=>l.StringValue.fromUTF8(a),qt=a=>new l.U8Value(a),Mt=a=>new l.U16Value(a),Ht=a=>new l.U32Value(a),Dt=a=>new l.U64Value(a),jt=a=>new l.BigUIntValue(BigInt(a)),Qt=a=>new l.BooleanValue(a),Gt=a=>new l.AddressValue(l.Address.newFromBech32(a)),zt=a=>new l.TokenIdentifierValue(a),Kt=a=>l.BytesValue.fromHex(a),Jt=a=>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(a.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(a.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(a.amount)),"amount")]),Xt=a=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Yt=()=>new l.NothingValue;var j=require("@multiversx/sdk-core");var tt=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=v(this.config),r=new j.TransactionsFactoryConfig({chainID:e.chainId}),n=new j.TransferTransactionsFactory({config:r}),i={protocol:O("abi"),content:t},s=j.Address.newFromBech32(this.config.user.wallet),c=JSON.stringify(i),u=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});return u.gasLimit=u.gasLimit+BigInt(2e6),u}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=P.WarpAbi(t);if(e){let c=this.cache.get(r);if(c)return S.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),c}let n=v(this.config),s=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await s.getTransaction(t),u=await this.createFromTransaction(c);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(c){return console.error("WarpAbiBuilder: Error creating from transaction hash",c),null}}};var W=require("@multiversx/sdk-core");var Q=require("@multiversx/sdk-core/out");var o=require("@multiversx/sdk-core/out");var Ct=new RegExp(`${f.ArgParamsSeparator}(.*)`),_=class{nativeToString(t,e){return t==="esdt"&&e instanceof o.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(o.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(o.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(o.List.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),i=r.join(f.ArgCompositeSeparator),s=n.join(f.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(o.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(o.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(o.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 o.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new o.StringType;if(t==="uint8")return new o.U8Type;if(t==="uint16")return new o.U16Type;if(t==="uint32")return new o.U32Type;if(t==="uint64")return new o.U64Type;if(t==="biguint")return new o.BigUIntType;if(t==="bool")return new o.BooleanType;if(t==="address")return new o.AddressType;if(t==="token")return new o.TokenIdentifierType;if(t==="hex")return new o.BytesType;if(t==="codemeta")return new o.CodeMetadataType;if(t==="esdt"||t==="nft")return new o.StructType("EsdtTokenPayment",[new o.FieldDefinition("token_identifier","",new o.TokenIdentifierType),new o.FieldDefinition("token_nonce","",new o.U64Type),new o.FieldDefinition("amount","",new o.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[i,s]=n.split(f.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(f.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${i[p]}:${u}`)[1]);return[r,c]}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,s,c]=n.split(f.ArgCompositeSeparator);return[r,new o.TokenTransfer({token:new o.Token({identifier:i,nonce:BigInt(s)}),amount:BigInt(c)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new o.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionValue.newMissingTyped(n.getType()):o.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionalValue.newMissing():new o.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.VariadicValue(new o.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(f.ArgCompositeSeparator),s=n.split(f.ArgCompositeSeparator),c=i.map((p,d)=>this.stringToTyped(`${s[d]}:${p}`)),u=c.map(p=>p.getType());return new o.CompositeValue(new o.CompositeType(...u),c)}if(e==="string")return r?o.StringValue.fromUTF8(r):new o.NothingValue;if(e==="uint8")return r?new o.U8Value(Number(r)):new o.NothingValue;if(e==="uint16")return r?new o.U16Value(Number(r)):new o.NothingValue;if(e==="uint32")return r?new o.U32Value(Number(r)):new o.NothingValue;if(e==="uint64")return r?new o.U64Value(BigInt(r)):new o.NothingValue;if(e==="biguint")return r?new o.BigUIntValue(BigInt(r)):new o.NothingValue;if(e==="bool")return r?new o.BooleanValue(typeof r=="boolean"?r:r==="true"):new o.NothingValue;if(e==="address")return r?new o.AddressValue(o.Address.newFromBech32(r)):new o.NothingValue;if(e==="token")return r?new o.TokenIdentifierValue(r):new o.NothingValue;if(e==="hex")return r?o.BytesValue.fromHex(r):new o.NothingValue;if(e==="codemeta")return new o.CodeMetadataValue(o.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new o.Struct(this.nativeToType("esdt"),[new o.Field(new o.TokenIdentifierValue(n[0]),"token_identifier"),new o.Field(new o.U64Value(BigInt(n[1])),"token_nonce"),new o.Field(new o.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof o.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.StringType)return"string";if(t instanceof o.U8Type)return"uint8";if(t instanceof o.U16Type)return"uint16";if(t instanceof o.U32Type)return"uint32";if(t instanceof o.U64Type)return"uint64";if(t instanceof o.BigUIntType)return"biguint";if(t instanceof o.BooleanType)return"bool";if(t instanceof o.AddressType)return"address";if(t instanceof o.TokenIdentifierType)return"token";if(t instanceof o.BytesType)return"hex";if(t instanceof o.CodeMetadataType)return"codemeta";if(t instanceof o.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Zt=async(a,t)=>{if(typeof window>"u"){let e;try{e=require("vm2").VM}catch{throw new Error("The 'vm2' package is required for transform execution in Node.js environments. Please install it with 'npm install vm2', or use this library in a browser environment.")}let r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
`],{type:"application/javascript"}),i=URL.createObjectURL(n),s=new Worker(i);s.onmessage=function(c){c.data.error?r(new Error(c.data.error)):e(c.data.result),s.terminate(),URL.revokeObjectURL(i)},s.onerror=function(c){r(new Error(`Error in transform: ${c.message}`)),s.terminate(),URL.revokeObjectURL(i)},s.postMessage(t)}catch(n){return r(n)}})},lt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)},te=(a,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,a),ft=async(a,t)=>{if(!a.results)return t;let e={...t},r=Object.entries(a.results).filter(([,n])=>n.startsWith(f.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(f.Transform.Prefix.length)}));for(let{key:n,code:i}of r)try{e[n]=await Zt(i,e)}catch(s){console.error(`Transform error for result '${n}':`,s),e[n]=null}return e},Wt=async(a,t,e,r,n=1)=>{let i=[],s={};if(!t.results||!e.abi||e.type!=="contract")return{values:i,results:s};let c=await a.getAbiForAction(e),u=new Q.TransactionEventsParser({abi:c}),d=new Q.SmartContractTransactionsOutcomeParser({abi:c}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[g,T]of Object.entries(t.results)){if(T.startsWith(f.Transform.Prefix))continue;let b=lt(T);if(b!==null&&b!==n){s[g]=null;continue}let[B,h,w]=T.split(".");if(B==="event"){if(!h||isNaN(Number(w)))continue;let I=Number(w),C=(0,Q.findEventsByFirstTopic)(r,h),R=u.parseEvents({events:C})[0],E=Object.values(R)[I]||null;i.push(E),s[g]=E&&E.valueOf()}else if(B==="out"||B.startsWith("out[")){if(!h)continue;let I=Number(h),C=d.values[I-1]||null;w&&(C=C[w]||null),C&&typeof C=="object"&&(C="toFixed"in C?C.toFixed():C.valueOf()),i.push(C),s[g]=C&&C.valueOf()}}return{values:i,results:await ft(t,s)}},bt=async(a,t,e=1)=>{let r=new _,n=t.map(u=>r.typedToString(u)),i=t.map(u=>r.typedToNative(u)[1]),s={};if(!a.results)return{values:n,results:s};let c=u=>{let p=u.split(".").slice(1).map(g=>parseInt(g)-1);if(p.length===0)return;let d=i[p[0]];for(let g=1;g<p.length;g++){if(d==null)return;d=d[p[g]]}return d};for(let[u,p]of Object.entries(a.results)){if(p.startsWith(f.Transform.Prefix))continue;let d=lt(p);if(d!==null&&d!==e){s[u]=null;continue}(p.startsWith("out.")||p==="out"||p.startsWith("out["))&&(s[u]=c(p)||null)}return{values:n,results:await ft(a,s)}},It=async(a,t,e=1)=>{let r=[],n={};for(let[i,s]of Object.entries(a.results||{})){if(s.startsWith(f.Transform.Prefix))continue;let c=lt(s);if(c!==null&&c!==e){n[i]=null;continue}let[u,...p]=s.split(".");if(u!=="out"&&!u.startsWith("out["))continue;let d=p.length===0?t?.data||t:te(t,p);r.push(d),n[i]=d}return{values:r,results:await ft(a,n)}};var ee=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],vt=a=>ee.find(t=>t.id===a)||null;var et=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var dt=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 et(t)}async createTransactionForExecute(t,e,r){let n=M(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let i=W.Address.newFromBech32(this.config.user.wallet),s=await y.getChainInfoForAction(this.config,n),c=new W.TransactionsFactoryConfig({chainID:s.chainId}),{destination:u,args:p,value:d,transfers:g,data:T}=await this.getTxComponentsFromInputs(s,n,r,i),b=p.map(B=>this.serializer.stringToTyped(B));if(n.type==="transfer")return new W.TransferTransactionsFactory({config:c}).createTransactionForTransfer(i,{receiver:u,nativeAmount:d,tokenTransfers:g,data:T?new Uint8Array(T):void 0});if(n.type==="contract"&&u.isSmartContract())return new W.SmartContractTransactionsFactory({config:c}).createTransactionForExecute(i,{contract:u,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:b,tokenTransfers:g,nativeTransferAmount:d});throw n.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):n.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${n.type})`)}async getTransactionExecutionResults(t,e,r){let n=M(t,e),i=await U.apply(this.config,t),{values:s,results:c}=await Wt(this,i,n,r,e),u=y.getNextInfo(this.config,i,e,c),p=this.getPreparedMessages(i,c);return{success:r.status.isSuccessful(),warp:i,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:u,values:s,results:c,messages:p}}async executeQuery(t,e,r){let n=M(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await y.getChainInfoForAction(this.config,n),s=await U.apply(this.config,t),c=await this.getAbiForAction(n),{args:u}=await this.getTxComponentsFromInputs(i,n,r),p=u.map(x=>this.serializer.stringToTyped(x)),d=y.getChainEntrypoint(i,this.config.env),g=W.Address.newFromBech32(n.address),T=d.createSmartContractController(c),b=T.createQuery({contract:g,function:n.func,arguments:p}),B=await T.runQuery(b),h=B.returnCode==="ok",w=new W.ArgSerializer,I=c.getEndpoint(B.function),C=B.returnDataParts.map(x=>Buffer.from(x)),R=w.buffersToValues(C,I.output),{values:E,results:q}=await bt(s,R,e),at=y.getNextInfo(this.config,s,e,q);return{success:h,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:at,values:E,results:q,messages:this.getPreparedMessages(s,q)}}async executeCollect(t,e,r,n){let i=M(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await y.getChainInfoForAction(this.config,i),c=await U.apply(this.config,t),u=await this.getResolvedInputs(s,i,r),p=this.getModifiedInputs(u),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 I=w;return{token:I.token.identifier,nonce:I.token.nonce.toString(),amount:I.amount.toString()}}else return w},g=new Headers;g.set("Content-Type","application/json"),g.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([h,w])=>{g.set(h,w)});let T=Object.fromEntries(p.map(h=>[h.input.as||h.input.name,d(h)])),b=i.destination.method||"GET",B=b==="GET"?void 0:JSON.stringify({inputs:T,meta:n});try{let h=await fetch(i.destination.url,{method:b,headers:g,body:B}),w=await h.json(),{values:I,results:C}=await It(c,w,e),R=y.getNextInfo(this.config,c,e,C);return{success:h.ok,warp:c,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:I,results:C,messages:this.getPreparedMessages(c,C)}}catch(h){return console.error(h),{success:!1,warp:c,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let i=await this.getResolvedInputs(t,e,r),s=this.getModifiedInputs(i),c=s.find(x=>x.input.position==="receiver")?.value,u="address"in e?e.address:null,p=c?.split(":")[1]||u||n?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let d=W.Address.newFromBech32(p),g=this.getPreparedArgs(e,s),T=s.find(x=>x.input.position==="value")?.value||null,b="value"in e?e.value:null,B=BigInt(T?.split(":")[1]||b||0),h=s.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),I=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...h?.map(x=>this.serializer.stringToNative(x)[1])||[]],C=s.find(x=>x.input.position==="data")?.value,R="data"in e?e.data||"":null,E=C||R||null,q=E?this.serializer.stringToTyped(E).valueOf():null,at=q?Buffer.from(q):null;return{destination:d,args:g,value:B,transfers:I,data:at}}async getResolvedInputs(t,e,r){let n=e.inputs||[],i=await Promise.all(r.map(c=>this.preprocessInput(t,c))),s=(c,u)=>{if(c.source==="query"){let p=this.url.searchParams.get(c.name);return p?this.serializer.nativeToString(c.type,p):null}else return c.source===f.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:i[u]||null};return n.map((c,u)=>({input:c,value:s(c,u)}))}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(u=>u.input.name===n)?.value?.split(":")[1]);if(!i)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 c=G(s,+i);return{...e,value:`${e.input.type}:${c}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(i,+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[i,s,c,u]=n.split(f.ArgCompositeSeparator);if(u)return e;let p=new W.Token({identifier:i,nonce:BigInt(s)});if(!new W.TokenComputer().isFungible(p))return e;let T=vt(i)?.decimals;if(T||(T=(await(await fetch(`${t.apiUrl}/tokens/${i}`)).json()).decimals),!T)throw new Error(`WarpActionExecutor: Decimals not found for token ${i}`);let b=new W.TokenTransfer({token:p,amount:G(c,T)});return this.serializer.nativeToString(r,b)+f.ArgCompositeSeparator+T}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=v(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return W.AbiRegistry.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 s=Number(n.position.split(":")[1])-1;r.splice(s,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,z(i,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 tt(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 W.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return W.AbiRegistry.create(r)}}toTypedTransfer(t){return new W.TokenTransfer({token:new W.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var gt=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 console.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,CacheTtl,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,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 St=Object.create;var it=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var Ut=(i,t)=>()=>(i&&(t=i(i=0)),t);var mt=(i,t)=>{for(var e in t)it(i,e,{get:t[e],enumerable:!0})},ht=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pt(t))!Vt.call(i,n)&&n!==e&&it(i,n,{get:()=>t[n],enumerable:!(r=Et(t,n))||r.enumerable});return i};var ct=(i,t,e)=>(e=i!=null?St(Rt(i)):{},ht(t||!i||!i.__esModule?it(e,"default",{value:i,enumerable:!0}):e,i)),Nt=i=>ht(it({},"__esModule",{value:!0}),i);var bt={};mt(bt,{runInVm:()=>re});var re,It=Ut(()=>{"use strict";re=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 oe={};mt(oe,{BrandBuilder:()=>lt,CacheKey:()=>E,CacheTtl:()=>Y,Config:()=>B,WarpAbiBuilder:()=>rt,WarpActionExecutor:()=>gt,WarpArgSerializer:()=>$,WarpBuilder:()=>tt,WarpCache:()=>V,WarpConstants:()=>f,WarpContractLoader:()=>nt,WarpIndex:()=>dt,WarpInterpolator:()=>U,WarpLink:()=>et,WarpProtocolVersions:()=>L,WarpRegistry:()=>M,WarpUtils:()=>T,WarpValidator:()=>Z,address:()=>Jt,biguint:()=>zt,boolean:()=>Kt,codemeta:()=>te,composite:()=>Mt,esdt:()=>Zt,getChainExplorerUrl:()=>Ot,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>x,getWarpActionByIndex:()=>F,hex:()=>Yt,list:()=>qt,nothing:()=>ee,option:()=>$t,optional:()=>Lt,replacePlaceholders:()=>K,shiftBigintBy:()=>z,string:()=>Ht,toPreviewText:()=>ut,toTypedChainInfo:()=>at,token:()=>Xt,u16:()=>Dt,u32:()=>Qt,u64:()=>Gt,u8:()=>jt,variadic:()=>_t});module.exports=Nt(oe);var H=require("@multiversx/sdk-core"),Wt=ct(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"},B={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"},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:B.MainChain.Name,displayName:B.MainChain.DisplayName,chainId:B.MainChain.ChainId(i.env),blockTime:B.MainChain.BlockTime(i.env),addressHrp:B.MainChain.AddressHrp,apiUrl:B.MainChain.ApiUrl(i.env),explorerUrl:B.MainChain.ExplorerUrl(i.env)}),Ot=(i,t)=>i.explorerUrl+(t?"/"+t:""),q=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}`)},F=(i,t)=>i?.actions[t-1],at=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString()}),z=(i,t)=>{let e=i.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let s=r+n;if(a>=s.length)return 0n;let o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ut=(i,t=100)=>{if(!i)return"";let e=i.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},K=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var 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 D=require("@multiversx/sdk-core");var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var k=class k{get(t){let e=k.cache.get(t);return e?Date.now()>e.expiresAt?(k.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;k.cache.set(t,{value:e,expiresAt:n})}forget(t){k.cache.delete(t)}clear(){k.cache.clear()}};k.cache=new Map;var X=k;var Y={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},E={Warp:i=>`warp:${i}`,WarpAbi:i=>`warp-abi:${i}`,LastWarpExecutionInputs:(i,t)=>`warp-exec-inputs:${i}:${t}`,RegistryInfo:i=>`registry-info:${i}`,Brand:i=>`brand:${i}`,ChainInfo:i=>`chain:${i}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new X:typeof window<"u"&&window.localStorage?new J:new X}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Tt=ct(require("qr-code-styling"));var _=require("@multiversx/sdk-core");var yt=ct(require("ajv"));var Z=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),r=t.actions.some(s=>s.type==="query");if(!e&&!r)return[];let n=t.actions.some(s=>s.abi),a=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||B.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new yt.default,s=a.compile(n);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var tt=class{constructor(t){this.pendingWarp={protocol:q("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 _.TransactionsFactoryConfig({chainID:e.chainId}),n=new _.TransferTransactionsFactory({config:r}),a=_.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),o=n.createTransactionForTransfer(a,{receiver:_.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=E.Warp(t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=x(this.config),s=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ut(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new Z(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
|
|
12
|
+
`))}};var U=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(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],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);u&&n(a,u)}else if(s.startsWith(`${f.Vars.Env}:`)){let o=s.split(`${f.Vars.Env}:`)[1],u=t.vars?.[o];u&&n(a,u)}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 pt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var st=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),wt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var 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=E.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:a,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(o),[p]=s.parseQueryResponse(u),g=p?st(p):null,d=g?.brand?await this.fetchBrand(g.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:g,brand:d},e.ttl),{registryInfo:g,brand:d}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=E.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return C.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),a=this.getController(),s=a.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),o=await a.runQuery(s),[u]=a.parseQueryResponse(o),p=u?st(u):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}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(st)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s),u=o.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(u.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos();if(t&&t.ttl){let p=this.cache.get(e);if(p)return C.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(a),[o]=n.parseQueryResponse(s),u=o.map(at);if(t&&t.ttl){for(let p of u)this.cache.set(E.ChainInfo(p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=E.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:a,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(o),[p]=s.parseQueryResponse(u),g=p?at(p):null;return e&&e.ttl&&g&&this.cache.set(r,g,e.ttl),g}catch{return null}}async fetchBrand(t,e){let r=E.Brand(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 u=await o.getTransaction(t),p=JSON.parse(u.data.toString());return p.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return m.Address.newFromBech32(this.config.registry?.contract||B.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?wt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=x(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(pt);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(pt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var et=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(f.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(n)).filter(p=>p.match),o=s.length>0,u=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:u}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):T.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:a,identifierBase:s}=n,o=new tt(this.config),u=new M(this.config),p=null,g=null,d=null;if(a==="hash"){p=await o.createFromTransactionHash(s,e);let y=await u.getInfoByHash(s,e);g=y.registryInfo,d=y.brand}else if(a==="alias"){let y=await u.getInfoByAlias(s,e);g=y.registryInfo,d=y.brand,y.registryInfo&&(p=await o.createFromTransactionHash(y.registryInfo.hash,e))}let w=p?await U.apply(this.config,p):null;return w?{match:!0,url:t,warp:w,registryInfo:g,brand:d}:r}catch(a){return C.error("Error detecting warp link",a),r}}build(t,e){let r=this.config.clientUrl||B.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return B.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=T.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",a="black",s="#23F7DD"){let o=this.build(t,e);return new Tt.default({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=B.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 kt="https://",T=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,a]=r.split(f.IdentifierParamSeparator),s=a.split("?")[0];return{type:n,identifier:a,identifierBase:s}}static getNextInfo(t,e,r,n){let a=e.actions?.[r]?.next||e.next||null;if(!a)return null;if(a.startsWith(kt))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o)return[{identifier:s,url:this.buildNextUrl(s,t)}];let u=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=K(o,{...e.vars,...n}),W=h?`${s}?${h}`:s;return[{identifier:W,url:this.buildNextUrl(W,t)}]}let p=u[0];if(!p)return[];let g=p.match(/{{([^[]+)\[\]/),d=g?g[1]:null;if(!d||n[d]===void 0)return[];let w=Array.isArray(n[d])?n[d]:[n[d]];if(w.length===0)return[];let y=u.filter(h=>h.includes(`{{${d}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),A=W&&W[1]||"";return{placeholder:h,field:A?A.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return w.map(h=>{let W=o;for(let{regex:P,field:R}of y){let v=R?this.getNestedValue(h,R):h;if(v==null)return null;W=W.replace(P,v)}if(W.includes("{{")||W.includes("}}"))return null;let A=W?`${s}?${W}`:s;return{identifier:A,url:this.buildNextUrl(A,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 et(e).build(a.type,a.identifierBase);if(!n)return o;let u=new URL(o);return new URLSearchParams(n).forEach((p,g)=>u.searchParams.set(g,p)),u.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:Y.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new D.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new D.TestnetEntrypoint(t.apiUrl,n,r):new D.MainnetEntrypoint(t.apiUrl,n,r)}};var lt=class{constructor(t){this.pendingBrand={protocol:q("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 H.TransactionsFactoryConfig({chainID:e.chainId}),n=new H.TransferTransactionsFactory({config:r}),a=H.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(a,{receiver:H.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||B.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new Wt.default,s=a.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var l=require("@multiversx/sdk-core/out"),$t=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Lt=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),qt=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new l.List(t,i)},_t=i=>l.VariadicValue.fromItems(...i),Mt=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},Ht=i=>l.StringValue.fromUTF8(i),jt=i=>new l.U8Value(i),Dt=i=>new l.U16Value(i),Qt=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 Q=require("@multiversx/sdk-core");var rt=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=x(this.config),r=new Q.TransactionsFactoryConfig({chainID:e.chainId}),n=new Q.TransferTransactionsFactory({config:r}),a={protocol:q("abi"),content:t},s=Q.Address.newFromBech32(this.config.user.wallet),o=JSON.stringify(a),u=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return u.gasLimit=u.gasLimit+BigInt(2e6),u}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=E.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=x(this.config),s=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};var b=require("@multiversx/sdk-core");var G=require("@multiversx/sdk-core/out");var c=require("@multiversx/sdk-core/out");var Ct=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],p=(o?o.split(","):[]).map(g=>this.stringToNative(`${s}:${g}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let a=n.split(f.ArgParamsSeparator),s=a.slice(0,-1).join(f.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(g=>this.stringToNative(`${s}:${g}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),o=n.split(f.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${a[p]}:${u}`)[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(Ct,2),o=a.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new c.List(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(Ct,2),o=a.split(",").map(u=>this.stringToTyped(`${n}:${u}`));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((p,g)=>this.stringToTyped(`${s[g]}:${p}`)),u=o.map(p=>p.getType());return new c.CompositeValue(new c.CompositeType(...u),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 ft=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)},ne=(i,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,i),vt=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,I]of Object.entries(t.results))o[y]=I;return{values:s,results:await ot(t,o,n,a)}}let p=await i.getAbiForAction(e),g=new G.TransactionEventsParser({abi:p}),w=new G.SmartContractTransactionsOutcomeParser({abi:p}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[y,I]of Object.entries(t.results)){if(I.startsWith(f.Transform.Prefix))continue;if(I.startsWith("input.")){o[y]=I;continue}let h=ft(I);if(h!==null&&h!==n){o[y]=null;continue}let[W,A,P]=I.split(".");if(W==="event"){if(!A||isNaN(Number(P)))continue;let R=Number(P),v=(0,G.findEventsByFirstTopic)(r,A),N=g.parseEvents({events:v})[0],O=Object.values(N)[R]||null;s.push(O),o[y]=O&&O.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!A)continue;let R=Number(A),v=w.values[R-1]||null;P&&(v=v[P]||null),v&&typeof v=="object"&&(v="toFixed"in v?v.toFixed():v.valueOf()),s.push(v),o[y]=v&&v.valueOf()}else o[y]=I}return{values:s,results:await ot(t,o,n,a)}},At=async(i,t,e,r)=>{let n=new $,a=t.map(p=>n.typedToString(p)),s=t.map(p=>n.typedToNative(p)[1]),o={};if(!i.results)return{values:a,results:o};let u=p=>{let g=p.split(".").slice(1).map(w=>parseInt(w)-1);if(g.length===0)return;let d=s[g[0]];for(let w=1;w<g.length;w++){if(d==null)return;d=d[g[w]]}return d};for(let[p,g]of Object.entries(i.results)){if(g.startsWith(f.Transform.Prefix))continue;let d=ft(g);if(d!==null&&d!==e){o[p]=null;continue}g.startsWith("out.")||g==="out"||g.startsWith("out[")?o[p]=u(g)||null:o[p]=g}return{values:a,results:await ot(i,o,e,r)}},xt=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 u=ft(o);if(u!==null&&u!==e){a[s]=null;continue}let[p,...g]=o.split(".");if(p==="out"||p.startsWith("out[")){let d=g.length===0?t?.data||t:ne(t,g);n.push(d),a[s]=d}else a[s]=o}return{values:n,results:await ot(i,a,e,r)}};var ot=async(i,t,e,r)=>{if(!i.results)return t;let n={...t};return n=ie(n,i,e,r),n=await ae(i,n),n},ie=(i,t,e,r)=>{let n={...i},a=F(t,e)?.inputs||[],s=new $;for(let[o,u]of Object.entries(n))if(typeof u=="string"&&u.startsWith("input.")){let p=u.split(".")[1],g=a.findIndex(d=>d.as===p||d.name===p);n[o]=g!==-1?s.stringToNative(r[g])[1]:null}return n},ae=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(()=>(It(),bt));e[n]=await s(a,e)}catch(s){C.error(`Transform error for result '${n}':`,s),e[n]=null}return e};var se=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Bt=i=>se.find(t=>t.id===i)||null;var nt=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return C.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return C.error("WarpContractLoader: getVerificationInfo error",r),null}}};var gt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new $,this.contractLoader=new nt(t),this.cache=new V(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=F(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let a=b.Address.newFromBech32(this.config.user.wallet),s=await T.getChainInfoForAction(this.config,n),o=new b.TransactionsFactoryConfig({chainID:s.chainId}),{destination:u,args:p,value:g,transfers:d,data:w}=await this.getTxComponentsFromInputs(s,n,r,a),y=p.map(h=>this.serializer.stringToTyped(h)),I=null;if(n.type==="transfer")I=new b.TransferTransactionsFactory({config:o}).createTransactionForTransfer(a,{receiver:u,nativeAmount:g,tokenTransfers:d,data:w?new Uint8Array(w):void 0});else if(n.type==="contract"&&u.isSmartContract())I=new b.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(a,{contract:u,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:y,tokenTransfers:d,nativeTransferAmount:g});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(!I)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(E.LastWarpExecutionInputs(t.meta?.hash||"",e),r,Y.OneWeek),I}async getTransactionExecutionResults(t,e,r){let n=await U.apply(this.config,t),a=F(n,e),s=this.cache.get(E.LastWarpExecutionInputs(t.meta?.hash||"",e))??[],{values:o,results:u}=await vt(this,n,a,r,e,s),p=T.getNextInfo(this.config,n,e,u),g=this.getPreparedMessages(n,u);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:p,values:o,results:u,messages:g}}async executeQuery(t,e,r){let n=F(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let a=await T.getChainInfoForAction(this.config,n),s=await U.apply(this.config,t),o=await this.getAbiForAction(n),{args:u}=await this.getTxComponentsFromInputs(a,n,r),p=u.map(S=>this.serializer.stringToTyped(S)),g=T.getChainEntrypoint(a,this.config.env),d=b.Address.newFromBech32(n.address),w=g.createSmartContractController(o),y=w.createQuery({contract:d,function:n.func,arguments:p}),I=await w.runQuery(y),h=I.returnCode==="ok",W=new b.ArgSerializer,A=o.getEndpoint(I.function),P=I.returnDataParts.map(S=>Buffer.from(S)),R=W.buffersToValues(P,A.output),{values:v,results:N}=await At(s,R,e,r),O=T.getNextInfo(this.config,s,e,N);return{success:h,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:O,values:v,results:N,messages:this.getPreparedMessages(s,N)}}async executeCollect(t,e,r,n){let a=F(t,e);if(!a)throw new Error("WarpActionExecutor: Action not found");let s=await T.getChainInfoForAction(this.config,a),o=await U.apply(this.config,t),u=await this.getResolvedInputs(s,a,r),p=this.getModifiedInputs(u),g=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 A=W;return{token:A.token.identifier,nonce:A.token.nonce.toString(),amount:A.amount.toString()}}else return W},d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([h,W])=>{d.set(h,W)});let w=Object.fromEntries(p.map(h=>[h.input.as||h.input.name,g(h)])),y=a.destination.method||"GET",I=y==="GET"?void 0:JSON.stringify({inputs:w,meta:n});try{let h=await fetch(a.destination.url,{method:y,headers:d,body:I}),W=await h.json(),{values:A,results:P}=await xt(o,W,e,r),R=T.getNextInfo(this.config,o,e,P);return{success:h.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:A,results:P,messages:this.getPreparedMessages(o,P)}}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:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let a=await this.getResolvedInputs(t,e,r),s=this.getModifiedInputs(a),o=s.find(S=>S.input.position==="receiver")?.value,u="address"in e?e.address:null,p=o?.split(":")[1]||u||n?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=b.Address.newFromBech32(p),d=this.getPreparedArgs(e,s),w=s.find(S=>S.input.position==="value")?.value||null,y="value"in e?e.value:null,I=BigInt(w?.split(":")[1]||y||0),h=s.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),A=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...h?.map(S=>this.serializer.stringToNative(S)[1])||[]],P=s.find(S=>S.input.position==="data")?.value,R="data"in e?e.data||"":null,v=P||R||null,N=v?this.serializer.stringToTyped(v).valueOf():null,O=N?Buffer.from(N):null;return{destination:g,args:d,value:I,transfers:A,data:O}}async getResolvedInputs(t,e,r){let n=e.inputs||[],a=await Promise.all(r.map(o=>this.preprocessInput(t,o))),s=(o,u)=>{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===f.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[u]||null};return n.map((o,u)=>({input:o,value:s(o,u)}))}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(u=>u.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(s,+a);return{...e,value:`${e.input.type}:${o}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let s=z(a,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(f.ArgParamsSeparator,2);if(r==="esdt"){let[a,s,o,u]=n.split(f.ArgCompositeSeparator);if(u)return e;let p=new b.Token({identifier:a,nonce:BigInt(s)});if(!new b.TokenComputer().isFungible(p))return e;let w=Bt(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 b.TokenTransfer({token:p,amount:z(o,w)});return this.serializer.nativeToString(r,y)+f.ArgCompositeSeparator+w}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=x(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return b.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;r.splice(s,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,K(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(f.IdentifierType.Hash)){let e=new rt(this.config),r=t.abi.split(f.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return b.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return b.AbiRegistry.create(r)}}toTypedTransfer(t){return new b.TokenTransfer({token:new b.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var dt=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,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,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});
|
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
`))}};var U=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&n(i,c)}else if(s.startsWith(`${p.Vars.Env}:`)){let o=s.split(`${p.Vars.Env}:`)[1],c=t.vars?.[o];c&&n(i,c)}else s===p.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:C(e)};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await m.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(p.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as It,Address as S,AddressValue as tt,BytesValue as W,SmartContractTransactionsFactory as fe,TransactionsFactoryConfig as de}from"@multiversx/sdk-core/out";var Z={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var G=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),bt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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,s=()=>e&&r?[W.fromHex(t),W.fromUTF8(e),W.fromHex(r)]:e?[W.fromHex(t),W.fromUTF8(e)]:[W.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:s()})}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:[W.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:[W.fromUTF8(t),W.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:[W.fromHex(t),W.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:[W.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:[W.fromHex(t),new tt(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:[W.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:[W.fromHex(t),W.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=E.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?G(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=E.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return A.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[W.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),u=c?G(c):null,l=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:l},e.ttl),{registryInfo:u,brand:l}}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 tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(G)}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 tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos();if(t&&t.ttl){let u=this.cache.get(e);if(u)return A.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),u}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(Y);if(t&&t.ttl){for(let u of c)this.cache.set(E.ChainInfo(u.chain),u,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=E.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?Y(u):null;return e&&e.ttl&&l&&this.cache.set(r,l,e.ttl),l}catch{return null}}async fetchBrand(t,e){let r=E.Brand(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=C(this.config),o=m.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),u=JSON.parse(c.data.toString());return u.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}catch{return null}}getRegistryContractAddress(){return S.newFromBech32(this.config.registry?.contract||b.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?bt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=C(this.config),e=new de({chainID:t.chainId}),r=It.create(Z);return new fe({config:e,abi:r})}getController(){let t=C(this.config),e=m.getChainEntrypoint(t,this.config.env),r=It.create(Z);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var z=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(p.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,c=s.map(u=>({url:u.url,warp:u.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(p.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):m.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,o=new Q(this.config),c=new $(this.config),u=null,l=null,f=null;if(i==="hash"){u=await o.createFromTransactionHash(s,e);let w=await c.getInfoByHash(s,e);l=w.registryInfo,f=w.brand}else if(i==="alias"){let w=await c.getInfoByAlias(s,e);l=w.registryInfo,f=w.brand,w.registryInfo&&(u=await o.createFromTransactionHash(w.registryInfo.hash,e))}let h=u?await U.apply(this.config,u):null;return h?{match:!0,url:t,warp:h,registryInfo:l,brand:f}:r}catch(i){return A.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||b.DefaultClientUrl(this.config.env),n=t===p.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+p.IdentifierParamSeparator+e);return b.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${p.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=m.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new ge({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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=b.SuperClientUrls.includes(e.origin),n=e.searchParams.get(p.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return m.getInfoFromPrefixedIdentifier(s)}};var we="https://",m=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(p.IdentifierParamSeparator)?e:`${p.IdentifierType.Alias}${p.IdentifierParamSeparator}${e}`,[n,i]=r.split(p.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(we))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:this.buildNextUrl(s,t)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let d=D(o,{...e.vars,...n}),g=d?`${s}?${d}`:s;return[{identifier:g,url:this.buildNextUrl(g,t)}]}let u=c[0];if(!u)return[];let l=u.match(/{{([^[]+)\[\]/),f=l?l[1]:null;if(!f||n[f]===void 0)return[];let h=Array.isArray(n[f])?n[f]:[n[f]];if(h.length===0)return[];let w=c.filter(d=>d.includes(`{{${f}[]`)).map(d=>{let g=d.match(/\[\](\.[^}]+)?}}/),T=g&&g[1]||"";return{placeholder:d,field:T?T.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(d=>{let g=o;for(let{regex:y,field:P}of w){let x=P?this.getNestedValue(d,P):d;if(x==null)return null;g=g.replace(y,x)}if(g.includes("{{")||g.includes("}}"))return null;let T=g?`${s}?${g}`:s;return{identifier:T,url:this.buildNextUrl(T,t)}}).filter(d=>d!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new z(e).build(i.type,i.identifierBase);if(!n)return o;let c=new URL(o);return new URLSearchParams(n).forEach((u,l)=>c.searchParams.set(l,u)),c.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return C(t);let r=await new $(t).getChainInfo(e.chain,{ttl:Ct.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new me(t.apiUrl,n,r):e==="testnet"?new ye(t.apiUrl,n,r):new he(t.apiUrl,n,r)}};var At=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=C(this.config),r=new Te({chainID:e.chainId}),n=new Ce({config:r}),i=vt.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:vt.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=C(this.config),n=m.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.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||b.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new We,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as be,AddressValue as Ie,BigUIntType as ve,BigUIntValue as xt,BooleanValue as Ae,BytesValue as xe,CodeMetadata as Be,CodeMetadataValue as Se,CompositeType as Ee,CompositeValue as Pe,Field as et,FieldDefinition as rt,List as Re,NothingValue as Ve,OptionalValue as nt,OptionValue as it,StringValue as Ue,Struct as Ne,StructType as Fe,TokenIdentifierType as Oe,TokenIdentifierValue as Bt,U16Value as ke,U32Value as $e,U64Type as Le,U64Value as St,U8Value as _e,VariadicValue as qe}from"@multiversx/sdk-core/out";var Nn=(a,t)=>a?it.newProvided(a):t?it.newMissingTyped(t):it.newMissing(),Fn=(a,t)=>a?new nt(a.getType(),a):t?new nt(t):nt.newMissing(),On=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Re(t,a)},kn=a=>qe.fromItems(...a),$n=a=>{let t=a.map(e=>e.getType());return new Pe(new Ee(...t),a)},Ln=a=>Ue.fromUTF8(a),_n=a=>new _e(a),qn=a=>new ke(a),Mn=a=>new $e(a),Hn=a=>new St(a),Dn=a=>new xt(BigInt(a)),jn=a=>new Ae(a),Qn=a=>new Ie(be.newFromBech32(a)),Gn=a=>new Bt(a),zn=a=>xe.fromHex(a),Kn=a=>new Ne(new Fe("EsdtTokenPayment",[new rt("token_identifier","",new Oe),new rt("token_nonce","",new Le),new rt("amount","",new ve)]),[new et(new Bt(a.token.identifier),"token_identifier"),new et(new St(BigInt(a.token.nonce)),"token_nonce"),new et(new xt(BigInt(a.amount)),"amount")]),Jn=a=>new Se(Be.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Xn=()=>new Ve;import{Address as Me,TransactionsFactoryConfig as He,TransferTransactionsFactory as De}from"@multiversx/sdk-core";var K=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=C(this.config),r=new He({chainID:e.chainId}),n=new De({config:r}),i={protocol:O("abi"),content:t},s=Me.newFromBech32(this.config.user.wallet),o=JSON.stringify(i),c=n.createTransactionForTransfer(s,{receiver:s,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=E.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return A.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=C(this.config),s=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as yt,Address as wt,ArgSerializer as ir,SmartContractTransactionsFactory as ar,Token as ne,TokenComputer as sr,TokenTransfer as ie,TransactionsFactoryConfig as or,TransferTransactionsFactory as cr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Ye,TransactionEventsParser as Ze,findEventsByFirstTopic as tr}from"@multiversx/sdk-core/out";import{Address as je,AddressType as Et,AddressValue as Pt,BigUIntType as at,BigUIntValue as st,BooleanType as Rt,BooleanValue as Vt,BytesType as Ut,BytesValue as Nt,CodeMetadata as Qe,CodeMetadataType as Ft,CodeMetadataValue as Ot,CompositeType as kt,CompositeValue as $t,Field as ot,FieldDefinition as ct,List as Lt,ListType as Ge,NothingValue as B,OptionalType as ze,OptionalValue as ut,OptionType as Ke,OptionValue as pt,StringType as _t,StringValue as qt,Struct as Je,StructType as Mt,Token as Xe,TokenIdentifierType as lt,TokenIdentifierValue as ft,TokenTransfer as Ht,U16Type as Dt,U16Value as jt,U32Type as Qt,U32Value as Gt,U64Type as dt,U64Value as gt,U8Type as zt,U8Value as Kt,VariadicType as Jt,VariadicValue as Xt}from"@multiversx/sdk-core/out";var Yt=new RegExp(`${p.ArgParamsSeparator}(.*)`),L=class{nativeToString(t,e){return t==="esdt"&&e instanceof Ht?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(pt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(ut.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Lt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Xt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass($t.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[1]),i=r.join(p.ArgCompositeSeparator),s=n.join(p.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(st.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Kt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(jt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Gt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(qt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(ft.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Ot.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 kt(...e.split(p.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new _t;if(t==="uint8")return new zt;if(t==="uint16")return new Dt;if(t==="uint32")return new Qt;if(t==="uint64")return new dt;if(t==="biguint")return new at;if(t==="bool")return new Rt;if(t==="address")return new Et;if(t==="token")return new lt;if(t==="hex")return new Ut;if(t==="codemeta")return new Ft;if(t==="esdt"||t==="nft")return new Mt("EsdtTokenPayment",[new ct("token_identifier","",new lt),new ct("token_nonce","",new dt),new ct("amount","",new at)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(p.ArgParamsSeparator),r=e[0],n=e.slice(1).join(p.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(p.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(p.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`list:${s}`,u]}else if(r==="variadic"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`variadic:${s}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=n.split(p.ArgCompositeSeparator).map((c,u)=>this.stringToNative(`${i[u]}:${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,s,o]=n.split(p.ArgCompositeSeparator);return[r,new Ht({token:new Xe({identifier:i,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 B;if(e==="option"){let n=this.stringToTyped(r);return n instanceof B?pt.newMissingTyped(n.getType()):pt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof B?ut.newMissing():new ut(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Lt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Xt(new Jt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(p.ArgCompositeSeparator),s=n.split(p.ArgCompositeSeparator),o=i.map((u,l)=>this.stringToTyped(`${s[l]}:${u}`)),c=o.map(u=>u.getType());return new $t(new kt(...c),o)}if(e==="string")return r?qt.fromUTF8(r):new B;if(e==="uint8")return r?new Kt(Number(r)):new B;if(e==="uint16")return r?new jt(Number(r)):new B;if(e==="uint32")return r?new Gt(Number(r)):new B;if(e==="uint64")return r?new gt(BigInt(r)):new B;if(e==="biguint")return r?new st(BigInt(r)):new B;if(e==="bool")return r?new Vt(typeof r=="boolean"?r:r==="true"):new B;if(e==="address")return r?new Pt(je.newFromBech32(r)):new B;if(e==="token")return r?new ft(r):new B;if(e==="hex")return r?Nt.fromHex(r):new B;if(e==="codemeta")return new Ot(Qe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(p.ArgCompositeSeparator);return new Je(this.nativeToType("esdt"),[new ot(new ft(n[0]),"token_identifier"),new ot(new gt(BigInt(n[1])),"token_nonce"),new ot(new st(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Ke)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ze)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ge)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Jt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof _t)return"string";if(t instanceof zt)return"uint8";if(t instanceof Dt)return"uint16";if(t instanceof Qt)return"uint32";if(t instanceof dt)return"uint64";if(t instanceof at)return"biguint";if(t instanceof Rt)return"bool";if(t instanceof Et)return"address";if(t instanceof lt)return"token";if(t instanceof Ut)return"hex";if(t instanceof Ft)return"codemeta";if(t instanceof Mt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var er=async(a,t)=>{if(typeof window>"u"){let e;try{e=oe("vm2").VM}catch{throw new Error("The 'vm2' package is required for transform execution in Node.js environments. Please install it with 'npm install vm2', or use this library in a browser environment.")}let r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
|
|
3
|
-
self.onmessage = function(e) {
|
|
4
|
-
try {
|
|
5
|
-
const input = e.data;
|
|
6
|
-
const result = (${a})(input);
|
|
7
|
-
self.postMessage({ result });
|
|
8
|
-
} catch (error) {
|
|
9
|
-
self.postMessage({ error: error.toString() });
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
`],{type:"application/javascript"}),i=URL.createObjectURL(n),s=new Worker(i);s.onmessage=function(o){o.data.error?r(new Error(o.data.error)):e(o.data.result),s.terminate(),URL.revokeObjectURL(i)},s.onerror=function(o){r(new Error(`Error in transform: ${o.message}`)),s.terminate(),URL.revokeObjectURL(i)},s.postMessage(t)}catch(n){return r(n)}})},mt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)},rr=(a,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,a),ht=async(a,t)=>{if(!a.results)return t;let e={...t},r=Object.entries(a.results).filter(([,n])=>n.startsWith(p.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(p.Transform.Prefix.length)}));for(let{key:n,code:i}of r)try{e[n]=await er(i,e)}catch(s){console.error(`Transform error for result '${n}':`,s),e[n]=null}return e},Zt=async(a,t,e,r,n=1)=>{let i=[],s={};if(!t.results||!e.abi||e.type!=="contract")return{values:i,results:s};let o=await a.getAbiForAction(e),c=new Ze({abi:o}),l=new Ye({abi:o}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[f,h]of Object.entries(t.results)){if(h.startsWith(p.Transform.Prefix))continue;let w=mt(h);if(w!==null&&w!==n){s[f]=null;continue}let[v,d,g]=h.split(".");if(v==="event"){if(!d||isNaN(Number(g)))continue;let T=Number(g),y=tr(r,d),P=c.parseEvents({events:y})[0],x=Object.values(P)[T]||null;i.push(x),s[f]=x&&x.valueOf()}else if(v==="out"||v.startsWith("out[")){if(!d)continue;let T=Number(d),y=l.values[T-1]||null;g&&(y=y[g]||null),y&&typeof y=="object"&&(y="toFixed"in y?y.toFixed():y.valueOf()),i.push(y),s[f]=y&&y.valueOf()}}return{values:i,results:await ht(t,s)}},te=async(a,t,e=1)=>{let r=new L,n=t.map(c=>r.typedToString(c)),i=t.map(c=>r.typedToNative(c)[1]),s={};if(!a.results)return{values:n,results:s};let o=c=>{let u=c.split(".").slice(1).map(f=>parseInt(f)-1);if(u.length===0)return;let l=i[u[0]];for(let f=1;f<u.length;f++){if(l==null)return;l=l[u[f]]}return l};for(let[c,u]of Object.entries(a.results)){if(u.startsWith(p.Transform.Prefix))continue;let l=mt(u);if(l!==null&&l!==e){s[c]=null;continue}(u.startsWith("out.")||u==="out"||u.startsWith("out["))&&(s[c]=o(u)||null)}return{values:n,results:await ht(a,s)}},ee=async(a,t,e=1)=>{let r=[],n={};for(let[i,s]of Object.entries(a.results||{})){if(s.startsWith(p.Transform.Prefix))continue;let o=mt(s);if(o!==null&&o!==e){n[i]=null;continue}let[c,...u]=s.split(".");if(c!=="out"&&!c.startsWith("out["))continue;let l=u.length===0?t?.data||t:rr(t,u);r.push(l),n[i]=l}return{values:r,results:await ht(a,n)}};var nr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],re=a=>nr.find(t=>t.id===a)||null;var J=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var ae=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 L,this.contractLoader=new J(t)}async createTransactionForExecute(t,e,r){let n=_(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let i=wt.newFromBech32(this.config.user.wallet),s=await m.getChainInfoForAction(this.config,n),o=new or({chainID:s.chainId}),{destination:c,args:u,value:l,transfers:f,data:h}=await this.getTxComponentsFromInputs(s,n,r,i),w=u.map(v=>this.serializer.stringToTyped(v));if(n.type==="transfer")return new cr({config:o}).createTransactionForTransfer(i,{receiver:c,nativeAmount:l,tokenTransfers:f,data:h?new Uint8Array(h):void 0});if(n.type==="contract"&&c.isSmartContract())return new ar({config:o}).createTransactionForExecute(i,{contract:c,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:w,tokenTransfers:f,nativeTransferAmount:l});throw n.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):n.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${n.type})`)}async getTransactionExecutionResults(t,e,r){let n=_(t,e),i=await U.apply(this.config,t),{values:s,results:o}=await Zt(this,i,n,r,e),c=m.getNextInfo(this.config,i,e,o),u=this.getPreparedMessages(i,o);return{success:r.status.isSuccessful(),warp:i,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:c,values:s,results:o,messages:u}}async executeQuery(t,e,r){let n=_(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await m.getChainInfoForAction(this.config,n),s=await U.apply(this.config,t),o=await this.getAbiForAction(n),{args:c}=await this.getTxComponentsFromInputs(i,n,r),u=c.map(I=>this.serializer.stringToTyped(I)),l=m.getChainEntrypoint(i,this.config.env),f=wt.newFromBech32(n.address),h=l.createSmartContractController(o),w=h.createQuery({contract:f,function:n.func,arguments:u}),v=await h.runQuery(w),d=v.returnCode==="ok",g=new ir,T=o.getEndpoint(v.function),y=v.returnDataParts.map(I=>Buffer.from(I)),P=g.buffersToValues(y,T.output),{values:x,results:N}=await te(s,P,e),X=m.getNextInfo(this.config,s,e,N);return{success:d,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:X,values:x,results:N,messages:this.getPreparedMessages(s,N)}}async executeCollect(t,e,r,n){let i=_(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await m.getChainInfoForAction(this.config,i),o=await U.apply(this.config,t),c=await this.getResolvedInputs(s,i,r),u=this.getModifiedInputs(c),l=d=>{if(!d.value)return null;let g=this.serializer.stringToNative(d.value)[1];if(d.input.type==="biguint")return g.toString();if(d.input.type==="esdt"){let T=g;return{token:T.token.identifier,nonce:T.token.nonce.toString(),amount:T.amount.toString()}}else return g},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,g])=>{f.set(d,g)});let h=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,l(d)])),w=i.destination.method||"GET",v=w==="GET"?void 0:JSON.stringify({inputs:h,meta:n});try{let d=await fetch(i.destination.url,{method:w,headers:f,body:v}),g=await d.json(),{values:T,results:y}=await ee(o,g,e),P=m.getNextInfo(this.config,o,e,y);return{success:d.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:P,values:T,results:y,messages:this.getPreparedMessages(o,y)}}catch(d){return console.error(d),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let i=await this.getResolvedInputs(t,e,r),s=this.getModifiedInputs(i),o=s.find(I=>I.input.position==="receiver")?.value,c="address"in e?e.address:null,u=o?.split(":")[1]||c||n?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=wt.newFromBech32(u),f=this.getPreparedArgs(e,s),h=s.find(I=>I.input.position==="value")?.value||null,w="value"in e?e.value:null,v=BigInt(h?.split(":")[1]||w||0),d=s.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),T=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...d?.map(I=>this.serializer.stringToNative(I)[1])||[]],y=s.find(I=>I.input.position==="data")?.value,P="data"in e?e.data||"":null,x=y||P||null,N=x?this.serializer.stringToTyped(x).valueOf():null,X=N?Buffer.from(N):null;return{destination:l,args:f,value:v,transfers:T,data:X}}async getResolvedInputs(t,e,r){let n=e.inputs||[],i=await Promise.all(r.map(o=>this.preprocessInput(t,o))),s=(o,c)=>{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===p.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:s(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 s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=H(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=H(i,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(p.ArgParamsSeparator,2);if(r==="esdt"){let[i,s,o,c]=n.split(p.ArgCompositeSeparator);if(c)return e;let u=new ne({identifier:i,nonce:BigInt(s)});if(!new sr().isFungible(u))return e;let h=re(i)?.decimals;if(h||(h=(await(await fetch(`${t.apiUrl}/tokens/${i}`)).json()).decimals),!h)throw new Error(`WarpActionExecutor: Decimals not found for token ${i}`);let w=new ie({token:u,amount:H(o,h)});return this.serializer.nativeToString(r,w)+p.ArgCompositeSeparator+h}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=C(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return yt.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 s=Number(n.position.split(":")[1])-1;r.splice(s,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,D(i,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(p.IdentifierType.Hash)){let e=new K(this.config),r=t.abi.split(p.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return yt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return yt.create(r)}}toTypedTransfer(t){return new ie({token:new ne({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var se=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 console.error("WarpIndex: Error searching for warps: ",n),n}}};export{At as BrandBuilder,E as CacheKey,Ct as CacheTtl,b as Config,K as WarpAbiBuilder,ae as WarpActionExecutor,L as WarpArgSerializer,Q as WarpBuilder,V as WarpCache,p as WarpConstants,J as WarpContractLoader,se as WarpIndex,U as WarpInterpolator,z as WarpLink,F as WarpProtocolVersions,$ as WarpRegistry,m as WarpUtils,j as WarpValidator,Qn as address,Dn as biguint,jn as boolean,Jn as codemeta,$n as composite,Kn as esdt,gr as getChainExplorerUrl,O as getLatestProtocolIdentifier,C as getMainChainInfo,_ as getWarpActionByIndex,zn as hex,On as list,Xn as nothing,Nn as option,Fn as optional,D as replacePlaceholders,H as shiftBigintBy,Ln as string,Tt as toPreviewText,Y as toTypedChainInfo,Gn as token,qn as u16,Mn as u32,Hn as u64,_n as u8,kn as variadic};
|
|
1
|
+
import"./chunk-3SAEGOMQ.mjs";import{Address as vt,TransactionsFactoryConfig as we,TransferTransactionsFactory as Te}from"@multiversx/sdk-core";import We from"ajv";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:s=>s.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var $={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},v={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${$.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${$.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:s=>s==="devnet"?"https://devnet-explorer.multiversx.com":s==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:s=>6e3,AddressHrp:"erd",ChainId:s=>s==="devnet"?"D":s==="testnet"?"T":"1"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var b=s=>({name:v.MainChain.Name,displayName:v.MainChain.DisplayName,chainId:v.MainChain.ChainId(s.env),blockTime:v.MainChain.BlockTime(s.env),addressHrp:v.MainChain.AddressHrp,apiUrl:v.MainChain.ApiUrl(s.env),explorerUrl:v.MainChain.ExplorerUrl(s.env)}),gr=(s,t)=>s.explorerUrl+(t?"/"+t:""),L=s=>{if(s==="warp")return`warp:${$.Warp}`;if(s==="brand")return`brand:${$.Brand}`;if(s==="abi")return`abi:${$.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},O=(s,t)=>s?.actions[t-1],tt=s=>({name:s.name.toString(),displayName:s.display_name.toString(),chainId:s.chain_id.toString(),blockTime:s.block_time.toNumber(),addressHrp:s.address_hrp.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString()}),M=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let a=r+n;if(i>=a.length)return 0n;let o=a.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Wt=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},j=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var _=class _{static info(...t){_.isTestEnv||console.info(...t)}static warn(...t){_.isTestEnv||console.warn(...t)}static error(...t){_.isTestEnv||console.error(...t)}};_.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=_;import{DevnetEntrypoint as de,MainnetEntrypoint as me,TestnetEntrypoint as he}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 D=U;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},B={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,LastWarpExecutionInputs:(s,t)=>`warp-exec-inputs:${s}:${t}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`,ChainInfos:()=>"chains"},R=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new H:t==="memory"?new D:typeof window<"u"&&window.localStorage?new H:new D}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};import ge from"qr-code-styling";import{Address as Ct,TransactionsFactoryConfig as ce,TransferTransactionsFactory as ue}from"@multiversx/sdk-core";import oe from"ajv";var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,i)=>{n&&Object.keys(n).forEach(a=>{a!==a.toUpperCase()&&e.push(`${i} name '${a}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi),i=Object.values(t.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||v.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new oe,a=i.compile(n);return a(t)?[]:[`Schema validation failed: ${i.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var z=class{constructor(t){this.pendingWarp={protocol:L("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new R(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 ce({chainID:e.chainId}),n=new ue({config:r}),i=Ct.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=n.createTransactionForTransfer(i,{receiver:Ct.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.Warp(t);if(e){let o=this.cache.get(r);if(o)return w.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=b(this.config),a=h.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return w.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Wt(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new G(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
|
|
2
|
+
`))}};var 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 h.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 It,Address as P,AddressValue as rt,BytesValue as I,SmartContractTransactionsFactory as le,TransactionsFactoryConfig as fe}from"@multiversx/sdk-core/out";var et={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var K=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),owner:s.owner.toString(),createdAt:s.created_at.toNumber(),upgradedAt:s.upgraded_at?.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),bt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});var q=class{constructor(t){this.config=t,this.cache=new R(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=P.newFromBech32(this.config.user.wallet),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,a=()=>e&&r?[I.fromHex(t),I.fromUTF8(e),I.fromHex(r)]:e?[I.fromHex(t),I.fromUTF8(e)]:[I.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:a()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[I.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromUTF8(t),I.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t),I.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[I.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[I.fromHex(t),new rt(new P(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=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=P.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[I.fromHex(t),I.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getInfoByAlias",arguments:[I.fromUTF8(t)]}),c=await a.runQuery(o),[u]=a.parseQueryResponse(c),p=u?K(u):null,f=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:f},e.ttl),{registryInfo:p,brand:f}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=B.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return w.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[I.fromHex(t)]}),o=await i.runQuery(a),[c]=i.parseQueryResponse(o),u=c?K(c):null,p=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:p},e.ttl),{registryInfo:u,brand:p}}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 rt(new P(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a);return o.map(K)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new rt(new P(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a),c=o.map(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=B.ChainInfos();if(t&&t.ttl){let u=this.cache.get(e);if(u)return w.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),u}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(tt);if(t&&t.ttl){for(let u of c)this.cache.set(B.ChainInfo(u.chain),u,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:i,function:"getChain",arguments:[I.fromUTF8(t)]}),c=await a.runQuery(o),[u]=a.parseQueryResponse(c),p=u?tt(u):null;return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch{return null}}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return w.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=b(this.config),o=h.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),u=JSON.parse(c.data.toString());return u.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}catch{return null}}getRegistryContractAddress(){return P.newFromBech32(this.config.registry?.contract||v.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?bt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=b(this.config),e=new fe({chainID:t.chainId}),r=It.create(et);return new le({config:e,abi:r})}getController(){let t=b(this.config),e=h.getChainEntrypoint(t,this.config.env),r=It.create(et);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var J=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),a=(await Promise.all(n)).filter(u=>u.match),o=a.length>0,c=a.map(u=>({url:u.url,warp:u.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):h.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:a}=n,o=new z(this.config),c=new q(this.config),u=null,p=null,f=null;if(i==="hash"){u=await o.createFromTransactionHash(a,e);let d=await c.getInfoByHash(a,e);p=d.registryInfo,f=d.brand}else if(i==="alias"){let d=await c.getInfoByAlias(a,e);p=d.registryInfo,f=d.brand,d.registryInfo&&(u=await o.createFromTransactionHash(d.registryInfo.hash,e))}let m=u?await F.apply(this.config,u):null;return m?{match:!0,url:t,warp:m,registryInfo:p,brand:f}:r}catch(i){return w.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||v.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return v.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=h.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",a="#23F7DD"){let o=this.build(t,e);return new ge({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=v.SuperClientUrls.includes(e.origin),n=e.searchParams.get(l.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(a)}};var ye="https://",h=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(l.IdentifierParamSeparator)?e:`${l.IdentifierType.Alias}${l.IdentifierParamSeparator}${e}`,[n,i]=r.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(ye))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=j(o,{...e.vars,...n}),y=g?`${a}?${g}`:a;return[{identifier:y,url:this.buildNextUrl(y,t)}]}let u=c[0];if(!u)return[];let p=u.match(/{{([^[]+)\[\]/),f=p?p[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 y=g.match(/\[\](\.[^}]+)?}}/),C=y&&y[1]||"";return{placeholder:g,field:C?C.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(g=>{let y=o;for(let{regex:x,field:E}of d){let W=E?this.getNestedValue(g,E):g;if(W==null)return null;y=y.replace(x,W)}if(y.includes("{{")||y.includes("}}"))return null;let C=y?`${a}?${y}`:a;return{identifier:C,url:this.buildNextUrl(C,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 J(e).build(i.type,i.identifierBase);if(!n)return o;let c=new URL(o);return new URLSearchParams(n).forEach((u,p)=>c.searchParams.set(p,u)),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 q(t).getChainInfo(e.chain,{ttl:Q.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new de(t.apiUrl,n,r):e==="testnet"?new he(t.apiUrl,n,r):new me(t.apiUrl,n,r)}};var At=class{constructor(t){this.pendingBrand={protocol:L("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=b(this.config),r=new we({chainID:e.chainId}),n=new Te({config:r}),i=vt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:vt.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=h.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return w.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||v.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new We,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};import{Address as Ce,AddressValue as be,BigUIntType as Ie,BigUIntValue as xt,BooleanValue as ve,BytesValue as Ae,CodeMetadata as xe,CodeMetadataValue as Be,CompositeType as Se,CompositeValue as Ee,Field as nt,FieldDefinition as it,List as Pe,NothingValue as Re,OptionalValue as at,OptionValue as st,StringValue as Ve,Struct as Ne,StructType as Ue,TokenIdentifierType as Fe,TokenIdentifierValue as Bt,U16Value as Oe,U32Value as ke,U64Type as $e,U64Value as St,U8Value as Le,VariadicValue as _e}from"@multiversx/sdk-core/out";var Un=(s,t)=>s?st.newProvided(s):t?st.newMissingTyped(t):st.newMissing(),Fn=(s,t)=>s?new at(s.getType(),s):t?new at(t):at.newMissing(),On=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Pe(t,s)},kn=s=>_e.fromItems(...s),$n=s=>{let t=s.map(e=>e.getType());return new Ee(new Se(...t),s)},Ln=s=>Ve.fromUTF8(s),_n=s=>new Le(s),qn=s=>new Oe(s),Hn=s=>new ke(s),Dn=s=>new St(s),Mn=s=>new xt(BigInt(s)),jn=s=>new ve(s),Qn=s=>new be(Ce.newFromBech32(s)),Gn=s=>new Bt(s),zn=s=>Ae.fromHex(s),Kn=s=>new Ne(new Ue("EsdtTokenPayment",[new it("token_identifier","",new Fe),new it("token_nonce","",new $e),new it("amount","",new Ie)]),[new nt(new Bt(s.token.identifier),"token_identifier"),new nt(new St(BigInt(s.token.nonce)),"token_nonce"),new nt(new xt(BigInt(s.amount)),"amount")]),Jn=s=>new Be(xe.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Xn=()=>new Re;import{Address as qe,TransactionsFactoryConfig as He,TransferTransactionsFactory as De}from"@multiversx/sdk-core";var X=class{constructor(t){this.cache=new R;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 He({chainID:e.chainId}),n=new De({config:r}),i={protocol:L("abi"),content:t},a=qe.newFromBech32(this.config.user.wallet),o=JSON.stringify(i),c=n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=B.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return w.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=b(this.config),a=h.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return w.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as wt,Address as Tt,ArgSerializer as ir,SmartContractTransactionsFactory as ar,Token as ne,TokenComputer as sr,TokenTransfer as ie,TransactionsFactoryConfig as or,TransferTransactionsFactory as cr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Xe,TransactionEventsParser as Ye,findEventsByFirstTopic as Ze}from"@multiversx/sdk-core/out";import{Address as Me,AddressType as Et,AddressValue as Pt,BigUIntType as ot,BigUIntValue as ct,BooleanType as Rt,BooleanValue as Vt,BytesType as Nt,BytesValue as Ut,CodeMetadata as je,CodeMetadataType as Ft,CodeMetadataValue as Ot,CompositeType as kt,CompositeValue as $t,Field as ut,FieldDefinition as pt,List as Lt,ListType as Qe,NothingValue as S,OptionalType as Ge,OptionalValue as lt,OptionType as ze,OptionValue as ft,StringType as _t,StringValue as qt,Struct as Ke,StructType as Ht,Token as Je,TokenIdentifierType as gt,TokenIdentifierValue as dt,TokenTransfer as Dt,U16Type as Mt,U16Value as jt,U32Type as Qt,U32Value as Gt,U64Type as mt,U64Value as ht,U8Type as zt,U8Value as Kt,VariadicType as Jt,VariadicValue as Xt}from"@multiversx/sdk-core/out";var Yt=new RegExp(`${l.ArgParamsSeparator}(.*)`),k=class{nativeToString(t,e){return t==="esdt"&&e instanceof Dt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(ft.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(lt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Lt.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(Xt.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($t.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(ct.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Kt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(jt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Gt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ht.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(qt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(dt.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ut.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Ot.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 kt(...e.split(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new _t;if(t==="uint8")return new zt;if(t==="uint16")return new Mt;if(t==="uint32")return new Qt;if(t==="uint64")return new mt;if(t==="biguint")return new ot;if(t==="bool")return new Rt;if(t==="address")return new Et;if(t==="token")return new gt;if(t==="hex")return new Nt;if(t==="codemeta")return new Ft;if(t==="esdt"||t==="nft")return new Ht("EsdtTokenPayment",[new pt("token_identifier","",new gt),new pt("token_nonce","",new mt),new pt("amount","",new ot)]);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],u=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`list:${a}`,u]}else if(r==="variadic"){let i=n.split(l.ArgParamsSeparator),a=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`variadic:${a}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((c,u)=>this.stringToNative(`${i[u]}:${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 Dt({token:new Je({identifier:i,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new S;if(e==="option"){let n=this.stringToTyped(r);return n instanceof S?ft.newMissingTyped(n.getType()):ft.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof S?lt.newMissing():new lt(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Lt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Xt(new Jt(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((u,p)=>this.stringToTyped(`${a[p]}:${u}`)),c=o.map(u=>u.getType());return new $t(new kt(...c),o)}if(e==="string")return r?qt.fromUTF8(r):new S;if(e==="uint8")return r?new Kt(Number(r)):new S;if(e==="uint16")return r?new jt(Number(r)):new S;if(e==="uint32")return r?new Gt(Number(r)):new S;if(e==="uint64")return r?new ht(BigInt(r)):new S;if(e==="biguint")return r?new ct(BigInt(r)):new S;if(e==="bool")return r?new Vt(typeof r=="boolean"?r:r==="true"):new S;if(e==="address")return r?new Pt(Me.newFromBech32(r)):new S;if(e==="token")return r?new dt(r):new S;if(e==="hex")return r?Ut.fromHex(r):new S;if(e==="codemeta")return new Ot(je.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new Ke(this.nativeToType("esdt"),[new ut(new dt(n[0]),"token_identifier"),new ut(new ht(BigInt(n[1])),"token_nonce"),new ut(new ct(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof ze)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ge)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Qe)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Jt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof _t)return"string";if(t instanceof zt)return"uint8";if(t instanceof Mt)return"uint16";if(t instanceof Qt)return"uint32";if(t instanceof mt)return"uint64";if(t instanceof ot)return"biguint";if(t instanceof Rt)return"bool";if(t instanceof Et)return"address";if(t instanceof gt)return"token";if(t instanceof Nt)return"hex";if(t instanceof Ft)return"codemeta";if(t instanceof Ht&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var yt=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)},tr=(s,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,s),Zt=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,T]of Object.entries(t.results))o[d]=T;return{values:a,results:await Y(t,o,n,i)}}let u=await s.getAbiForAction(e),p=new Ye({abi:u}),m=new Xe({abi:u}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,T]of Object.entries(t.results)){if(T.startsWith(l.Transform.Prefix))continue;if(T.startsWith("input.")){o[d]=T;continue}let g=yt(T);if(g!==null&&g!==n){o[d]=null;continue}let[y,C,x]=T.split(".");if(y==="event"){if(!C||isNaN(Number(x)))continue;let E=Number(x),W=Ze(r,C),V=p.parseEvents({events:W})[0],N=Object.values(V)[E]||null;a.push(N),o[d]=N&&N.valueOf()}else if(y==="out"||y.startsWith("out[")){if(!C)continue;let E=Number(C),W=m.values[E-1]||null;x&&(W=W[x]||null),W&&typeof W=="object"&&(W="toFixed"in W?W.toFixed():W.valueOf()),a.push(W),o[d]=W&&W.valueOf()}else o[d]=T}return{values:a,results:await Y(t,o,n,i)}},te=async(s,t,e,r)=>{let n=new k,i=t.map(u=>n.typedToString(u)),a=t.map(u=>n.typedToNative(u)[1]),o={};if(!s.results)return{values:i,results:o};let c=u=>{let p=u.split(".").slice(1).map(m=>parseInt(m)-1);if(p.length===0)return;let f=a[p[0]];for(let m=1;m<p.length;m++){if(f==null)return;f=f[p[m]]}return f};for(let[u,p]of Object.entries(s.results)){if(p.startsWith(l.Transform.Prefix))continue;let f=yt(p);if(f!==null&&f!==e){o[u]=null;continue}p.startsWith("out.")||p==="out"||p.startsWith("out[")?o[u]=c(p)||null:o[u]=p}return{values:i,results:await Y(s,o,e,r)}},ee=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=yt(o);if(c!==null&&c!==e){i[a]=null;continue}let[u,...p]=o.split(".");if(u==="out"||u.startsWith("out[")){let f=p.length===0?t?.data||t:tr(t,p);n.push(f),i[a]=f}else i[a]=o}return{values:n,results:await Y(s,i,e,r)}};var Y=async(s,t,e,r)=>{if(!s.results)return t;let n={...t};return n=er(n,s,e,r),n=await rr(s,n),n},er=(s,t,e,r)=>{let n={...s},i=O(t,e)?.inputs||[],a=new k;for(let[o,c]of Object.entries(n))if(typeof c=="string"&&c.startsWith("input.")){let u=c.split(".")[1],p=i.findIndex(f=>f.as===u||f.name===u);n[o]=p!==-1?a.stringToNative(r[p])[1]:null}return n},rr=async(s,t)=>{if(!s.results)return t;let e={...t},r=Object.entries(s.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of r)try{let{runInVm:a}=await import("./vm-JCVDACTR.mjs");e[n]=await a(i,e)}catch(a){w.error(`Transform error for result '${n}':`,a),e[n]=null}return e};var nr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],re=s=>nr.find(t=>t.id===s)||null;var Z=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return w.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return w.error("WarpContractLoader: getVerificationInfo error",r),null}}};var ae=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new k,this.contractLoader=new Z(t),this.cache=new R(t.cache?.type)}async createTransactionForExecute(t,e,r){let n=O(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let i=Tt.newFromBech32(this.config.user.wallet),a=await h.getChainInfoForAction(this.config,n),o=new or({chainID:a.chainId}),{destination:c,args:u,value:p,transfers:f,data:m}=await this.getTxComponentsFromInputs(a,n,r,i),d=u.map(g=>this.serializer.stringToTyped(g)),T=null;if(n.type==="transfer")T=new cr({config:o}).createTransactionForTransfer(i,{receiver:c,nativeAmount:p,tokenTransfers:f,data:m?new Uint8Array(m):void 0});else if(n.type==="contract"&&c.isSmartContract())T=new ar({config:o}).createTransactionForExecute(i,{contract:c,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:d,tokenTransfers:f,nativeTransferAmount:p});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(!T)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(B.LastWarpExecutionInputs(t.meta?.hash||"",e),r,Q.OneWeek),T}async getTransactionExecutionResults(t,e,r){let n=await F.apply(this.config,t),i=O(n,e),a=this.cache.get(B.LastWarpExecutionInputs(t.meta?.hash||"",e))??[],{values:o,results:c}=await Zt(this,n,i,r,e,a),u=h.getNextInfo(this.config,n,e,c),p=this.getPreparedMessages(n,c);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:u,values:o,results:c,messages:p}}async executeQuery(t,e,r){let n=O(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await h.getChainInfoForAction(this.config,n),a=await F.apply(this.config,t),o=await this.getAbiForAction(n),{args:c}=await this.getTxComponentsFromInputs(i,n,r),u=c.map(A=>this.serializer.stringToTyped(A)),p=h.getChainEntrypoint(i,this.config.env),f=Tt.newFromBech32(n.address),m=p.createSmartContractController(o),d=m.createQuery({contract:f,function:n.func,arguments:u}),T=await m.runQuery(d),g=T.returnCode==="ok",y=new ir,C=o.getEndpoint(T.function),x=T.returnDataParts.map(A=>Buffer.from(A)),E=y.buffersToValues(x,C.output),{values:W,results:V}=await te(a,E,e,r),N=h.getNextInfo(this.config,a,e,V);return{success:g,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:N,values:W,results:V,messages:this.getPreparedMessages(a,V)}}async executeCollect(t,e,r,n){let i=O(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let a=await h.getChainInfoForAction(this.config,i),o=await F.apply(this.config,t),c=await this.getResolvedInputs(a,i,r),u=this.getModifiedInputs(c),p=g=>{if(!g.value)return null;let y=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return y.toString();if(g.input.type==="esdt"){let C=y;return{token:C.token.identifier,nonce:C.token.nonce.toString(),amount:C.amount.toString()}}else return y},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([g,y])=>{f.set(g,y)});let m=Object.fromEntries(u.map(g=>[g.input.as||g.input.name,p(g)])),d=i.destination.method||"GET",T=d==="GET"?void 0:JSON.stringify({inputs:m,meta:n});try{let g=await fetch(i.destination.url,{method:d,headers:f,body:T}),y=await g.json(),{values:C,results:x}=await ee(o,y,e,r),E=h.getNextInfo(this.config,o,e,x);return{success:g.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:E,values:C,results:x,messages:this.getPreparedMessages(o,x)}}catch(g){return w.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r,n){let i=await this.getResolvedInputs(t,e,r),a=this.getModifiedInputs(i),o=a.find(A=>A.input.position==="receiver")?.value,c="address"in e?e.address:null,u=o?.split(":")[1]||c||n?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=Tt.newFromBech32(u),f=this.getPreparedArgs(e,a),m=a.find(A=>A.input.position==="value")?.value||null,d="value"in e?e.value:null,T=BigInt(m?.split(":")[1]||d||0),g=a.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),C=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...g?.map(A=>this.serializer.stringToNative(A)[1])||[]],x=a.find(A=>A.input.position==="data")?.value,E="data"in e?e.data||"":null,W=x||E||null,V=W?this.serializer.stringToTyped(W).valueOf():null,N=V?Buffer.from(V):null;return{destination:p,args:f,value:T,transfers:C,data:N}}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 u=this.url.searchParams.get(o.name);return u?this.serializer.nativeToString(o.type,u):null}else return o.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:i[c]||null};return n.map((o,c)=>({input:o,value:a(o,c)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(i,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(l.ArgParamsSeparator,2);if(r==="esdt"){let[i,a,o,c]=n.split(l.ArgCompositeSeparator);if(c)return e;let u=new ne({identifier:i,nonce:BigInt(a)});if(!new sr().isFungible(u))return e;let m=re(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 ie({token:u,amount:M(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 wt.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let a=Number(n.position.split(":")[1])-1;r.splice(a,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,j(i,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(l.IdentifierType.Hash)){let e=new X(this.config),r=t.abi.split(l.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return wt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return wt.create(r)}}toTypedTransfer(t){return new ie({token:new ne({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var se=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw w.error("WarpIndex: Error searching for warps: ",n),n}}};export{At as BrandBuilder,B as CacheKey,Q as CacheTtl,v as Config,X as WarpAbiBuilder,ae as WarpActionExecutor,k as WarpArgSerializer,z as WarpBuilder,R as WarpCache,l as WarpConstants,Z as WarpContractLoader,se as WarpIndex,F as WarpInterpolator,J as WarpLink,$ as WarpProtocolVersions,q as WarpRegistry,h as WarpUtils,G as WarpValidator,Qn as address,Mn as biguint,jn as boolean,Jn as codemeta,$n as composite,Kn as esdt,gr as getChainExplorerUrl,L as getLatestProtocolIdentifier,b as getMainChainInfo,O as getWarpActionByIndex,zn as hex,On as list,Xn as nothing,Un as option,Fn as optional,j as replacePlaceholders,M as shiftBigintBy,Ln as string,Wt as toPreviewText,tt as toTypedChainInfo,Gn as token,qn as u16,Hn as u32,Dn as u64,_n as u8,kn as variadic};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a as l}from"./chunk-3SAEGOMQ.mjs";var u=async(n,i)=>{if(typeof window>"u"){let s;try{s=l("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 e=new s({timeout:1e3,sandbox:{result:i},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}return new Promise((s,e)=>{try{let o=new Blob([`
|
|
2
|
+
self.onmessage = function(e) {
|
|
3
|
+
try {
|
|
4
|
+
const result = e.data;
|
|
5
|
+
const output = (${n})(result);
|
|
6
|
+
self.postMessage({ result: output });
|
|
7
|
+
} catch (error) {
|
|
8
|
+
self.postMessage({ error: error.toString() });
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
`],{type:"application/javascript"}),a=URL.createObjectURL(o),r=new Worker(a);r.onmessage=function(t){t.data.error?e(new Error(t.data.error)):s(t.data.result),r.terminate(),URL.revokeObjectURL(a)},r.onerror=function(t){e(new Error(`Error in transform: ${t.message}`)),r.terminate(),URL.revokeObjectURL(a)},r.postMessage(i)}catch(o){return e(o)}})};export{u as runInVm};
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vleap/warps",
|
|
3
|
-
"version": "2.3.0-alpha.
|
|
3
|
+
"version": "2.3.0-alpha.5",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"scripts": {
|
|
9
|
-
"build": "tsup",
|
|
9
|
+
"build": "tsup src/index.ts --dts --format cjs,esm --minify --clean",
|
|
10
10
|
"test": "jest --config jest.config.js",
|
|
11
11
|
"lint": "tsc --noEmit",
|
|
12
12
|
"prepare": "npm run build",
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@multiversx/sdk-core": "^14.0.2"
|
|
21
|
+
"@multiversx/sdk-core": "^14.0.2",
|
|
22
|
+
"vm2": "^3.9.17"
|
|
22
23
|
},
|
|
23
24
|
"devDependencies": {
|
|
24
25
|
"@multiversx/sdk-core": "^14.2.1",
|
|
@@ -28,9 +29,7 @@
|
|
|
28
29
|
"jest-fetch-mock": "^3.0.3",
|
|
29
30
|
"ts-jest": "^29.4.0",
|
|
30
31
|
"tsup": "^8.5.0",
|
|
31
|
-
"typescript": "^5.8.3"
|
|
32
|
-
},
|
|
33
|
-
"optionalDependencies": {
|
|
32
|
+
"typescript": "^5.8.3",
|
|
34
33
|
"vm2": "^3.9.19"
|
|
35
34
|
},
|
|
36
35
|
"publishConfig": {
|