@vleap/warps 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -297,6 +297,10 @@ declare class WarpAbiBuilder {
297
297
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<WarpAbi | null>;
298
298
  }
299
299
 
300
+ type ResolvedInput = {
301
+ input: WarpActionInput;
302
+ value: string | null;
303
+ };
300
304
  declare class WarpActionExecutor {
301
305
  private config;
302
306
  private url;
@@ -313,9 +317,9 @@ declare class WarpActionExecutor {
313
317
  transfers: TokenTransfer$1[];
314
318
  data: Buffer | null;
315
319
  }>;
316
- private getModifiedInputs;
317
- private getResolvedInputs;
318
- private preprocessInput;
320
+ getResolvedInputs(action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
321
+ getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
322
+ preprocessInput(input: string): Promise<string>;
319
323
  private getPreparedArgs;
320
324
  private getAbiForAction;
321
325
  private fetchAbi;
@@ -331,7 +335,7 @@ declare class WarpArgSerializer {
331
335
  nativeToType(type: BaseWarpActionInputType): Type;
332
336
  stringToNative(value: string): [WarpActionInputType, WarpNativeValue];
333
337
  stringToTyped(value: string): TypedValue;
334
- typeToNative(type: Type): BaseWarpActionInputType;
338
+ typeToString(type: Type): WarpActionInputType;
335
339
  }
336
340
 
337
341
  declare class WarpBuilder {
package/dist/index.d.ts CHANGED
@@ -297,6 +297,10 @@ declare class WarpAbiBuilder {
297
297
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<WarpAbi | null>;
298
298
  }
299
299
 
300
+ type ResolvedInput = {
301
+ input: WarpActionInput;
302
+ value: string | null;
303
+ };
300
304
  declare class WarpActionExecutor {
301
305
  private config;
302
306
  private url;
@@ -313,9 +317,9 @@ declare class WarpActionExecutor {
313
317
  transfers: TokenTransfer$1[];
314
318
  data: Buffer | null;
315
319
  }>;
316
- private getModifiedInputs;
317
- private getResolvedInputs;
318
- private preprocessInput;
320
+ getResolvedInputs(action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
321
+ getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
322
+ preprocessInput(input: string): Promise<string>;
319
323
  private getPreparedArgs;
320
324
  private getAbiForAction;
321
325
  private fetchAbi;
@@ -331,7 +335,7 @@ declare class WarpArgSerializer {
331
335
  nativeToType(type: BaseWarpActionInputType): Type;
332
336
  stringToNative(value: string): [WarpActionInputType, WarpNativeValue];
333
337
  stringToTyped(value: string): TypedValue;
334
- typeToNative(type: Type): BaseWarpActionInputType;
338
+ typeToString(type: Type): WarpActionInputType;
335
339
  }
336
340
 
337
341
  declare class WarpBuilder {
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var pt=Object.create;var q=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var ft=(s,t)=>{for(var e in t)q(s,e,{get:t[e],enumerable:!0})},Z=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lt(t))!gt.call(s,n)&&n!==e&&q(s,n,{get:()=>t[n],enumerable:!(r=ut(t,n))||r.enumerable});return s};var H=(s,t,e)=>(e=s!=null?pt(dt(s)):{},Z(t||!s||!s.__esModule?q(e,"default",{value:s,enumerable:!0}):e,s)),mt=s=>Z(q({},"__esModule",{value:!0}),s);var Ot={};ft(Ot,{BrandBuilder:()=>z,CacheKey:()=>C,Config:()=>w,WarpAbiBuilder:()=>k,WarpActionExecutor:()=>M,WarpArgSerializer:()=>$,WarpBuilder:()=>E,WarpCache:()=>A,WarpConstants:()=>d,WarpContractLoader:()=>O,WarpIndex:()=>G,WarpLink:()=>N,WarpProtocolVersions:()=>I,WarpRegistry:()=>F,WarpUtils:()=>y,WarpValidator:()=>S,address:()=>Rt,biguint:()=>Vt,boolean:()=>Pt,codemeta:()=>Nt,composite:()=>bt,esdt:()=>Ft,getChainId:()=>W,getLatestProtocolIdentifier:()=>B,getWarpActionByIndex:()=>ht,hex:()=>Et,list:()=>At,nothing:()=>kt,option:()=>Tt,optional:()=>Wt,shiftBigintBy:()=>U,string:()=>It,toPreviewText:()=>j,toTypedRegistryInfo:()=>R,token:()=>Ut,u16:()=>vt,u32:()=>xt,u64:()=>St,u8:()=>Bt,variadic:()=>Ct});module.exports=mt(Ot);var x=require("@multiversx/sdk-core"),rt=H(require("ajv"));var I={Warp:"1.0.0",Brand:"0.1.0",Abi:"0.1.0"},w={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${I.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${I.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"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var W=s=>s==="devnet"?"D":s==="testnet"?"T":"1",B=s=>{if(s==="warp")return`warp:${I.Warp}`;if(s==="brand")return`brand:${I.Brand}`;if(s==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},ht=(s,t)=>s?.actions[t-1],R=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),U=(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 o=r+n;if(i>=o.length)return 0n;let p=o.slice(0,-i)||"0";return BigInt(p)}else return BigInt(s)},j=(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};var b=require("@multiversx/sdk-core");var d={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var Y=H(require("qr-code-styling"));var v=require("@multiversx/sdk-core");var C={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},A=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var X=H(require("ajv"));var S=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||w.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new X.default,o=i.compile(n);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var E=class{constructor(t){this.cache=new A;this.pendingWarp={protocol:B("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new v.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new v.TransferTransactionsFactory({config:e}),n=v.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:v.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new S(this.config).validate(r),y.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=C.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=y.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),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 new S(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return j(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var g=require("@multiversx/sdk-core/out");var Q={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",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}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var F=class{constructor(t){this.cache=new A;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[g.BytesValue.fromHex(t),g.BytesValue.fromUTF8(e)]:[g.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromUTF8(t),g.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t),g.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.BytesValue.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t),g.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=C.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),h}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[g.BytesValue.fromUTF8(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?R(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}}async getInfoByHash(t,e){let r=C.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),h}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[g.BytesValue.fromHex(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?R(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}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;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 g.AddressValue(new g.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o);return p.map(R)}async getUserBrands(t){let e=t||this.config.userAddress;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 g.AddressValue(new g.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o),u=p.map(h=>h.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(u.map(h=>this.fetchBrand(h,l)))).filter(h=>h!==null)}async fetchBrand(t,e){let r=C.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=y.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=JSON.parse(i.data.toString());return o.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return g.Address.newFromBech32(this.config.registryContract||w.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new g.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=g.AbiRegistry.create(Q);return new g.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=y.getChainEntrypoint(this.config),e=g.AbiRegistry.create(Q);return t.createSmartContractController(e)}};var N=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(d.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(n)).filter(l=>l.match),p=o.length>0,u=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:u}}async detect(t){let e=t.startsWith(d.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new E(this.config),o=new F(this.config),p=null,u=null,l=null;if(r==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:h}=await o.getInfoByHash(n);u=f,l=h}catch{}}else if(r==="alias"){let{registryInfo:f,brand:h}=await o.getInfoByAlias(n);u=f,l=h,f&&(p=await i.createFromTransactionHash(f.hash))}return p?{match:!0,url:t,warp:p,registryInfo:u,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||w.DefaultClientUrl(this.config.env),n=t===d.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+d.IdentifierParamSeparator+e);return w.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${d.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let p=this.build(t,e);return new Y.default({type:"svg",width:r,height:r,data:String(p),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(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=w.SuperClientUrls.includes(e.origin),n=e.searchParams.get(d.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return y.getInfoFromPrefixedIdentifier(o)}};var wt="https://",tt="query",et="env",y=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,o)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o=="string"&&o.startsWith(`${tt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${tt}:`)[1],u=new URL(e.currentUrl).searchParams.get(p);u&&n(i,u)}else if(typeof o=="string"&&o.startsWith(`${et}:`)){let p=o.split(`${et}:`)[1],u=e.vars?.[p];u&&n(i,u)}else n(i,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(d.IdentifierParamSeparator)?e:`${d.IdentifierType.Alias}${d.IdentifierParamSeparator}${e}`,[n,i]=r.split(d.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(wt))return t.next;{let r=new N(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getChainEntrypoint(t){return t.env==="devnet"?new b.DevnetEntrypoint:t.env==="testnet"?new b.TestnetEntrypoint:new b.MainnetEntrypoint}static getConfiguredChainApi(t){let e=t.chainApiUrl||w.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new b.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var z=class{constructor(t){this.pendingBrand={protocol:B("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new x.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new x.TransferTransactionsFactory({config:e}),n=x.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:x.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}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=y.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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.brandSchemaUrl||w.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new rt.default,o=i.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out"),Tt=(s,t)=>s?c.OptionValue.newProvided(s):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),Wt=(s,t)=>s?new c.OptionalValue(s.getType(),s):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),At=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new c.List(t,s)},Ct=s=>c.VariadicValue.fromItems(...s),bt=s=>{let t=s.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),s)},It=s=>c.StringValue.fromUTF8(s),Bt=s=>new c.U8Value(s),vt=s=>new c.U16Value(s),xt=s=>new c.U32Value(s),St=s=>new c.U64Value(s),Vt=s=>new c.BigUIntValue(BigInt(s)),Pt=s=>new c.BooleanValue(s),Rt=s=>new c.AddressValue(c.Address.newFromBech32(s)),Ut=s=>new c.TokenIdentifierValue(s),Et=s=>c.BytesValue.fromHex(s),Ft=s=>new c.Struct(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)]),[new c.Field(new c.TokenIdentifierValue(s.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(s.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(s.amount)),"amount")]),Nt=s=>new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),kt=()=>new c.NothingValue;var V=require("@multiversx/sdk-core");var k=class{constructor(t){this.cache=new A;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new V.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new V.TransferTransactionsFactory({config:e}),n={protocol:B("abi"),content:t},i=V.Address.newFromBech32(this.config.userAddress),o=JSON.stringify(n),p=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return p.gasLimit=p.gasLimit+BigInt(2e6),p}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=C.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=y.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};var m=require("@multiversx/sdk-core");var $t=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],nt=s=>$t.find(t=>t.id===s)||null;var a=require("@multiversx/sdk-core/out");var it=new RegExp(`${d.ArgParamsSeparator}(.*)`),$=class{nativeToString(t,e){return t==="esdt"&&e instanceof a.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(a.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(a.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(a.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typedToString(p).split(d.ArgParamsSeparator)[0]),n=e.map(p=>this.typedToString(p).split(d.ArgParamsSeparator)[1]),i=r.join(d.ArgCompositeSeparator),o=n.join(d.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(a.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 a.CompositeType(...e.split(d.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new a.StringType;if(t==="uint8")return new a.U8Type;if(t==="uint16")return new a.U16Type;if(t==="uint32")return new a.U32Type;if(t==="uint64")return new a.U64Type;if(t==="biguint")return new a.BigUIntType;if(t==="bool")return new a.BooleanType;if(t==="address")return new a.AddressType;if(t==="token")return new a.TokenIdentifierType;if(t==="hex")return new a.BytesType;if(t==="codemeta")return new a.CodeMetadataType;if(t==="esdt"||t==="nft")return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(d.ArgParamsSeparator),r=e[0],n=e.slice(1).join(d.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(d.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(d.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(d.ArgParamsSeparator),o=i.slice(0,-1).join(d.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let i=n.split(d.ArgParamsSeparator),o=i.slice(0,-1).join(d.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(d.ArgCompositeSeparator),p=n.split(d.ArgCompositeSeparator).map((u,l)=>this.stringToNative(`${i[l]}:${u}`)[1]);return[r,p]}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,o,p]=n.split(d.ArgCompositeSeparator);return[r,new a.TokenTransfer({token:new a.Token({identifier:i,nonce:BigInt(o)}),amount:BigInt(p)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new a.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(it,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.List(this.nativeToType(n),p)}if(e==="variadic"){let[n,i]=r.split(it,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(n)),p)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(d.ArgCompositeSeparator),o=n.split(d.ArgCompositeSeparator),p=i.map((l,f)=>this.stringToTyped(`${o[f]}:${l}`)),u=p.map(l=>l.getType());return new a.CompositeValue(new a.CompositeType(...u),p)}if(e==="string")return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(e==="uint8")return r?new a.U8Value(Number(r)):new a.NothingValue;if(e==="uint16")return r?new a.U16Value(Number(r)):new a.NothingValue;if(e==="uint32")return r?new a.U32Value(Number(r)):new a.NothingValue;if(e==="uint64")return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(e==="biguint")return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(e==="bool")return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(e==="address")return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(e==="token")return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(e==="hex")return r?a.BytesValue.fromHex(r):new a.NothingValue;if(e==="codemeta")return new a.CodeMetadataValue(a.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new a.Struct(this.nativeToType("esdt"),[new a.Field(new a.TokenIdentifierValue(n[0]),"token_identifier"),new a.Field(new a.U64Value(BigInt(n[1])),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof a.StringType)return"string";if(t instanceof a.U8Type)return"uint8";if(t instanceof a.U16Type)return"uint16";if(t instanceof a.U32Type)return"uint32";if(t instanceof a.U64Type)return"uint64";if(t instanceof a.BigUIntType)return"biguint";if(t instanceof a.BooleanType)return"bool";if(t instanceof a.AddressType)return"address";if(t instanceof a.TokenIdentifierType)return"token";if(t instanceof a.BytesType)return"hex";if(t instanceof a.CodeMetadataType)return"codemeta";if(t instanceof a.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var O=class{constructor(t){this.config=t}async getContract(t){try{let r=await y.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await y.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var M=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 O(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),n=new m.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:i,args:o,value:p,transfers:u,data:l}=await this.getTxComponentsFromInputs(t,e,r),f=o.map(h=>this.serializer.stringToTyped(h));if(t.type==="transfer")return new m.TransferTransactionsFactory({config:n}).createTransactionForTransfer(r,{receiver:i,nativeAmount:p,tokenTransfers:u,data:l?new Uint8Array(l):void 0});if(t.type==="contract"&&i.isSmartContract())return new m.SmartContractTransactionsFactory({config:n}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:f,tokenTransfers:u,nativeTransferAmount:p});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error("WarpActionExecutor: Invalid action type")}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=await this.getAbiForAction(t),{args:n}=await this.getTxComponentsFromInputs(t,e),i=n.map(P=>this.serializer.stringToTyped(P)),o=y.getChainEntrypoint(this.config),p=m.Address.newFromBech32(t.address),u=o.createSmartContractController(r),l=u.createQuery({contract:p,function:t.func,arguments:i}),f=await u.runQuery(l);if(!(f.returnCode==="ok"))throw new Error(`WarpActionExecutor: Query failed with return code ${f.returnCode}`);let L=new m.ArgSerializer,D=r.getEndpoint(f.function),_=f.returnDataParts.map(P=>Buffer.from(P));return L.buffersToValues(_,D.output)[0]}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,o])=>{n.set(i,o)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(T=>T.input.position==="receiver")?.value,p="address"in t?t.address:null,u=o?.split(":")[1]||p||r?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=m.Address.newFromBech32(u),f=this.getPreparedArgs(t,i),h=i.find(T=>T.input.position==="value")?.value||null,L="value"in t?t.value:null,D=BigInt(h?.split(":")[1]||L||0),_=i.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),P=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],..._?.map(T=>this.serializer.stringToNative(T)[1])||[]],st=i.find(T=>T.input.position==="data")?.value,ot="data"in t?t.data||"":null,K=st||ot||null,J=K?this.serializer.stringToTyped(K).valueOf():null,ct=J?Buffer.from(J):null;return{destination:l,args:f,value:D,transfers:P,data:ct}}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 o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=U(o,+i);return{...e,value:`${e.input.type}:${p}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=U(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),i=(o,p)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):n[p]||null;return r.map((o,p)=>({input:o,value:i(o,p)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,n]=t.split(d.ArgCompositeSeparator);if(n)return t;let i=r;if(!new m.TokenComputer().isFungible(i.token))return t;let u=nt(i.token.identifier)?.decimals;if(!u){let f=this.config.chainApiUrl||w.Chain.ApiUrl(this.config.env);u=(await(await fetch(`${f}/tokens/${i.token.identifier}`)).json()).decimals}if(!u)throw new Error(`WarpActionExecutor: Decimals not found for token ${i.token.identifier}`);let l=new m.TokenTransfer({token:i.token,amount:U(i.amount,u)});return this.serializer.nativeToString(e,l)+d.ArgCompositeSeparator+u}return t}catch{return t}}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 o=Number(n.position.split(":")[1])-1;r.splice(o,0,i)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return m.AbiRegistry.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(d.IdentifierType.Hash)){let e=new k(this.config),r=t.abi.split(d.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return m.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return m.AbiRegistry.create(r)}}toTypedTransfer(t){return new m.TokenTransfer({token:new m.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var G=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"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,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
1
+ "use strict";var pt=Object.create;var _=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var ft=(s,t)=>{for(var e in t)_(s,e,{get:t[e],enumerable:!0})},X=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lt(t))!gt.call(s,n)&&n!==e&&_(s,n,{get:()=>t[n],enumerable:!(r=ut(t,n))||r.enumerable});return s};var H=(s,t,e)=>(e=s!=null?pt(dt(s)):{},X(t||!s||!s.__esModule?_(e,"default",{value:s,enumerable:!0}):e,s)),mt=s=>X(_({},"__esModule",{value:!0}),s);var Ot={};ft(Ot,{BrandBuilder:()=>z,CacheKey:()=>C,Config:()=>w,WarpAbiBuilder:()=>O,WarpActionExecutor:()=>M,WarpArgSerializer:()=>L,WarpBuilder:()=>$,WarpCache:()=>A,WarpConstants:()=>l,WarpContractLoader:()=>q,WarpIndex:()=>G,WarpLink:()=>k,WarpProtocolVersions:()=>I,WarpRegistry:()=>N,WarpUtils:()=>y,WarpValidator:()=>x,address:()=>Rt,biguint:()=>Vt,boolean:()=>Pt,codemeta:()=>$t,composite:()=>bt,esdt:()=>Ft,getChainId:()=>W,getLatestProtocolIdentifier:()=>B,getWarpActionByIndex:()=>ht,hex:()=>Et,list:()=>At,nothing:()=>Nt,option:()=>Tt,optional:()=>Wt,shiftBigintBy:()=>F,string:()=>It,toPreviewText:()=>j,toTypedRegistryInfo:()=>E,token:()=>Ut,u16:()=>vt,u32:()=>St,u64:()=>xt,u8:()=>Bt,variadic:()=>Ct});module.exports=mt(Ot);var S=require("@multiversx/sdk-core"),nt=H(require("ajv"));var I={Warp:"1.0.0",Brand:"0.1.0",Abi:"0.1.0"},w={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${I.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${I.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"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var W=s=>s==="devnet"?"D":s==="testnet"?"T":"1",B=s=>{if(s==="warp")return`warp:${I.Warp}`;if(s==="brand")return`brand:${I.Brand}`;if(s==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},ht=(s,t)=>s?.actions[t-1],E=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),F=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let o=r+n;if(a>=o.length)return 0n;let p=o.slice(0,-a)||"0";return BigInt(p)}else return BigInt(s)},j=(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};var b=require("@multiversx/sdk-core");var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var tt=H(require("qr-code-styling"));var v=require("@multiversx/sdk-core");var C={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},A=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var Y=H(require("ajv"));var x=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||w.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new Y.default,o=a.compile(n);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var $=class{constructor(t){this.cache=new A;this.pendingWarp={protocol:B("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new v.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new v.TransferTransactionsFactory({config:e}),n=v.Address.newFromBech32(this.config.userAddress),a=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:v.Address.newFromBech32(this.config.userAddress),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 new x(this.config).validate(r),y.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=C.Warp(t);if(e){let a=this.cache.get(r);if(a)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),a}let n=y.getConfiguredChainApi(this.config);try{let a=await n.getTransaction(t),o=await this.createFromTransaction(a);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(a){return console.error("WarpBuilder: Error creating from transaction hash",a),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 new x(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return j(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var g=require("@multiversx/sdk-core/out");var Q={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",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}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var N=class{constructor(t){this.cache=new A;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[g.BytesValue.fromHex(t),g.BytesValue.fromUTF8(e)]:[g.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromUTF8(t),g.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t),g.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.BytesValue.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=g.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.BytesValue.fromHex(t),g.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=C.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),m}let n=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByAlias",arguments:[g.BytesValue.fromUTF8(t)]}),p=await a.runQuery(o),[d]=a.parseQueryResponse(p),u=d?E(d):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}async getInfoByHash(t,e){let r=C.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),m}let n=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[g.BytesValue.fromHex(t)]}),p=await a.runQuery(o),[d]=a.parseQueryResponse(p),u=d?E(d):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;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 g.AddressValue(new g.Address(e))]}),o=await n.runQuery(a),[p]=n.parseQueryResponse(o);return p.map(E)}async getUserBrands(t){let e=t||this.config.userAddress;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 g.AddressValue(new g.Address(e))]}),o=await n.runQuery(a),[p]=n.parseQueryResponse(o),d=p.map(m=>m.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(d.map(m=>this.fetchBrand(m,u)))).filter(m=>m!==null)}async fetchBrand(t,e){let r=C.Brand(t);if(e){let a=this.cache.get(r);if(a)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),a}let n=y.getConfiguredChainApi(this.config);try{let a=await n.getTransaction(t),o=JSON.parse(a.data.toString());return o.meta={hash:a.hash,creator:a.sender.bech32(),createdAt:new Date(a.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(a){return console.error("WarpRegistry: Error fetching brand from transaction hash",a),null}}getRegistryContractAddress(){return g.Address.newFromBech32(this.config.registryContract||w.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new g.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=g.AbiRegistry.create(Q);return new g.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=y.getChainEntrypoint(this.config),e=g.AbiRegistry.create(Q);return t.createSmartContractController(e)}};var k=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)),o=(await Promise.all(n)).filter(u=>u.match),p=o.length>0,d=o.map(u=>({url:u.url,warp:u.warp}));return{match:p,results:d}}async detect(t){let e=t.startsWith(l.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,a=new $(this.config),o=new N(this.config),p=null,d=null,u=null;if(r==="hash"){p=await a.createFromTransactionHash(n);try{let{registryInfo:f,brand:m}=await o.getInfoByHash(n);d=f,u=m}catch{}}else if(r==="alias"){let{registryInfo:f,brand:m}=await o.getInfoByAlias(n);d=f,u=m,f&&(p=await a.createFromTransactionHash(f.hash))}return p?{match:!0,url:t,warp:p,registryInfo:d,brand:u}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||w.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return w.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",a="black",o="#23F7DD"){let p=this.build(t,e);return new tt.default({type:"svg",width:r,height:r,data:String(p),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(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=w.SuperClientUrls.includes(e.origin),n=e.searchParams.get(l.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let o=decodeURIComponent(a);return y.getInfoFromPrefixedIdentifier(o)}};var wt="https://",et="query",rt="env",y=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(a,o)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o=="string"&&o.startsWith(`${et}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${et}:`)[1],d=new URL(e.currentUrl).searchParams.get(p);d&&n(a,d)}else if(typeof o=="string"&&o.startsWith(`${rt}:`)){let p=o.split(`${rt}:`)[1],d=e.vars?.[p];d&&n(a,d)}else n(a,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(l.IdentifierParamSeparator)?e:`${l.IdentifierType.Alias}${l.IdentifierParamSeparator}${e}`,[n,a]=r.split(l.IdentifierParamSeparator);return{type:n,id:a}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(wt))return t.next;{let r=new k(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getChainEntrypoint(t){return t.env==="devnet"?new b.DevnetEntrypoint:t.env==="testnet"?new b.TestnetEntrypoint:new b.MainnetEntrypoint}static getConfiguredChainApi(t){let e=t.chainApiUrl||w.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new b.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var z=class{constructor(t){this.pendingBrand={protocol:B("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new S.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new S.TransferTransactionsFactory({config:e}),n=S.Address.newFromBech32(this.config.userAddress),a=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:S.Address.newFromBech32(this.config.userAddress),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=y.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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.brandSchemaUrl||w.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new nt.default,o=a.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out"),Tt=(s,t)=>s?c.OptionValue.newProvided(s):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),Wt=(s,t)=>s?new c.OptionalValue(s.getType(),s):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),At=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new c.List(t,s)},Ct=s=>c.VariadicValue.fromItems(...s),bt=s=>{let t=s.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),s)},It=s=>c.StringValue.fromUTF8(s),Bt=s=>new c.U8Value(s),vt=s=>new c.U16Value(s),St=s=>new c.U32Value(s),xt=s=>new c.U64Value(s),Vt=s=>new c.BigUIntValue(BigInt(s)),Pt=s=>new c.BooleanValue(s),Rt=s=>new c.AddressValue(c.Address.newFromBech32(s)),Ut=s=>new c.TokenIdentifierValue(s),Et=s=>c.BytesValue.fromHex(s),Ft=s=>new c.Struct(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)]),[new c.Field(new c.TokenIdentifierValue(s.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(s.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(s.amount)),"amount")]),$t=s=>new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Nt=()=>new c.NothingValue;var V=require("@multiversx/sdk-core");var O=class{constructor(t){this.cache=new A;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new V.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new V.TransferTransactionsFactory({config:e}),n={protocol:B("abi"),content:t},a=V.Address.newFromBech32(this.config.userAddress),o=JSON.stringify(n),p=r.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return p.gasLimit=p.gasLimit+BigInt(2e6),p}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=C.WarpAbi(t);if(e){let a=this.cache.get(r);if(a)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),a}let n=y.getConfiguredChainApi(this.config);try{let a=await n.getTransaction(t),o=await this.createFromTransaction(a);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(a){return console.error("WarpAbiBuilder: Error creating from transaction hash",a),null}}};var h=require("@multiversx/sdk-core");var kt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],it=s=>kt.find(t=>t.id===s)||null;var i=require("@multiversx/sdk-core/out");var at=new RegExp(`${l.ArgParamsSeparator}(.*)`),L=class{nativeToString(t,e){return t==="esdt"&&e instanceof i.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(i.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(i.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(i.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[0])[0],a=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(i.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[0])[0],a=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(i.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typedToString(p).split(l.ArgParamsSeparator)[0]),n=e.map(p=>this.typedToString(p).split(l.ArgParamsSeparator)[1]),a=r.join(l.ArgCompositeSeparator),o=n.join(l.ArgCompositeSeparator);return`composite(${a}):${o}`}if(t.hasClassOrSuperclass(i.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(i.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(i.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(i.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(i.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(i.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(i.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(i.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(i.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(i.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(i.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 i.CompositeType(...e.split(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new i.StringType;if(t==="uint8")return new i.U8Type;if(t==="uint16")return new i.U16Type;if(t==="uint32")return new i.U32Type;if(t==="uint64")return new i.U64Type;if(t==="biguint")return new i.BigUIntType;if(t==="bool")return new i.BooleanType;if(t==="address")return new i.AddressType;if(t==="token")return new i.TokenIdentifierType;if(t==="hex")return new i.BytesType;if(t==="codemeta")return new i.CodeMetadataType;if(t==="esdt"||t==="nft")return new i.StructType("EsdtTokenPayment",[new i.FieldDefinition("token_identifier","",new i.TokenIdentifierType),new i.FieldDefinition("token_nonce","",new i.U64Type),new i.FieldDefinition("amount","",new i.BigUIntType)]);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[a,o]=n.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(r==="optional"){let[a,o]=n.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(r==="list"){let a=n.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),p=a[a.length-1],u=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`list:${o}`,u]}else if(r==="variadic"){let a=n.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),p=a[a.length-1],u=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`variadic:${o}`,u]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=n.split(l.ArgCompositeSeparator).map((d,u)=>this.stringToNative(`${a[u]}:${d}`)[1]);return[r,p]}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,o,p]=n.split(l.ArgCompositeSeparator);return[r,new i.TokenTransfer({token:new i.Token({identifier:a,nonce:BigInt(o)}),amount:BigInt(p)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new i.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof i.NothingValue?i.OptionValue.newMissingTyped(n.getType()):i.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof i.NothingValue?i.OptionalValue.newMissing():new i.OptionalValue(n.getType(),n)}if(e==="list"){let[n,a]=r.split(at,2),p=a.split(",").map(d=>this.stringToTyped(`${n}:${d}`));return new i.List(this.nativeToType(n),p)}if(e==="variadic"){let[n,a]=r.split(at,2),p=a.split(",").map(d=>this.stringToTyped(`${n}:${d}`));return new i.VariadicValue(new i.VariadicType(this.nativeToType(n)),p)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator),p=a.map((u,f)=>this.stringToTyped(`${o[f]}:${u}`)),d=p.map(u=>u.getType());return new i.CompositeValue(new i.CompositeType(...d),p)}if(e==="string")return r?i.StringValue.fromUTF8(r):new i.NothingValue;if(e==="uint8")return r?new i.U8Value(Number(r)):new i.NothingValue;if(e==="uint16")return r?new i.U16Value(Number(r)):new i.NothingValue;if(e==="uint32")return r?new i.U32Value(Number(r)):new i.NothingValue;if(e==="uint64")return r?new i.U64Value(BigInt(r)):new i.NothingValue;if(e==="biguint")return r?new i.BigUIntValue(BigInt(r)):new i.NothingValue;if(e==="bool")return r?new i.BooleanValue(typeof r=="boolean"?r:r==="true"):new i.NothingValue;if(e==="address")return r?new i.AddressValue(i.Address.newFromBech32(r)):new i.NothingValue;if(e==="token")return r?new i.TokenIdentifierValue(r):new i.NothingValue;if(e==="hex")return r?i.BytesValue.fromHex(r):new i.NothingValue;if(e==="codemeta")return new i.CodeMetadataValue(i.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new i.Struct(this.nativeToType("esdt"),[new i.Field(new i.TokenIdentifierValue(n[0]),"token_identifier"),new i.Field(new i.U64Value(BigInt(n[1])),"token_nonce"),new i.Field(new i.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof i.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof i.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof i.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof i.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof i.StringType)return"string";if(t instanceof i.U8Type)return"uint8";if(t instanceof i.U16Type)return"uint16";if(t instanceof i.U32Type)return"uint32";if(t instanceof i.U64Type)return"uint64";if(t instanceof i.BigUIntType)return"biguint";if(t instanceof i.BooleanType)return"bool";if(t instanceof i.AddressType)return"address";if(t instanceof i.TokenIdentifierType)return"token";if(t instanceof i.BytesType)return"hex";if(t instanceof i.CodeMetadataType)return"codemeta";if(t instanceof i.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var q=class{constructor(t){this.config=t}async getContract(t){try{let r=await y.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await y.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var M=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 q(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=h.Address.newFromBech32(this.config.userAddress),n=new h.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:a,args:o,value:p,transfers:d,data:u}=await this.getTxComponentsFromInputs(t,e,r),f=o.map(m=>this.serializer.stringToTyped(m));if(t.type==="transfer")return new h.TransferTransactionsFactory({config:n}).createTransactionForTransfer(r,{receiver:a,nativeAmount:p,tokenTransfers:d,data:u?new Uint8Array(u):void 0});if(t.type==="contract"&&a.isSmartContract())return new h.SmartContractTransactionsFactory({config:n}).createTransactionForExecute(r,{contract:a,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:f,tokenTransfers:d,nativeTransferAmount:p});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=await this.getAbiForAction(t),{args:n}=await this.getTxComponentsFromInputs(t,e),a=n.map(U=>this.serializer.stringToTyped(U)),o=y.getChainEntrypoint(this.config),p=h.Address.newFromBech32(t.address),d=o.createSmartContractController(r),u=d.createQuery({contract:p,function:t.func,arguments:a}),f=await d.runQuery(u);if(!(f.returnCode==="ok"))throw new Error(`WarpActionExecutor: Query failed with return code ${f.returnCode}`);let P=new h.ArgSerializer,R=r.getEndpoint(f.function),D=f.returnDataParts.map(U=>Buffer.from(U));return P.buffersToValues(D,R.output)[0]}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([a,o])=>{n.set(a,o)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),a=this.getModifiedInputs(n),o=a.find(T=>T.input.position==="receiver")?.value,p="address"in t?t.address:null,d=o?.split(":")[1]||p||r?.toBech32();if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let u=h.Address.newFromBech32(d),f=this.getPreparedArgs(t,a),m=a.find(T=>T.input.position==="value")?.value||null,P="value"in t?t.value:null,R=BigInt(m?.split(":")[1]||P||0),D=a.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),U=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...D?.map(T=>this.serializer.stringToNative(T)[1])||[]],st=a.find(T=>T.input.position==="data")?.value,ot="data"in t?t.data||"":null,J=st||ot||null,Z=J?this.serializer.stringToTyped(J).valueOf():null,ct=Z?Buffer.from(Z):null;return{destination:u,args:f,value:R,transfers:U,data:ct}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),a=(o,p)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):n[p]||null;return r.map((o,p)=>({input:o,value:a(o,p)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let a=Number(t.find(d=>d.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=F(o,+a);return{...e,value:`${e.input.type}:${p}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=F(a,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(l.ArgParamsSeparator,2);if(e==="esdt"){let[n,a,o,p]=r.split(l.ArgCompositeSeparator);if(p)return t;let d=new h.Token({identifier:n,nonce:BigInt(a)});if(!new h.TokenComputer().isFungible(d))return t;let m=it(n)?.decimals;if(!m){let R=this.config.chainApiUrl||w.Chain.ApiUrl(this.config.env);m=(await(await fetch(`${R}/tokens/${n}`)).json()).decimals}if(!m)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let P=new h.TokenTransfer({token:d,amount:F(o,m)});return this.serializer.nativeToString(e,P)+l.ArgCompositeSeparator+m}return t}catch{return t}}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 o=Number(n.position.split(":")[1])-1;r.splice(o,0,a)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return h.AbiRegistry.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(l.IdentifierType.Hash)){let e=new O(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 h.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return h.AbiRegistry.create(r)}}toTypedTransfer(t){return new h.TokenTransfer({token:new h.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var G=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"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,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Address as ct,TransactionsFactoryConfig as re,TransferTransactionsFactory as ne}from"@multiversx/sdk-core";import ie from"ajv";var C={Warp:"1.0.0",Brand:"0.1.0",Abi:"0.1.0"},f={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${C.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${C.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"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var w=s=>s==="devnet"?"D":s==="testnet"?"T":"1",b=s=>{if(s==="warp")return`warp:${C.Warp}`;if(s==="brand")return`brand:${C.Brand}`;if(s==="abi")return`abi:${C.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},_e=(s,t)=>s?.actions[t-1],x=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),S=(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 BigInt(s)},rt=(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};import{ApiNetworkProvider as Zt,DevnetEntrypoint as Xt,MainnetEntrypoint as Yt,TestnetEntrypoint as te}from"@multiversx/sdk-core";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import Jt from"qr-code-styling";import{Address as nt,TransactionsFactoryConfig as Qt,TransferTransactionsFactory as zt}from"@multiversx/sdk-core";var A={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},W=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};import jt from"ajv";var B=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||f.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new jt,a=i.compile(n);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var V=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:b("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Qt({chainID:w(this.config.env)}),r=new zt({config:e}),n=nt.newFromBech32(this.config.userAddress),i=JSON.stringify(t),a=r.createTransactionForTransfer(n,{receiver:nt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new B(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),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 new B(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return rt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as it,Address as T,AddressValue as at,BytesValue as m,SmartContractTransactionsFactory as Gt,TransactionsFactoryConfig as Kt}from"@multiversx/sdk-core/out";var $={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",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}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var P=class{constructor(t){this.cache=new W;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[m.fromHex(t),m.fromUTF8(e)]:[m.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromUTF8(t),m.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[m.fromUTF8(t)]}),o=await i.runQuery(a),[c]=i.parseQueryResponse(o),p=c?x(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getInfoByHash(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.fromHex(t)]}),o=await i.runQuery(a),[c]=i.parseQueryResponse(o),p=c?x(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;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 at(new T(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a);return o.map(x)}async getUserBrands(t){let e=t||this.config.userAddress;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 at(new T(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a),c=o.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}async fetchBrand(t,e){let r=A.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return T.newFromBech32(this.config.registryContract||f.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new Kt({chainID:w(this.config.env)}),e=it.create($);return new Gt({config:t,abi:e})}getController(){let t=g.getChainEntrypoint(this.config),e=it.create($);return t.createSmartContractController(e)}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(n)).filter(p=>p.match),o=a.length>0,c=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new V(this.config),a=new P(this.config),o=null,c=null,p=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:l,brand:d}=await a.getInfoByHash(n);c=l,p=d}catch{}}else if(r==="alias"){let{registryInfo:l,brand:d}=await a.getInfoByAlias(n);c=l,p=d,l&&(o=await i.createFromTransactionHash(l.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||f.DefaultClientUrl(this.config.env),n=t===u.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return f.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${u.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",a="#23F7DD"){let o=this.build(t,e);return new Jt({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=f.SuperClientUrls.includes(e.origin),n=e.searchParams.get(u.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return g.getInfoFromPrefixedIdentifier(a)}};var ee="https://",st="query",ot="env",g=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,a)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${st}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${st}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(i,c)}else if(typeof a=="string"&&a.startsWith(`${ot}:`)){let o=a.split(`${ot}:`)[1],c=e.vars?.[o];c&&n(i,c)}else n(i,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(u.IdentifierParamSeparator)?e:`${u.IdentifierType.Alias}${u.IdentifierParamSeparator}${e}`,[n,i]=r.split(u.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(ee))return t.next;{let r=new R(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getChainEntrypoint(t){return t.env==="devnet"?new Xt:t.env==="testnet"?new te:new Yt}static getConfiguredChainApi(t){let e=t.chainApiUrl||f.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Zt(e,{timeout:3e4,clientName:"warp-sdk"})}};var pt=class{constructor(t){this.pendingBrand={protocol:b("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new re({chainID:w(this.config.env)}),r=new ne({config:e}),n=ct.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:ct.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}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=g.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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.brandSchemaUrl||f.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new ie,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};import{Address as ae,AddressValue as se,BigUIntType as oe,BigUIntValue as ut,BooleanValue as ce,BytesValue as pe,CodeMetadata as ue,CodeMetadataValue as le,CompositeType as de,CompositeValue as ge,Field as O,FieldDefinition as L,List as fe,NothingValue as me,OptionalValue as q,OptionValue as D,StringValue as he,Struct as ye,StructType as we,TokenIdentifierType as Te,TokenIdentifierValue as lt,U16Value as We,U32Value as Ae,U64Type as Ce,U64Value as dt,U8Value as be,VariadicValue as Ie}from"@multiversx/sdk-core/out";var Or=(s,t)=>s?D.newProvided(s):t?D.newMissingTyped(t):D.newMissing(),Lr=(s,t)=>s?new q(s.getType(),s):t?new q(t):q.newMissing(),qr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new fe(t,s)},Dr=s=>Ie.fromItems(...s),_r=s=>{let t=s.map(e=>e.getType());return new ge(new de(...t),s)},Hr=s=>he.fromUTF8(s),jr=s=>new be(s),Qr=s=>new We(s),zr=s=>new Ae(s),Mr=s=>new dt(s),Gr=s=>new ut(BigInt(s)),Kr=s=>new ce(s),Jr=s=>new se(ae.newFromBech32(s)),Zr=s=>new lt(s),Xr=s=>pe.fromHex(s),Yr=s=>new ye(new we("EsdtTokenPayment",[new L("token_identifier","",new Te),new L("token_nonce","",new Ce),new L("amount","",new oe)]),[new O(new lt(s.token.identifier),"token_identifier"),new O(new dt(BigInt(s.token.nonce)),"token_nonce"),new O(new ut(BigInt(s.amount)),"amount")]),tn=s=>new le(ue.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),en=()=>new me;import{Address as Be,TransactionsFactoryConfig as ve,TransferTransactionsFactory as xe}from"@multiversx/sdk-core";var U=class{constructor(t){this.cache=new W;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new ve({chainID:w(this.config.env)}),r=new xe({config:e}),n={protocol:b("abi"),content:t},i=Be.newFromBech32(this.config.userAddress),a=JSON.stringify(n),o=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}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=A.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};import{AbiRegistry as X,Address as Y,ArgSerializer as Fe,SmartContractTransactionsFactory as Ne,Token as ke,TokenComputer as $e,TokenTransfer as $t,TransactionsFactoryConfig as Oe,TransferTransactionsFactory as Le}from"@multiversx/sdk-core";var Se=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],gt=s=>Se.find(t=>t.id===s)||null;import{Address as Ve,AddressType as ft,AddressValue as mt,BigUIntType as _,BigUIntValue as H,BooleanType as ht,BooleanValue as yt,BytesType as wt,BytesValue as Tt,CodeMetadata as Pe,CodeMetadataType as Wt,CodeMetadataValue as At,CompositeType as Ct,CompositeValue as bt,Field as j,FieldDefinition as Q,List as It,NothingValue as h,OptionalValue as z,OptionValue as M,StringType as Bt,StringValue as vt,Struct as Re,StructType as xt,Token as Ue,TokenIdentifierType as G,TokenIdentifierValue as K,TokenTransfer as St,U16Type as Vt,U16Value as Pt,U32Type as Rt,U32Value as Ut,U64Type as J,U64Value as Z,U8Type as Et,U8Value as Ft,VariadicType as Ee,VariadicValue as Nt}from"@multiversx/sdk-core/out";var kt=new RegExp(`${u.ArgParamsSeparator}(.*)`),E=class{nativeToString(t,e){return t==="esdt"&&e instanceof St?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(M.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(z.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(It.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Nt.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(bt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),i=r.join(u.ArgCompositeSeparator),a=n.join(u.ArgCompositeSeparator);return`composite(${i}):${a}`}if(t.hasClassOrSuperclass(H.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ft.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ut.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Z.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(vt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(yt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(mt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(At.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 Ct(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Bt;if(t==="uint8")return new Et;if(t==="uint16")return new Vt;if(t==="uint32")return new Rt;if(t==="uint64")return new J;if(t==="biguint")return new _;if(t==="bool")return new ht;if(t==="address")return new ft;if(t==="token")return new G;if(t==="hex")return new wt;if(t==="codemeta")return new Wt;if(t==="esdt"||t==="nft")return new xt("EsdtTokenPayment",[new Q("token_identifier","",new G),new Q("token_nonce","",new J),new Q("amount","",new _)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],n=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,a]=n.split(u.ArgParamsSeparator);return[`option:${i}`,a||null]}else if(r==="optional"){let[i,a]=n.split(u.ArgParamsSeparator);return[`optional:${i}`,a||null]}else if(r==="list"){let i=n.split(u.ArgParamsSeparator),a=i.slice(0,-1).join(u.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let i=n.split(u.ArgParamsSeparator),a=i.slice(0,-1).join(u.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=n.split(u.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${i[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,a,o]=n.split(u.ArgCompositeSeparator);return[r,new St({token:new Ue({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 h;if(e==="option"){let n=this.stringToTyped(r);return n instanceof h?M.newMissingTyped(n.getType()):M.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof h?z.newMissing():new z(n.getType(),n)}if(e==="list"){let[n,i]=r.split(kt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new It(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(kt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Nt(new Ee(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(u.ArgCompositeSeparator),a=n.split(u.ArgCompositeSeparator),o=i.map((p,l)=>this.stringToTyped(`${a[l]}:${p}`)),c=o.map(p=>p.getType());return new bt(new Ct(...c),o)}if(e==="string")return r?vt.fromUTF8(r):new h;if(e==="uint8")return r?new Ft(Number(r)):new h;if(e==="uint16")return r?new Pt(Number(r)):new h;if(e==="uint32")return r?new Ut(Number(r)):new h;if(e==="uint64")return r?new Z(BigInt(r)):new h;if(e==="biguint")return r?new H(BigInt(r)):new h;if(e==="bool")return r?new yt(typeof r=="boolean"?r:r==="true"):new h;if(e==="address")return r?new mt(Ve.newFromBech32(r)):new h;if(e==="token")return r?new K(r):new h;if(e==="hex")return r?Tt.fromHex(r):new h;if(e==="codemeta")return new At(Pe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(u.ArgCompositeSeparator);return new Re(this.nativeToType("esdt"),[new j(new K(n[0]),"token_identifier"),new j(new Z(BigInt(n[1])),"token_nonce"),new j(new H(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof Bt)return"string";if(t instanceof Et)return"uint8";if(t instanceof Vt)return"uint16";if(t instanceof Rt)return"uint32";if(t instanceof J)return"uint64";if(t instanceof _)return"biguint";if(t instanceof ht)return"bool";if(t instanceof ft)return"address";if(t instanceof G)return"token";if(t instanceof wt)return"hex";if(t instanceof Wt)return"codemeta";if(t instanceof xt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var F=class{constructor(t){this.config=t}async getContract(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var Ot=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 E,this.contractLoader=new F(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Y.newFromBech32(this.config.userAddress),n=new Oe({chainID:w(this.config.env)}),{destination:i,args:a,value:o,transfers:c,data:p}=await this.getTxComponentsFromInputs(t,e,r),l=a.map(d=>this.serializer.stringToTyped(d));if(t.type==="transfer")return new Le({config:n}).createTransactionForTransfer(r,{receiver:i,nativeAmount:o,tokenTransfers:c,data:p?new Uint8Array(p):void 0});if(t.type==="contract"&&i.isSmartContract())return new Ne({config:n}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:c,nativeTransferAmount:o});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error("WarpActionExecutor: Invalid action type")}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=await this.getAbiForAction(t),{args:n}=await this.getTxComponentsFromInputs(t,e),i=n.map(I=>this.serializer.stringToTyped(I)),a=g.getChainEntrypoint(this.config),o=Y.newFromBech32(t.address),c=a.createSmartContractController(r),p=c.createQuery({contract:o,function:t.func,arguments:i}),l=await c.runQuery(p);if(!(l.returnCode==="ok"))throw new Error(`WarpActionExecutor: Query failed with return code ${l.returnCode}`);let v=new Fe,N=r.getEndpoint(l.function),k=l.returnDataParts.map(I=>Buffer.from(I));return v.buffersToValues(k,N.output)[0]}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,a])=>{n.set(i,a)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),a=i.find(y=>y.input.position==="receiver")?.value,o="address"in t?t.address:null,c=a?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=Y.newFromBech32(c),l=this.getPreparedArgs(t,i),d=i.find(y=>y.input.position==="value")?.value||null,v="value"in t?t.value:null,N=BigInt(d?.split(":")[1]||v||0),k=i.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),I=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...k?.map(y=>this.serializer.stringToNative(y)[1])||[]],Dt=i.find(y=>y.input.position==="data")?.value,_t="data"in t?t.data||"":null,tt=Dt||_t||null,et=tt?this.serializer.stringToTyped(tt).valueOf():null,Ht=et?Buffer.from(et):null;return{destination:p,args:l,value:N,transfers:I,data:Ht}}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=S(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=S(i,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(a=>this.preprocessInput(a))),i=(a,o)=>a.source==="query"?this.serializer.nativeToString(a.type,this.url.searchParams.get(a.name)||""):n[o]||null;return r.map((a,o)=>({input:a,value:i(a,o)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,n]=t.split(u.ArgCompositeSeparator);if(n)return t;let i=r;if(!new $e().isFungible(i.token))return t;let c=gt(i.token.identifier)?.decimals;if(!c){let l=this.config.chainApiUrl||f.Chain.ApiUrl(this.config.env);c=(await(await fetch(`${l}/tokens/${i.token.identifier}`)).json()).decimals}if(!c)throw new Error(`WarpActionExecutor: Decimals not found for token ${i.token.identifier}`);let p=new $t({token:i.token,amount:S(i.amount,c)});return this.serializer.nativeToString(e,p)+u.ArgCompositeSeparator+c}return t}catch{return t}}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}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return X.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(u.IdentifierType.Hash)){let e=new U(this.config),r=t.abi.split(u.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return X.create(n.content)}else{let r=await(await fetch(t.abi)).json();return X.create(r)}}toTypedTransfer(t){return new $t({token:new ke({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Lt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"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{pt as BrandBuilder,A as CacheKey,f as Config,U as WarpAbiBuilder,Ot as WarpActionExecutor,E as WarpArgSerializer,V as WarpBuilder,W as WarpCache,u as WarpConstants,F as WarpContractLoader,Lt as WarpIndex,R as WarpLink,C as WarpProtocolVersions,P as WarpRegistry,g as WarpUtils,B as WarpValidator,Jr as address,Gr as biguint,Kr as boolean,tn as codemeta,_r as composite,Yr as esdt,w as getChainId,b as getLatestProtocolIdentifier,_e as getWarpActionByIndex,Xr as hex,qr as list,en as nothing,Or as option,Lr as optional,S as shiftBigintBy,Hr as string,rt as toPreviewText,x as toTypedRegistryInfo,Zr as token,Qr as u16,zr as u32,Mr as u64,jr as u8,Dr as variadic};
1
+ import{Address as pt,TransactionsFactoryConfig as ie,TransferTransactionsFactory as ae}from"@multiversx/sdk-core";import se from"ajv";var C={Warp:"1.0.0",Brand:"0.1.0",Abi:"0.1.0"},f={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${C.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${C.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"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var w=s=>s==="devnet"?"D":s==="testnet"?"T":"1",b=s=>{if(s==="warp")return`warp:${C.Warp}`;if(s==="brand")return`brand:${C.Brand}`;if(s==="abi")return`abi:${C.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},Qe=(s,t)=>s?.actions[t-1],V=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),P=(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 BigInt(s)},nt=(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};import{ApiNetworkProvider as Yt,DevnetEntrypoint as te,MainnetEntrypoint as ee,TestnetEntrypoint as re}from"@multiversx/sdk-core";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import Xt from"qr-code-styling";import{Address as it,TransactionsFactoryConfig as Mt,TransferTransactionsFactory as Gt}from"@multiversx/sdk-core";var A={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},W=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};import zt from"ajv";var S=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||f.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new zt,a=i.compile(n);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var R=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:b("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Mt({chainID:w(this.config.env)}),r=new Gt({config:e}),n=it.newFromBech32(this.config.userAddress),i=JSON.stringify(t),a=r.createTransactionForTransfer(n,{receiver:it.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new S(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),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 new S(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return nt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as at,Address as T,AddressValue as st,BytesValue as m,SmartContractTransactionsFactory as Jt,TransactionsFactoryConfig as Zt}from"@multiversx/sdk-core/out";var k={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",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}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var U=class{constructor(t){this.cache=new W;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[m.fromHex(t),m.fromUTF8(e)]:[m.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromUTF8(t),m.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[m.fromUTF8(t)]}),o=await i.runQuery(a),[p]=i.parseQueryResponse(o),c=p?V(p):null,l=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:l},e.ttl),{registryInfo:c,brand:l}}async getInfoByHash(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.fromHex(t)]}),o=await i.runQuery(a),[p]=i.parseQueryResponse(o),c=p?V(p):null,l=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:l},e.ttl),{registryInfo:c,brand:l}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;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 st(new T(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a);return o.map(V)}async getUserBrands(t){let e=t||this.config.userAddress;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 st(new T(e))]}),a=await n.runQuery(i),[o]=n.parseQueryResponse(a),p=o.map(d=>d.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(d=>this.fetchBrand(d,c)))).filter(d=>d!==null)}async fetchBrand(t,e){let r=A.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return T.newFromBech32(this.config.registryContract||f.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new Zt({chainID:w(this.config.env)}),e=at.create(k);return new Jt({config:t,abi:e})}getController(){let t=g.getChainEntrypoint(this.config),e=at.create(k);return t.createSmartContractController(e)}};var E=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(n)).filter(c=>c.match),o=a.length>0,p=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t){let e=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new R(this.config),a=new U(this.config),o=null,p=null,c=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:l,brand:d}=await a.getInfoByHash(n);p=l,c=d}catch{}}else if(r==="alias"){let{registryInfo:l,brand:d}=await a.getInfoByAlias(n);p=l,c=d,l&&(o=await i.createFromTransactionHash(l.hash))}return o?{match:!0,url:t,warp:o,registryInfo:p,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||f.DefaultClientUrl(this.config.env),n=t===u.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return f.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${u.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",a="#23F7DD"){let o=this.build(t,e);return new Xt({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=f.SuperClientUrls.includes(e.origin),n=e.searchParams.get(u.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return g.getInfoFromPrefixedIdentifier(a)}};var ne="https://",ot="query",ct="env",g=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,a)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${ot}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${ot}:`)[1],p=new URL(e.currentUrl).searchParams.get(o);p&&n(i,p)}else if(typeof a=="string"&&a.startsWith(`${ct}:`)){let o=a.split(`${ct}:`)[1],p=e.vars?.[o];p&&n(i,p)}else n(i,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(u.IdentifierParamSeparator)?e:`${u.IdentifierType.Alias}${u.IdentifierParamSeparator}${e}`,[n,i]=r.split(u.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(ne))return t.next;{let r=new E(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getChainEntrypoint(t){return t.env==="devnet"?new te:t.env==="testnet"?new re:new ee}static getConfiguredChainApi(t){let e=t.chainApiUrl||f.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Yt(e,{timeout:3e4,clientName:"warp-sdk"})}};var ut=class{constructor(t){this.pendingBrand={protocol:b("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new ie({chainID:w(this.config.env)}),r=new ae({config:e}),n=pt.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:pt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}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=g.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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.brandSchemaUrl||f.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new se,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};import{Address as oe,AddressValue as ce,BigUIntType as pe,BigUIntValue as lt,BooleanValue as ue,BytesValue as le,CodeMetadata as de,CodeMetadataValue as ge,CompositeType as fe,CompositeValue as me,Field as O,FieldDefinition as L,List as he,NothingValue as ye,OptionalValue as q,OptionValue as D,StringValue as we,Struct as Te,StructType as We,TokenIdentifierType as Ae,TokenIdentifierValue as dt,U16Value as Ce,U32Value as be,U64Type as Ie,U64Value as gt,U8Value as Be,VariadicValue as ve}from"@multiversx/sdk-core/out";var Dr=(s,t)=>s?D.newProvided(s):t?D.newMissingTyped(t):D.newMissing(),_r=(s,t)=>s?new q(s.getType(),s):t?new q(t):q.newMissing(),Hr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new he(t,s)},jr=s=>ve.fromItems(...s),Qr=s=>{let t=s.map(e=>e.getType());return new me(new fe(...t),s)},zr=s=>we.fromUTF8(s),Mr=s=>new Be(s),Gr=s=>new Ce(s),Kr=s=>new be(s),Jr=s=>new gt(s),Zr=s=>new lt(BigInt(s)),Xr=s=>new ue(s),Yr=s=>new ce(oe.newFromBech32(s)),tn=s=>new dt(s),en=s=>le.fromHex(s),rn=s=>new Te(new We("EsdtTokenPayment",[new L("token_identifier","",new Ae),new L("token_nonce","",new Ie),new L("amount","",new pe)]),[new O(new dt(s.token.identifier),"token_identifier"),new O(new gt(BigInt(s.token.nonce)),"token_nonce"),new O(new lt(BigInt(s.amount)),"amount")]),nn=s=>new ge(de.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),an=()=>new ye;import{Address as Se,TransactionsFactoryConfig as xe,TransferTransactionsFactory as Ve}from"@multiversx/sdk-core";var F=class{constructor(t){this.cache=new W;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new xe({chainID:w(this.config.env)}),r=new Ve({config:e}),n={protocol:b("abi"),content:t},i=Se.newFromBech32(this.config.userAddress),a=JSON.stringify(n),o=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}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=A.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};import{AbiRegistry as X,Address as Y,ArgSerializer as Oe,SmartContractTransactionsFactory as Le,Token as Lt,TokenComputer as qe,TokenTransfer as qt,TransactionsFactoryConfig as De,TransferTransactionsFactory as _e}from"@multiversx/sdk-core";var Pe=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ft=s=>Pe.find(t=>t.id===s)||null;import{Address as Re,AddressType as mt,AddressValue as ht,BigUIntType as _,BigUIntValue as H,BooleanType as yt,BooleanValue as wt,BytesType as Tt,BytesValue as Wt,CodeMetadata as Ue,CodeMetadataType as At,CodeMetadataValue as Ct,CompositeType as bt,CompositeValue as It,Field as j,FieldDefinition as Q,List as Bt,ListType as Ee,NothingValue as h,OptionalType as Fe,OptionalValue as z,OptionType as $e,OptionValue as M,StringType as vt,StringValue as St,Struct as Ne,StructType as xt,Token as ke,TokenIdentifierType as G,TokenIdentifierValue as K,TokenTransfer as Vt,U16Type as Pt,U16Value as Rt,U32Type as Ut,U32Value as Et,U64Type as J,U64Value as Z,U8Type as Ft,U8Value as $t,VariadicType as Nt,VariadicValue as kt}from"@multiversx/sdk-core/out";var Ot=new RegExp(`${u.ArgParamsSeparator}(.*)`),$=class{nativeToString(t,e){return t==="esdt"&&e instanceof Vt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(M.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(z.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Bt.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(kt.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(It.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),i=r.join(u.ArgCompositeSeparator),a=n.join(u.ArgCompositeSeparator);return`composite(${i}):${a}`}if(t.hasClassOrSuperclass(H.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass($t.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Rt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Et.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Z.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(St.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(wt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(ht.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Wt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Ct.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 bt(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new vt;if(t==="uint8")return new Ft;if(t==="uint16")return new Pt;if(t==="uint32")return new Ut;if(t==="uint64")return new J;if(t==="biguint")return new _;if(t==="bool")return new yt;if(t==="address")return new mt;if(t==="token")return new G;if(t==="hex")return new Tt;if(t==="codemeta")return new At;if(t==="esdt"||t==="nft")return new xt("EsdtTokenPayment",[new Q("token_identifier","",new G),new Q("token_nonce","",new J),new Q("amount","",new _)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],n=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,a]=n.split(u.ArgParamsSeparator);return[`option:${i}`,a||null]}else if(r==="optional"){let[i,a]=n.split(u.ArgParamsSeparator);return[`optional:${i}`,a||null]}else if(r==="list"){let i=n.split(u.ArgParamsSeparator),a=i.slice(0,-1).join(u.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`list:${a}`,c]}else if(r==="variadic"){let i=n.split(u.ArgParamsSeparator),a=i.slice(0,-1).join(u.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`variadic:${a}`,c]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=n.split(u.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,a,o]=n.split(u.ArgCompositeSeparator);return[r,new Vt({token:new ke({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 h;if(e==="option"){let n=this.stringToTyped(r);return n instanceof h?M.newMissingTyped(n.getType()):M.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof h?z.newMissing():new z(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Ot,2),o=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new Bt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Ot,2),o=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new kt(new Nt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(u.ArgCompositeSeparator),a=n.split(u.ArgCompositeSeparator),o=i.map((c,l)=>this.stringToTyped(`${a[l]}:${c}`)),p=o.map(c=>c.getType());return new It(new bt(...p),o)}if(e==="string")return r?St.fromUTF8(r):new h;if(e==="uint8")return r?new $t(Number(r)):new h;if(e==="uint16")return r?new Rt(Number(r)):new h;if(e==="uint32")return r?new Et(Number(r)):new h;if(e==="uint64")return r?new Z(BigInt(r)):new h;if(e==="biguint")return r?new H(BigInt(r)):new h;if(e==="bool")return r?new wt(typeof r=="boolean"?r:r==="true"):new h;if(e==="address")return r?new ht(Re.newFromBech32(r)):new h;if(e==="token")return r?new K(r):new h;if(e==="hex")return r?Wt.fromHex(r):new h;if(e==="codemeta")return new Ct(Ue.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(u.ArgCompositeSeparator);return new Ne(this.nativeToType("esdt"),[new j(new K(n[0]),"token_identifier"),new j(new Z(BigInt(n[1])),"token_nonce"),new j(new H(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof $e)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Fe)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ee)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Nt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof vt)return"string";if(t instanceof Ft)return"uint8";if(t instanceof Pt)return"uint16";if(t instanceof Ut)return"uint32";if(t instanceof J)return"uint64";if(t instanceof _)return"biguint";if(t instanceof yt)return"bool";if(t instanceof mt)return"address";if(t instanceof G)return"token";if(t instanceof Tt)return"hex";if(t instanceof At)return"codemeta";if(t instanceof xt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var N=class{constructor(t){this.config=t}async getContract(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),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 N(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Y.newFromBech32(this.config.userAddress),n=new De({chainID:w(this.config.env)}),{destination:i,args:a,value:o,transfers:p,data:c}=await this.getTxComponentsFromInputs(t,e,r),l=a.map(d=>this.serializer.stringToTyped(d));if(t.type==="transfer")return new _e({config:n}).createTransactionForTransfer(r,{receiver:i,nativeAmount:o,tokenTransfers:p,data:c?new Uint8Array(c):void 0});if(t.type==="contract"&&i.isSmartContract())return new Le({config:n}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:p,nativeTransferAmount:o});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=await this.getAbiForAction(t),{args:n}=await this.getTxComponentsFromInputs(t,e),i=n.map(v=>this.serializer.stringToTyped(v)),a=g.getChainEntrypoint(this.config),o=Y.newFromBech32(t.address),p=a.createSmartContractController(r),c=p.createQuery({contract:o,function:t.func,arguments:i}),l=await p.runQuery(c);if(!(l.returnCode==="ok"))throw new Error(`WarpActionExecutor: Query failed with return code ${l.returnCode}`);let I=new Oe,B=r.getEndpoint(l.function),x=l.returnDataParts.map(v=>Buffer.from(v));return I.buffersToValues(x,B.output)[0]}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,a])=>{n.set(i,a)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),a=i.find(y=>y.input.position==="receiver")?.value,o="address"in t?t.address:null,p=a?.split(":")[1]||o||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let c=Y.newFromBech32(p),l=this.getPreparedArgs(t,i),d=i.find(y=>y.input.position==="value")?.value||null,I="value"in t?t.value:null,B=BigInt(d?.split(":")[1]||I||0),x=i.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),v=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...x?.map(y=>this.serializer.stringToNative(y)[1])||[]],Ht=i.find(y=>y.input.position==="data")?.value,jt="data"in t?t.data||"":null,et=Ht||jt||null,rt=et?this.serializer.stringToTyped(et).valueOf():null,Qt=rt?Buffer.from(rt):null;return{destination:c,args:l,value:B,transfers:v,data:Qt}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(a=>this.preprocessInput(a))),i=(a,o)=>a.source==="query"?this.serializer.nativeToString(a.type,this.url.searchParams.get(a.name)||""):n[o]||null;return r.map((a,o)=>({input:a,value:i(a,o)}))}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(p=>p.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=P(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=P(i,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(u.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,a,o]=r.split(u.ArgCompositeSeparator);if(o)return t;let p=new Lt({identifier:n,nonce:BigInt(i)});if(!new qe().isFungible(p))return t;let d=ft(n)?.decimals;if(!d){let B=this.config.chainApiUrl||f.Chain.ApiUrl(this.config.env);d=(await(await fetch(`${B}/tokens/${n}`)).json()).decimals}if(!d)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let I=new qt({token:p,amount:P(a,d)});return this.serializer.nativeToString(e,I)+u.ArgCompositeSeparator+d}return t}catch{return t}}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}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return X.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(u.IdentifierType.Hash)){let e=new F(this.config),r=t.abi.split(u.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return X.create(n.content)}else{let r=await(await fetch(t.abi)).json();return X.create(r)}}toTypedTransfer(t){return new qt({token:new Lt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var _t=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"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{ut as BrandBuilder,A as CacheKey,f as Config,F as WarpAbiBuilder,Dt as WarpActionExecutor,$ as WarpArgSerializer,R as WarpBuilder,W as WarpCache,u as WarpConstants,N as WarpContractLoader,_t as WarpIndex,E as WarpLink,C as WarpProtocolVersions,U as WarpRegistry,g as WarpUtils,S as WarpValidator,Yr as address,Zr as biguint,Xr as boolean,nn as codemeta,Qr as composite,rn as esdt,w as getChainId,b as getLatestProtocolIdentifier,Qe as getWarpActionByIndex,en as hex,Hr as list,an as nothing,Dr as option,_r as optional,P as shiftBigintBy,zr as string,nt as toPreviewText,V as toTypedRegistryInfo,tn as token,Gr as u16,Kr as u32,Jr as u64,Mr as u8,jr as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "1.0.3",
3
+ "version": "1.1.1",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",