@vleap/warps 3.0.0-alpha.34 → 3.0.0-alpha.35
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 +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -529,8 +529,12 @@ declare class WarpBrandBuilder {
|
|
|
529
529
|
|
|
530
530
|
declare class WarpBuilder {
|
|
531
531
|
private config;
|
|
532
|
+
private adapterBuilder;
|
|
532
533
|
private pendingWarp;
|
|
533
534
|
constructor(config: WarpInitConfig);
|
|
535
|
+
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
536
|
+
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
537
|
+
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
534
538
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
535
539
|
setName(name: string): WarpBuilder;
|
|
536
540
|
setTitle(title: string): WarpBuilder;
|
package/dist/index.d.ts
CHANGED
|
@@ -529,8 +529,12 @@ declare class WarpBrandBuilder {
|
|
|
529
529
|
|
|
530
530
|
declare class WarpBuilder {
|
|
531
531
|
private config;
|
|
532
|
+
private adapterBuilder;
|
|
532
533
|
private pendingWarp;
|
|
533
534
|
constructor(config: WarpInitConfig);
|
|
535
|
+
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
536
|
+
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
537
|
+
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
534
538
|
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
535
539
|
setName(name: string): WarpBuilder;
|
|
536
540
|
setTitle(title: string): WarpBuilder;
|
package/dist/index.js
CHANGED
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
self.postMessage({ error: error.toString() });
|
|
9
9
|
}
|
|
10
10
|
};
|
|
11
|
-
`],{type:"application/javascript"}),s=URL.createObjectURL(i),a=new Worker(s);a.onmessage=function(o){o.data.error?n(new Error(o.data.error)):e(o.data.result),a.terminate(),URL.revokeObjectURL(s)},a.onerror=function(o){n(new Error(`Error in transform: ${o.message}`)),a.terminate(),URL.revokeObjectURL(s)},a.postMessage(r)}catch(i){return n(i)}})});var Or={};V(Or,{CacheTtl:()=>Vr,KnownTokens:()=>nr,WarpBrandBuilder:()=>M,WarpBuilder:()=>D,WarpCache:()=>H,WarpCacheKey:()=>Lr,WarpConfig:()=>u,WarpConstants:()=>p,WarpIndex:()=>F,WarpInputTypes:()=>h,WarpInterpolator:()=>E,WarpLinkBuilder:()=>A,WarpLinkDetecter:()=>G,WarpLogger:()=>y,WarpProtocolVersions:()=>I,WarpSerializer:()=>T,WarpValidator:()=>R,address:()=>Nr,applyResultsToMessages:()=>hr,biguint:()=>$r,boolean:()=>Ur,evaluateResultsCommon:()=>tr,extractCollectResults:()=>br,extractIdentifierInfoFromUrl:()=>w,findKnownTokenById:()=>Ar,getChainExplorerUrl:()=>fr,getLatestProtocolIdentifier:()=>S,getMainChainInfo:()=>U,getNextInfo:()=>yr,getWarpActionByIndex:()=>O,getWarpInfoFromIdentifier:()=>v,hex:()=>qr,parseResultsOutIndex:()=>er,replacePlaceholders:()=>N,shiftBigintBy:()=>mr,string:()=>Tr,toPreviewText:()=>k,toTypedChainInfo:()=>gr,u16:()=>Br,u32:()=>Pr,u64:()=>Er,u8:()=>Rr});module.exports=dr(Or);var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:t=>t.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:t=>t.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:t=>t.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},h={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var I={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},u={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:t=>t==="devnet"?"https://devnet.usewarp.to":t==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:t=>t==="devnet"?"https://devnet-api.multiversx.com":t==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:t=>t==="devnet"?"https://devnet-explorer.multiversx.com":t==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:t=>6e3,AddressHrp:"erd",ChainId:t=>t==="devnet"?"D":t==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:t=>t==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":t==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",p.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var U=t=>({name:u.MainChain.Name,displayName:u.MainChain.DisplayName,chainId:u.MainChain.ChainId(t.env),blockTime:u.MainChain.BlockTime(t.env),addressHrp:u.MainChain.AddressHrp,apiUrl:u.MainChain.ApiUrl(t.env),explorerUrl:u.MainChain.ExplorerUrl(t.env),nativeToken:u.MainChain.NativeToken}),fr=(t,r)=>t.explorerUrl+(r?"/"+r:""),S=t=>{if(t==="warp")return`warp:${I.Warp}`;if(t==="brand")return`brand:${I.Brand}`;if(t==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${t}`)},O=(t,r)=>t?.actions[r-1],gr=t=>({name:t.name.toString(),displayName:t.display_name.toString(),chainId:t.chain_id.toString(),blockTime:t.block_time.toNumber(),addressHrp:t.address_hrp.toString(),apiUrl:t.api_url.toString(),explorerUrl:t.explorer_url.toString(),nativeToken:t.native_token.toString()}),mr=(t,r)=>{let e=t.toString(),[n,i=""]=e.split("."),s=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(s,"0"));if(r<0){let a=n+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},k=(t,r=100)=>{if(!t)return"";let e=t.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},N=(t,r)=>t.replace(/\{\{([^}]+)\}\}/g,(e,n)=>r[n]||""),hr=(t,r)=>{let e=Object.entries(t.messages||{}).map(([n,i])=>[n,N(i,r)]);return Object.fromEntries(e)};var v=t=>{let r=decodeURIComponent(t);if(r.includes(p.IdentifierParamSeparator)){let[n,i]=r.split(p.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}let e=r.split("?")[0];return e.length===64?{type:p.IdentifierType.Hash,identifier:r,identifierBase:e}:{type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},w=t=>{let r=new URL(t),e=u.SuperClientUrls.includes(r.origin),n=r.searchParams.get(p.IdentifierParamName),i=e&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return v(s)};var X=L(require("qr-code-styling"));var A=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!w(r):!1}build(r,e){let n=this.config.clientUrl||u.DefaultClientUrl(this.config.env),i=r===p.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(r+p.IdentifierParamSeparator+e);return u.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${p.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let e=v(r);return e?this.build(e.type,e.identifierBase):""}generateQrCode(r,e,n=512,i="white",s="black",a="#23F7DD"){let o=this.build(r,e);return new X.default({type:"svg",width:n,height:n,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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>`})}};var Wr="https://",yr=(t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(Wr))return[{identifier:null,url:i}];let[s,a]=i.split("?");if(!a)return[{identifier:s,url:j(s,t)}];let o=a.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let g=N(a,{...r.vars,...n}),m=g?`${s}?${g}`:s;return[{identifier:m,url:j(m,t)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),d=l?l[1]:null;if(!d||n[d]===void 0)return[];let W=Array.isArray(n[d])?n[d]:[n[d]];if(W.length===0)return[];let f=o.filter(g=>g.includes(`{{${d}[]`)).map(g=>{let m=g.match(/\[\](\.[^}]+)?}}/),C=m&&m[1]||"";return{placeholder:g,field:C?C.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(g=>{let m=a;for(let{regex:sr,field:J}of f){let q=J?vr(g,J):g;if(q==null)return null;m=m.replace(sr,q)}if(m.includes("{{")||m.includes("}}"))return null;let C=m?`${s}?${m}`:s;return{identifier:C,url:j(C,t)}}).filter(g=>g!==null)},j=(t,r)=>{let[e,n]=t.split("?"),i=v(e)||{type:"alias",identifier:e,identifierBase:e},a=new A(r).build(i.type,i.identifierBase);if(!n)return a;let o=new URL(a);return new URLSearchParams(n).forEach((c,l)=>o.searchParams.set(l,c)),o.toString().replace(/\/\?/,"?")},vr=(t,r)=>r.split(".").reduce((e,n)=>e?.[n],t);var b=class b{static info(...r){b.isTestEnv||console.info(...r)}static warn(...r){b.isTestEnv||console.warn(...r)}static error(...r){b.isTestEnv||console.error(...r)}};b.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=b;var T=class{nativeToString(r,e){return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(p.ArgParamsSeparator),n=e[0],i=e.slice(1).join(p.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[s,a]=i.split(p.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(n==="optional"){let[s,a]=i.split(p.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(n==="list"){let s=i.split(p.ArgParamsSeparator),a=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`list:${a}`,l]}else if(n==="variadic"){let s=i.split(p.ArgParamsSeparator),a=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`variadic:${a}`,l]}else if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[1]);return[n,o]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[s,a,o]=i.split(p.ArgCompositeSeparator);return[n,`${s}|${a}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var br=async(t,r,e,n)=>{let i=[],s={};for(let[a,o]of Object.entries(t.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let c=er(o);if(c!==null&&c!==e){s[a]=null;continue}let[l,...d]=o.split("."),W=(f,K)=>K.reduce((g,m)=>g&&g[m]!==void 0?g[m]:null,f);if(l==="out"||l.startsWith("out[")){let f=d.length===0?r?.data||r:W(r,d);i.push(f),s[a]=f}else s[a]=o}return{values:i,results:await tr(t,s,e,n)}},tr=async(t,r,e,n)=>{if(!t.results)return r;let i={...r};return i=Cr(i,t,e,n),i=await Sr(t,i),i},Cr=(t,r,e,n)=>{let i={...t},s=O(r,e)?.inputs||[],a=new T;for(let[o,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],d=s.findIndex(f=>f.as===l||f.name===l),W=d!==-1?n[d]?.value:null;i[o]=W?a.stringToNative(W)[1]:null}return i},Sr=async(t,r)=>{if(!t.results)return r;let e={...r},n=Object.entries(t.results).filter(([,i])=>i.startsWith(p.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(p.Transform.Prefix.length)}));for(let{key:i,code:s}of n)try{let a;typeof window>"u"?a=(await Promise.resolve().then(()=>(Y(),_))).runInVm:a=(await Promise.resolve().then(()=>(rr(),Z))).runInVm,e[i]=await a(s,e)}catch(a){y.error(`Transform error for result '${i}':`,a),e[i]=null}return e},er=t=>{if(t==="out")return 1;let r=t.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(t.startsWith("out.")||t.startsWith("event."),null)};var nr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Ar=t=>nr.find(r=>r.id===t)||null;var Tr=t=>`${h.String}:${t}`,Rr=t=>`${h.U8}:${t}`,Br=t=>`${h.U16}:${t}`,Pr=t=>`${h.U32}:${t}`,Er=t=>`${h.U64}:${t}`,$r=t=>`${h.Biguint}:${t}`,Ur=t=>`${h.Boolean}:${t}`,Nr=t=>`${h.Address}:${t}`,qr=t=>`${h.Hex}:${t}`;var ir=L(require("ajv"));var M=class{constructor(r){this.pendingBrand={protocol:S("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let n=JSON.parse(r);return e&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||u.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new ir.default,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var ar=L(require("ajv"));var R=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(a=>a.type==="contract"),n=r.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||u.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new ar.default({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var D=class{constructor(r){this.pendingWarp={protocol:S("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=r}async createFromRaw(r,e=!0){let n=JSON.parse(r);return e&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,e=100){return k(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let n=await new R(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
12
|
-
`))}};var
|
|
11
|
+
`],{type:"application/javascript"}),s=URL.createObjectURL(i),a=new Worker(s);a.onmessage=function(o){o.data.error?n(new Error(o.data.error)):e(o.data.result),a.terminate(),URL.revokeObjectURL(s)},a.onerror=function(o){n(new Error(`Error in transform: ${o.message}`)),a.terminate(),URL.revokeObjectURL(s)},a.postMessage(r)}catch(i){return n(i)}})});var Or={};V(Or,{CacheTtl:()=>Vr,KnownTokens:()=>nr,WarpBrandBuilder:()=>M,WarpBuilder:()=>D,WarpCache:()=>H,WarpCacheKey:()=>Lr,WarpConfig:()=>u,WarpConstants:()=>p,WarpIndex:()=>F,WarpInputTypes:()=>h,WarpInterpolator:()=>E,WarpLinkBuilder:()=>A,WarpLinkDetecter:()=>G,WarpLogger:()=>y,WarpProtocolVersions:()=>I,WarpSerializer:()=>S,WarpValidator:()=>B,address:()=>Nr,applyResultsToMessages:()=>hr,biguint:()=>$r,boolean:()=>Ur,evaluateResultsCommon:()=>tr,extractCollectResults:()=>Cr,extractIdentifierInfoFromUrl:()=>w,findKnownTokenById:()=>Ar,getChainExplorerUrl:()=>fr,getLatestProtocolIdentifier:()=>T,getMainChainInfo:()=>U,getNextInfo:()=>yr,getWarpActionByIndex:()=>O,getWarpInfoFromIdentifier:()=>v,hex:()=>qr,parseResultsOutIndex:()=>er,replacePlaceholders:()=>N,shiftBigintBy:()=>gr,string:()=>Sr,toPreviewText:()=>k,toTypedChainInfo:()=>mr,u16:()=>Rr,u32:()=>Pr,u64:()=>Er,u8:()=>Br});module.exports=dr(Or);var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:t=>t.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:t=>t.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:t=>t.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},h={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var I={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},u={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:t=>t==="devnet"?"https://devnet.usewarp.to":t==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:t=>t==="devnet"?"https://devnet-api.multiversx.com":t==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:t=>t==="devnet"?"https://devnet-explorer.multiversx.com":t==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:t=>6e3,AddressHrp:"erd",ChainId:t=>t==="devnet"?"D":t==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:t=>t==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":t==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",p.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var U=t=>({name:u.MainChain.Name,displayName:u.MainChain.DisplayName,chainId:u.MainChain.ChainId(t.env),blockTime:u.MainChain.BlockTime(t.env),addressHrp:u.MainChain.AddressHrp,apiUrl:u.MainChain.ApiUrl(t.env),explorerUrl:u.MainChain.ExplorerUrl(t.env),nativeToken:u.MainChain.NativeToken}),fr=(t,r)=>t.explorerUrl+(r?"/"+r:""),T=t=>{if(t==="warp")return`warp:${I.Warp}`;if(t==="brand")return`brand:${I.Brand}`;if(t==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${t}`)},O=(t,r)=>t?.actions[r-1],mr=t=>({name:t.name.toString(),displayName:t.display_name.toString(),chainId:t.chain_id.toString(),blockTime:t.block_time.toNumber(),addressHrp:t.address_hrp.toString(),apiUrl:t.api_url.toString(),explorerUrl:t.explorer_url.toString(),nativeToken:t.native_token.toString()}),gr=(t,r)=>{let e=t.toString(),[n,i=""]=e.split("."),s=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(s,"0"));if(r<0){let a=n+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},k=(t,r=100)=>{if(!t)return"";let e=t.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},N=(t,r)=>t.replace(/\{\{([^}]+)\}\}/g,(e,n)=>r[n]||""),hr=(t,r)=>{let e=Object.entries(t.messages||{}).map(([n,i])=>[n,N(i,r)]);return Object.fromEntries(e)};var v=t=>{let r=decodeURIComponent(t);if(r.includes(p.IdentifierParamSeparator)){let[n,i]=r.split(p.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}let e=r.split("?")[0];return e.length===64?{type:p.IdentifierType.Hash,identifier:r,identifierBase:e}:{type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},w=t=>{let r=new URL(t),e=u.SuperClientUrls.includes(r.origin),n=r.searchParams.get(p.IdentifierParamName),i=e&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return v(s)};var X=L(require("qr-code-styling"));var A=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!w(r):!1}build(r,e){let n=this.config.clientUrl||u.DefaultClientUrl(this.config.env),i=r===p.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(r+p.IdentifierParamSeparator+e);return u.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${p.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let e=v(r);return e?this.build(e.type,e.identifierBase):""}generateQrCode(r,e,n=512,i="white",s="black",a="#23F7DD"){let o=this.build(r,e);return new X.default({type:"svg",width:n,height:n,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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>`})}};var Wr="https://",yr=(t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(Wr))return[{identifier:null,url:i}];let[s,a]=i.split("?");if(!a)return[{identifier:s,url:j(s,t)}];let o=a.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let m=N(a,{...r.vars,...n}),g=m?`${s}?${m}`:s;return[{identifier:g,url:j(g,t)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),d=l?l[1]:null;if(!d||n[d]===void 0)return[];let W=Array.isArray(n[d])?n[d]:[n[d]];if(W.length===0)return[];let f=o.filter(m=>m.includes(`{{${d}[]`)).map(m=>{let g=m.match(/\[\](\.[^}]+)?}}/),b=g&&g[1]||"";return{placeholder:m,field:b?b.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(m=>{let g=a;for(let{regex:sr,field:J}of f){let q=J?vr(m,J):m;if(q==null)return null;g=g.replace(sr,q)}if(g.includes("{{")||g.includes("}}"))return null;let b=g?`${s}?${g}`:s;return{identifier:b,url:j(b,t)}}).filter(m=>m!==null)},j=(t,r)=>{let[e,n]=t.split("?"),i=v(e)||{type:"alias",identifier:e,identifierBase:e},a=new A(r).build(i.type,i.identifierBase);if(!n)return a;let o=new URL(a);return new URLSearchParams(n).forEach((c,l)=>o.searchParams.set(l,c)),o.toString().replace(/\/\?/,"?")},vr=(t,r)=>r.split(".").reduce((e,n)=>e?.[n],t);var C=class C{static info(...r){C.isTestEnv||console.info(...r)}static warn(...r){C.isTestEnv||console.warn(...r)}static error(...r){C.isTestEnv||console.error(...r)}};C.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=C;var S=class{nativeToString(r,e){return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(p.ArgParamsSeparator),n=e[0],i=e.slice(1).join(p.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[s,a]=i.split(p.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(n==="optional"){let[s,a]=i.split(p.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(n==="list"){let s=i.split(p.ArgParamsSeparator),a=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`list:${a}`,l]}else if(n==="variadic"){let s=i.split(p.ArgParamsSeparator),a=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`variadic:${a}`,l]}else if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[1]);return[n,o]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[s,a,o]=i.split(p.ArgCompositeSeparator);return[n,`${s}|${a}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var Cr=async(t,r,e,n)=>{let i=[],s={};for(let[a,o]of Object.entries(t.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let c=er(o);if(c!==null&&c!==e){s[a]=null;continue}let[l,...d]=o.split("."),W=(f,K)=>K.reduce((m,g)=>m&&m[g]!==void 0?m[g]:null,f);if(l==="out"||l.startsWith("out[")){let f=d.length===0?r?.data||r:W(r,d);i.push(f),s[a]=f}else s[a]=o}return{values:i,results:await tr(t,s,e,n)}},tr=async(t,r,e,n)=>{if(!t.results)return r;let i={...r};return i=br(i,t,e,n),i=await Tr(t,i),i},br=(t,r,e,n)=>{let i={...t},s=O(r,e)?.inputs||[],a=new S;for(let[o,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],d=s.findIndex(f=>f.as===l||f.name===l),W=d!==-1?n[d]?.value:null;i[o]=W?a.stringToNative(W)[1]:null}return i},Tr=async(t,r)=>{if(!t.results)return r;let e={...r},n=Object.entries(t.results).filter(([,i])=>i.startsWith(p.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(p.Transform.Prefix.length)}));for(let{key:i,code:s}of n)try{let a;typeof window>"u"?a=(await Promise.resolve().then(()=>(Y(),_))).runInVm:a=(await Promise.resolve().then(()=>(rr(),Z))).runInVm,e[i]=await a(s,e)}catch(a){y.error(`Transform error for result '${i}':`,a),e[i]=null}return e},er=t=>{if(t==="out")return 1;let r=t.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(t.startsWith("out.")||t.startsWith("event."),null)};var nr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Ar=t=>nr.find(r=>r.id===t)||null;var Sr=t=>`${h.String}:${t}`,Br=t=>`${h.U8}:${t}`,Rr=t=>`${h.U16}:${t}`,Pr=t=>`${h.U32}:${t}`,Er=t=>`${h.U64}:${t}`,$r=t=>`${h.Biguint}:${t}`,Ur=t=>`${h.Boolean}:${t}`,Nr=t=>`${h.Address}:${t}`,qr=t=>`${h.Hex}:${t}`;var ir=L(require("ajv"));var M=class{constructor(r){this.pendingBrand={protocol:T("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let n=JSON.parse(r);return e&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||u.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new ir.default,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var ar=L(require("ajv"));var B=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(a=>a.type==="contract"),n=r.actions.some(a=>a.type==="query");if(!e&&!n)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let e=this.config.schema?.warp||u.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new ar.default({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var D=class{constructor(r){this.pendingWarp={protocol:T("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=r,this.adapterBuilder=new r.repository.builder(r)}createInscriptionTransaction(r){return this.adapterBuilder.createInscriptionTransaction(r)}async createFromTransaction(r,e=!1){return this.adapterBuilder.createFromTransaction(r,e)}async createFromTransactionHash(r,e){return this.adapterBuilder.createFromTransactionHash(r,e)}async createFromRaw(r,e=!0){let n=JSON.parse(r);return e&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,e=100){return k(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let n=await new B(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
12
|
+
`))}};var R=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let n=JSON.parse(e);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(r)),null):n.value}catch{return null}}set(r,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var x=class x{get(r){let e=x.cache.get(r);return e?Date.now()>e.expiresAt?(x.cache.delete(r),null):e.value:null}set(r,e,n){let i=Date.now()+n*1e3;x.cache.set(r,{value:e,expiresAt:i})}forget(r){x.cache.delete(r)}clear(){x.cache.clear()}};x.cache=new Map;var P=x;var Vr={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},Lr={Warp:(t,r)=>`warp:${t}:${r}`,WarpAbi:(t,r)=>`warp-abi:${t}:${r}`,WarpExecutable:(t,r,e)=>`warp-exec:${t}:${r}:${e}`,RegistryInfo:(t,r)=>`registry-info:${t}:${r}`,Brand:(t,r)=>`brand:${t}:${r}`,ChainInfo:(t,r)=>`chain:${t}:${r}`,ChainInfos:t=>`chains:${t}`},H=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new R:r==="memory"?new P:typeof window<"u"&&window.localStorage?new R:new P}set(r,e,n){this.strategy.set(r,e,n)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var F=class{constructor(r){this.config=r}async search(r,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};var E=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config)}async apply(r,e){let n=this.applyVars(r,e);return await this.applyGlobals(r,n)}async applyGlobals(r,e){let n={...e};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,r),n}applyVars(r,e){if(!e?.vars)return e;let n=JSON.stringify(e),i=(s,a)=>{n=n.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(e.vars).forEach(([s,a])=>{if(typeof a!="string")i(s,a);else if(a.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&i(s,c)}else if(a.startsWith(`${p.Vars.Env}:`)){let o=a.split(`${p.Vars.Env}:`)[1],c=r.vars?.[o];c&&i(s,c)}else a===p.Source.UserWallet&&r.user?.wallet?i(s,r.user.wallet):i(s,a)}),JSON.parse(n)}async applyRootGlobals(r,e){let n=JSON.stringify(r),i={config:e,chain:U(e)};return Object.values(p.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let e=r.chain?await this.registry.getChainInfo(r.chain):U(this.config);if(!e)throw new Error(`Chain info not found for ${r.chain}`);let n=JSON.stringify(r),i={config:this.config,chain:e};return Object.values(p.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}};var G=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config),this.builder=new this.config.repository.builder(this.config)}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!w(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(r,e){let n={match:!1,url:r,warp:null,registryInfo:null,brand:null},i=r.startsWith(p.HttpProtocolPrefix)?w(r):v(r);if(!i)return n;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null;if(s==="hash"){o=await this.builder.createFromTransactionHash(a,e);let f=await this.registry.getInfoByHash(a,e);c=f.registryInfo,l=f.brand}else if(s==="alias"){let f=await this.registry.getInfoByAlias(a,e);c=f.registryInfo,l=f.brand,f.registryInfo&&(o=await this.builder.createFromTransactionHash(f.registryInfo.hash,e))}let d=new E(this.config),W=o?await d.apply(this.config,o):null;return W?{match:!0,url:r,warp:W,registryInfo:c,brand:l}:n}catch(s){return y.error("Error detecting warp link",s),n}}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpConfig,WarpConstants,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-3SAEGOMQ.mjs";var o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:e=>e.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},W={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var I={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},d={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:e=>e==="devnet"?"https://devnet.usewarp.to":e==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:e=>e==="devnet"?"https://devnet-api.multiversx.com":e==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:e=>e==="devnet"?"https://devnet-explorer.multiversx.com":e==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:e=>6e3,AddressHrp:"erd",ChainId:e=>e==="devnet"?"D":e==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:e=>e==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":e==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",o.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var U=e=>({name:d.MainChain.Name,displayName:d.MainChain.DisplayName,chainId:d.MainChain.ChainId(e.env),blockTime:d.MainChain.BlockTime(e.env),addressHrp:d.MainChain.AddressHrp,apiUrl:d.MainChain.ApiUrl(e.env),explorerUrl:d.MainChain.ExplorerUrl(e.env),nativeToken:d.MainChain.NativeToken}),sr=(e,r)=>e.explorerUrl+(r?"/"+r:""),T=e=>{if(e==="warp")return`warp:${I.Warp}`;if(e==="brand")return`brand:${I.Brand}`;if(e==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},L=(e,r)=>e?.actions[r-1],or=e=>({name:e.name.toString(),displayName:e.display_name.toString(),chainId:e.chain_id.toString(),blockTime:e.block_time.toNumber(),addressHrp:e.address_hrp.toString(),apiUrl:e.api_url.toString(),explorerUrl:e.explorer_url.toString(),nativeToken:e.native_token.toString()}),pr=(e,r)=>{let t=e.toString(),[n,i=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(s,"0"));if(r<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},k=(e,r=100)=>{if(!e)return"";let t=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},N=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),lr=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,N(i,r)]);return Object.fromEntries(t)};var x=e=>{let r=decodeURIComponent(e);if(r.includes(o.IdentifierParamSeparator)){let[n,i]=r.split(o.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}let t=r.split("?")[0];return t.length===64?{type:o.IdentifierType.Hash,identifier:r,identifierBase:t}:{type:o.IdentifierType.Alias,identifier:r,identifierBase:t}},w=e=>{let r=new URL(e),t=d.SuperClientUrls.includes(r.origin),n=r.searchParams.get(o.IdentifierParamName),i=t&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return x(s)};import K from"qr-code-styling";var B=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!w(r):!1}build(r,t){let n=this.config.clientUrl||d.DefaultClientUrl(this.config.env),i=r===o.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+o.IdentifierParamSeparator+t);return d.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${o.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let t=x(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",s="black",a="#23F7DD"){let p=this.build(r,t);return new K({type:"svg",width:n,height:n,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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>`})}};var J="https://",Cr=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(J))return[{identifier:null,url:i}];let[s,a]=i.split("?");if(!a)return[{identifier:s,url:q(s,e)}];let p=a.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=N(a,{...r.vars,...n}),m=g?`${s}?${g}`:s;return[{identifier:m,url:q(m,e)}]}let c=p[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[1]:null;if(!u||n[u]===void 0)return[];let h=Array.isArray(n[u])?n[u]:[n[u]];if(h.length===0)return[];let f=p.filter(g=>g.includes(`{{${u}[]`)).map(g=>{let m=g.match(/\[\](\.[^}]+)?}}/),b=m&&m[1]||"";return{placeholder:g,field:b?b.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let m=a;for(let{regex:G,field:O}of f){let $=O?Q(g,O):g;if($==null)return null;m=m.replace(G,$)}if(m.includes("{{")||m.includes("}}"))return null;let b=m?`${s}?${m}`:s;return{identifier:b,url:q(b,e)}}).filter(g=>g!==null)},q=(e,r)=>{let[t,n]=e.split("?"),i=x(t)||{type:"alias",identifier:t,identifierBase:t},a=new B(r).build(i.type,i.identifierBase);if(!n)return a;let p=new URL(a);return new URLSearchParams(n).forEach((c,l)=>p.searchParams.set(l,c)),p.toString().replace(/\/\?/,"?")},Q=(e,r)=>r.split(".").reduce((t,n)=>t?.[n],e);var C=class C{static info(...r){C.isTestEnv||console.info(...r)}static warn(...r){C.isTestEnv||console.warn(...r)}static error(...r){C.isTestEnv||console.error(...r)}};C.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=C;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(o.ArgParamsSeparator),n=t[0],i=t.slice(1).join(o.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[s,a]=i.split(o.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(n==="optional"){let[s,a]=i.split(o.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(n==="list"){let s=i.split(o.ArgParamsSeparator),a=s.slice(0,-1).join(o.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`list:${a}`,l]}else if(n==="variadic"){let s=i.split(o.ArgParamsSeparator),a=s.slice(0,-1).join(o.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`variadic:${a}`,l]}else if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[1]);return[n,p]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[s,a,p]=i.split(o.ArgCompositeSeparator);return[n,`${s}|${a}|${p}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var Er=async(e,r,t,n)=>{let i=[],s={};for(let[a,p]of Object.entries(e.results||{})){if(p.startsWith(o.Transform.Prefix))continue;let c=Y(p);if(c!==null&&c!==t){s[a]=null;continue}let[l,...u]=p.split("."),h=(f,V)=>V.reduce((g,m)=>g&&g[m]!==void 0?g[m]:null,f);if(l==="out"||l.startsWith("out[")){let f=u.length===0?r?.data||r:h(r,u);i.push(f),s[a]=f}else s[a]=p}return{values:i,results:await z(e,s,t,n)}},z=async(e,r,t,n)=>{if(!e.results)return r;let i={...r};return i=X(i,e,t,n),i=await _(e,i),i},X=(e,r,t,n)=>{let i={...e},s=L(r,t)?.inputs||[],a=new P;for(let[p,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(f=>f.as===l||f.name===l),h=u!==-1?n[u]?.value:null;i[p]=h?a.stringToNative(h)[1]:null}return i},_=async(e,r)=>{if(!e.results)return r;let t={...r},n=Object.entries(e.results).filter(([,i])=>i.startsWith(o.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(o.Transform.Prefix.length)}));for(let{key:i,code:s}of n)try{let a;typeof window>"u"?a=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:a=(await import("./runInVm-5YQ766M3.mjs")).runInVm,t[i]=await a(s,t)}catch(a){y.error(`Transform error for result '${i}':`,a),t[i]=null}return t},Y=e=>{if(e==="out")return 1;let r=e.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};var Z=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Lr=e=>Z.find(r=>r.id===e)||null;var zr=e=>`${W.String}:${e}`,Xr=e=>`${W.U8}:${e}`,_r=e=>`${W.U16}:${e}`,Yr=e=>`${W.U32}:${e}`,Zr=e=>`${W.U64}:${e}`,rt=e=>`${W.Biguint}:${e}`,tt=e=>`${W.Boolean}:${e}`,et=e=>`${W.Address}:${e}`,nt=e=>`${W.Hex}:${e}`;import rr from"ajv";var j=class{constructor(r){this.pendingBrand={protocol:T("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||d.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),s=new rr,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import tr from"ajv";var R=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&t.push(`${s} name '${a}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(a=>a.type==="contract"),n=r.actions.some(a=>a.type==="query");if(!t&&!n)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||d.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),s=new tr({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var D=class{constructor(r){this.pendingWarp={protocol:T("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return k(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new R(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var
|
|
1
|
+
import"./chunk-3SAEGOMQ.mjs";var o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:e=>e.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},W={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var I={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},d={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:e=>e==="devnet"?"https://devnet.usewarp.to":e==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:e=>e==="devnet"?"https://devnet-api.multiversx.com":e==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:e=>e==="devnet"?"https://devnet-explorer.multiversx.com":e==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:e=>6e3,AddressHrp:"erd",ChainId:e=>e==="devnet"?"D":e==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:e=>e==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":e==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",o.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var U=e=>({name:d.MainChain.Name,displayName:d.MainChain.DisplayName,chainId:d.MainChain.ChainId(e.env),blockTime:d.MainChain.BlockTime(e.env),addressHrp:d.MainChain.AddressHrp,apiUrl:d.MainChain.ApiUrl(e.env),explorerUrl:d.MainChain.ExplorerUrl(e.env),nativeToken:d.MainChain.NativeToken}),sr=(e,r)=>e.explorerUrl+(r?"/"+r:""),S=e=>{if(e==="warp")return`warp:${I.Warp}`;if(e==="brand")return`brand:${I.Brand}`;if(e==="abi")return`abi:${I.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},L=(e,r)=>e?.actions[r-1],or=e=>({name:e.name.toString(),displayName:e.display_name.toString(),chainId:e.chain_id.toString(),blockTime:e.block_time.toNumber(),addressHrp:e.address_hrp.toString(),apiUrl:e.api_url.toString(),explorerUrl:e.explorer_url.toString(),nativeToken:e.native_token.toString()}),pr=(e,r)=>{let t=e.toString(),[n,i=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(s,"0"));if(r<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},k=(e,r=100)=>{if(!e)return"";let t=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},N=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),lr=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,N(i,r)]);return Object.fromEntries(t)};var x=e=>{let r=decodeURIComponent(e);if(r.includes(o.IdentifierParamSeparator)){let[n,i]=r.split(o.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}let t=r.split("?")[0];return t.length===64?{type:o.IdentifierType.Hash,identifier:r,identifierBase:t}:{type:o.IdentifierType.Alias,identifier:r,identifierBase:t}},w=e=>{let r=new URL(e),t=d.SuperClientUrls.includes(r.origin),n=r.searchParams.get(o.IdentifierParamName),i=t&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return x(s)};import K from"qr-code-styling";var B=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!w(r):!1}build(r,t){let n=this.config.clientUrl||d.DefaultClientUrl(this.config.env),i=r===o.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+o.IdentifierParamSeparator+t);return d.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${o.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let t=x(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",s="black",a="#23F7DD"){let p=this.build(r,t);return new K({type:"svg",width:n,height:n,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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>`})}};var J="https://",Cr=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(J))return[{identifier:null,url:i}];let[s,a]=i.split("?");if(!a)return[{identifier:s,url:q(s,e)}];let p=a.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=N(a,{...r.vars,...n}),m=g?`${s}?${g}`:s;return[{identifier:m,url:q(m,e)}]}let c=p[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[1]:null;if(!u||n[u]===void 0)return[];let h=Array.isArray(n[u])?n[u]:[n[u]];if(h.length===0)return[];let f=p.filter(g=>g.includes(`{{${u}[]`)).map(g=>{let m=g.match(/\[\](\.[^}]+)?}}/),b=m&&m[1]||"";return{placeholder:g,field:b?b.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let m=a;for(let{regex:G,field:O}of f){let $=O?Q(g,O):g;if($==null)return null;m=m.replace(G,$)}if(m.includes("{{")||m.includes("}}"))return null;let b=m?`${s}?${m}`:s;return{identifier:b,url:q(b,e)}}).filter(g=>g!==null)},q=(e,r)=>{let[t,n]=e.split("?"),i=x(t)||{type:"alias",identifier:t,identifierBase:t},a=new B(r).build(i.type,i.identifierBase);if(!n)return a;let p=new URL(a);return new URLSearchParams(n).forEach((c,l)=>p.searchParams.set(l,c)),p.toString().replace(/\/\?/,"?")},Q=(e,r)=>r.split(".").reduce((t,n)=>t?.[n],e);var C=class C{static info(...r){C.isTestEnv||console.info(...r)}static warn(...r){C.isTestEnv||console.warn(...r)}static error(...r){C.isTestEnv||console.error(...r)}};C.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=C;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(o.ArgParamsSeparator),n=t[0],i=t.slice(1).join(o.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[s,a]=i.split(o.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(n==="optional"){let[s,a]=i.split(o.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(n==="list"){let s=i.split(o.ArgParamsSeparator),a=s.slice(0,-1).join(o.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`list:${a}`,l]}else if(n==="variadic"){let s=i.split(o.ArgParamsSeparator),a=s.slice(0,-1).join(o.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(u=>this.stringToNative(`${a}:${u}`)[1]);return[`variadic:${a}`,l]}else if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[1]);return[n,p]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[s,a,p]=i.split(o.ArgCompositeSeparator);return[n,`${s}|${a}|${p}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var Er=async(e,r,t,n)=>{let i=[],s={};for(let[a,p]of Object.entries(e.results||{})){if(p.startsWith(o.Transform.Prefix))continue;let c=Y(p);if(c!==null&&c!==t){s[a]=null;continue}let[l,...u]=p.split("."),h=(f,V)=>V.reduce((g,m)=>g&&g[m]!==void 0?g[m]:null,f);if(l==="out"||l.startsWith("out[")){let f=u.length===0?r?.data||r:h(r,u);i.push(f),s[a]=f}else s[a]=p}return{values:i,results:await z(e,s,t,n)}},z=async(e,r,t,n)=>{if(!e.results)return r;let i={...r};return i=X(i,e,t,n),i=await _(e,i),i},X=(e,r,t,n)=>{let i={...e},s=L(r,t)?.inputs||[],a=new P;for(let[p,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(f=>f.as===l||f.name===l),h=u!==-1?n[u]?.value:null;i[p]=h?a.stringToNative(h)[1]:null}return i},_=async(e,r)=>{if(!e.results)return r;let t={...r},n=Object.entries(e.results).filter(([,i])=>i.startsWith(o.Transform.Prefix)).map(([i,s])=>({key:i,code:s.substring(o.Transform.Prefix.length)}));for(let{key:i,code:s}of n)try{let a;typeof window>"u"?a=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:a=(await import("./runInVm-5YQ766M3.mjs")).runInVm,t[i]=await a(s,t)}catch(a){y.error(`Transform error for result '${i}':`,a),t[i]=null}return t},Y=e=>{if(e==="out")return 1;let r=e.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};var Z=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Lr=e=>Z.find(r=>r.id===e)||null;var zr=e=>`${W.String}:${e}`,Xr=e=>`${W.U8}:${e}`,_r=e=>`${W.U16}:${e}`,Yr=e=>`${W.U32}:${e}`,Zr=e=>`${W.U64}:${e}`,rt=e=>`${W.Biguint}:${e}`,tt=e=>`${W.Boolean}:${e}`,et=e=>`${W.Address}:${e}`,nt=e=>`${W.Hex}:${e}`;import rr from"ajv";var j=class{constructor(r){this.pendingBrand={protocol:S("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||d.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),s=new rr,a=s.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import tr from"ajv";var R=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&t.push(`${s} name '${a}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(a=>a.type==="contract"),n=r.actions.some(a=>a.type==="query");if(!t&&!n)return[];let i=r.actions.some(a=>a.abi),s=Object.values(r.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return r.results&&!i&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||d.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),s=new tr({strict:!1}),a=s.compile(i);return a(r)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var D=class{constructor(r){this.pendingWarp={protocol:S("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=r,this.adapterBuilder=new r.repository.builder(r)}createInscriptionTransaction(r){return this.adapterBuilder.createInscriptionTransaction(r)}async createFromTransaction(r,t=!1){return this.adapterBuilder.createFromTransaction(r,t)}async createFromTransactionHash(r,t){return this.adapterBuilder.createFromTransactionHash(r,t)}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return k(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new R(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var A=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(r)),null):n.value}catch{return null}}set(r,t,n){let i={value:t,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}};var v=class v{get(r){let t=v.cache.get(r);return t?Date.now()>t.expiresAt?(v.cache.delete(r),null):t.value:null}set(r,t,n){let i=Date.now()+n*1e3;v.cache.set(r,{value:t,expiresAt:i})}forget(r){v.cache.delete(r)}clear(){v.cache.clear()}};v.cache=new Map;var T=v;var vt={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},xt={Warp:(e,r)=>`warp:${e}:${r}`,WarpAbi:(e,r)=>`warp-abi:${e}:${r}`,WarpExecutable:(e,r,t)=>`warp-exec:${e}:${r}:${t}`,RegistryInfo:(e,r)=>`registry-info:${e}:${r}`,Brand:(e,r)=>`brand:${e}:${r}`,ChainInfo:(e,r)=>`chain:${e}:${r}`,ChainInfos:e=>`chains:${e}`},H=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new A:r==="memory"?new T:typeof window<"u"&&window.localStorage?new A:new T}set(r,t,n){this.strategy.set(r,t,n)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var M=class{constructor(r){this.config=r}async search(r,t,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};var E=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config)}async apply(r,t){let n=this.applyVars(r,t);return await this.applyGlobals(r,n)}async applyGlobals(r,t){let n={...t};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,r),n}applyVars(r,t){if(!t?.vars)return t;let n=JSON.stringify(t),i=(s,a)=>{n=n.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([s,a])=>{if(typeof a!="string")i(s,a);else if(a.startsWith(`${o.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=a.split(`${o.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(p);c&&i(s,c)}else if(a.startsWith(`${o.Vars.Env}:`)){let p=a.split(`${o.Vars.Env}:`)[1],c=r.vars?.[p];c&&i(s,c)}else a===o.Source.UserWallet&&r.user?.wallet?i(s,r.user.wallet):i(s,a)}),JSON.parse(n)}async applyRootGlobals(r,t){let n=JSON.stringify(r),i={config:t,chain:U(t)};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let t=r.chain?await this.registry.getChainInfo(r.chain):U(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let n=JSON.stringify(r),i={config:this.config,chain:t};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}};var F=class{constructor(r){this.config=r;this.registry=new this.config.repository.registry(this.config),this.builder=new this.config.repository.builder(this.config)}isValid(r){return r.startsWith(o.HttpProtocolPrefix)?!!w(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),p=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:c}}async detect(r,t){let n={match:!1,url:r,warp:null,registryInfo:null,brand:null},i=r.startsWith(o.HttpProtocolPrefix)?w(r):x(r);if(!i)return n;try{let{type:s,identifierBase:a}=i,p=null,c=null,l=null;if(s==="hash"){p=await this.builder.createFromTransactionHash(a,t);let f=await this.registry.getInfoByHash(a,t);c=f.registryInfo,l=f.brand}else if(s==="alias"){let f=await this.registry.getInfoByAlias(a,t);c=f.registryInfo,l=f.brand,f.registryInfo&&(p=await this.builder.createFromTransactionHash(f.registryInfo.hash,t))}let u=new E(this.config),h=p?await u.apply(this.config,p):null;return h?{match:!0,url:r,warp:h,registryInfo:c,brand:l}:n}catch(s){return y.error("Error detecting warp link",s),n}}};export{vt as CacheTtl,Z as KnownTokens,j as WarpBrandBuilder,D as WarpBuilder,H as WarpCache,xt as WarpCacheKey,d as WarpConfig,o as WarpConstants,M as WarpIndex,W as WarpInputTypes,E as WarpInterpolator,B as WarpLinkBuilder,F as WarpLinkDetecter,y as WarpLogger,I as WarpProtocolVersions,P as WarpSerializer,R as WarpValidator,et as address,lr as applyResultsToMessages,rt as biguint,tt as boolean,z as evaluateResultsCommon,Er as extractCollectResults,w as extractIdentifierInfoFromUrl,Lr as findKnownTokenById,sr as getChainExplorerUrl,S as getLatestProtocolIdentifier,U as getMainChainInfo,Cr as getNextInfo,L as getWarpActionByIndex,x as getWarpInfoFromIdentifier,nt as hex,Y as parseResultsOutIndex,N as replacePlaceholders,pr as shiftBigintBy,zr as string,k as toPreviewText,or as toTypedChainInfo,_r as u16,Yr as u32,Zr as u64,Xr as u8};
|