@vleap/warps 0.0.64 → 0.0.66

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
@@ -51,7 +51,7 @@ type WarpContractAction = {
51
51
  args: string[];
52
52
  value?: string;
53
53
  gasLimit: number;
54
- transfer?: WarpContractActionTransfer[];
54
+ transfers?: WarpContractActionTransfer[];
55
55
  inputs?: WarpActionInput[];
56
56
  next?: string;
57
57
  };
@@ -158,9 +158,11 @@ declare class WarpActionExecutor {
158
158
  private config;
159
159
  private url;
160
160
  constructor(config: WarpConfig, url: string);
161
- createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers?: TokenTransfer[]): Transaction$1;
161
+ createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
162
162
  getPositionValueFromUrl(action: WarpAction, position: WarpActionInputPosition): string | null;
163
+ getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
163
164
  getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
165
+ private toTypedTransfer;
164
166
  private toTypedArg;
165
167
  }
166
168
 
package/dist/index.d.ts CHANGED
@@ -51,7 +51,7 @@ type WarpContractAction = {
51
51
  args: string[];
52
52
  value?: string;
53
53
  gasLimit: number;
54
- transfer?: WarpContractActionTransfer[];
54
+ transfers?: WarpContractActionTransfer[];
55
55
  inputs?: WarpActionInput[];
56
56
  next?: string;
57
57
  };
@@ -158,9 +158,11 @@ declare class WarpActionExecutor {
158
158
  private config;
159
159
  private url;
160
160
  constructor(config: WarpConfig, url: string);
161
- createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers?: TokenTransfer[]): Transaction$1;
161
+ createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
162
162
  getPositionValueFromUrl(action: WarpAction, position: WarpActionInputPosition): string | null;
163
+ getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
163
164
  getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
165
+ private toTypedTransfer;
164
166
  private toTypedArg;
165
167
  }
166
168
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var O=Object.create;var C=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var j=(i,r)=>{for(var t in r)C(i,t,{get:r[t],enumerable:!0})},L=(i,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of _(r))!H.call(i,a)&&a!==t&&C(i,a,{get:()=>r[a],enumerable:!(e=$(r,a))||e.enumerable});return i};var F=(i,r,t)=>(t=i!=null?O(Q(i)):{},L(r||!i||!i.__esModule?C(t,"default",{value:i,enumerable:!0}):t,i)),K=i=>L(C({},"__esModule",{value:!0}),i);var J={};j(J,{BrandBuilder:()=>x,Config:()=>c,WarpActionExecutor:()=>U,WarpBuilder:()=>W,WarpLink:()=>E,WarpRegistry:()=>v});module.exports=K(J);var m=require("@multiversx/sdk-core"),N=F(require("ajv"));var c={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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 y=i=>i==="devnet"?"D":i==="testnet"?"T":"1",T=i=>`${i}:${c.LatestProtocolVersion}`,A=i=>{var r,t;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null}};var x=class{config;pendingBrand={protocol:T(c.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new m.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new m.TransferTransactionsFactory({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:m.Address.newFromBech32(this.config.userAddress),receiver:m.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new m.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}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.brandSchemaUrl||c.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),n=new N.default,o=n.compile(a);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(o.errors)}`)}};var u=require("@multiversx/sdk-core/out");var U=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let a=new u.TransactionsFactoryConfig({chainID:y(this.config.env)}),n=new u.SmartContractTransactionsFactory({config:a}),o=this.getTypedArgsFromInput(t),d=this.getPositionValueFromUrl(r,"value"),l=BigInt(d||r.value||0);return n.createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:o,tokenTransfers:e,nativeTransferAmount:l})}getPositionValueFromUrl(r,t){var o,d;let e=new URLSearchParams(this.url.search),a=(o=r.inputs)==null?void 0:o.filter(l=>l.source==="query"),n=(d=a==null?void 0:a.find(l=>l.position===t))==null?void 0:d.name;return n?e.get(n):null}getTypedArgsFromInput(r){return r.map(t=>{let[e,a]=t.split(":");return this.toTypedArg(a,e)})}toTypedArg(r,t){if(t==="string")return u.BytesValue.fromUTF8(r);if(t==="uint8")return new u.U8Value(Number(r));if(t==="uint16")return new u.U16Value(Number(r));if(t==="uint32")return new u.U32Value(Number(r));if(t==="uint64")return new u.U64Value(BigInt(r));if(t==="biguint")return new u.BigUIntValue(BigInt(r));if(t==="boolean")return new u.BooleanValue(r==="true");if(t==="address")return new u.AddressValue(u.Address.newFromBech32(r));if(t==="hex")return u.BytesValue.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};var f=require("@multiversx/sdk-core"),V=F(require("ajv"));var B={Warp:i=>`warp:${i}`,WarpInfo:i=>`warp-info:${i}`,Brand:i=>`brand:${i}`},w=class{cache=new Map;set(r,t,e){let a=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:a})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var W=class{config;cache=new w;pendingWarp={protocol:T(c.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new f.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new f.TransferTransactionsFactory({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:f.Address.newFromBech32(this.config.userAddress),receiver:f.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=B.Warp(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),n}let a=new f.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),o=await this.createFromTransaction(n);return t&&t.ttl&&o&&this.cache.set(e,o,t.ttl),o}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}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.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||c.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),n=new V.default,o=n.compile(a);if(!o(r))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(o.errors)}`)}};var D=F(require("qr-code-styling"));var s=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.50.6"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"}],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:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<WarpInfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{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}]}],esdtAttributes:[],hasCallback:!1,types:{WarpInfoView:{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>"}]}}};var v=class{config;unitPrice;cache=new w;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]:[s.BytesValue.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]})}createBrandRegisterTransaction(r){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");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[s.BytesValue.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromHex(t)]})}async getInfoByAlias(r,t){let e=B.WarpInfo(r);if(t){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByAlias): WarpInfo found in cache: ${r}`),g}let a=c.Registry.Contract(this.config.env),n=this.getController(),o=n.createQuery({contract:a,function:"getInfoByAlias",arguments:[s.BytesValue.fromUTF8(r)]}),d=await n.runQuery(o),[l]=n.parseQueryResponse(d),p=l?A(l):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:p,brand:h},t.ttl),{warp:p,brand:h}}async getInfoByHash(r,t){let e=B.WarpInfo(r);if(t){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByHash): WarpInfo found in cache: ${r}`),g}let a=c.Registry.Contract(this.config.env),n=this.getController(),o=n.createQuery({contract:a,function:"getInfoByHash",arguments:[s.BytesValue.fromHex(r)]}),d=await n.runQuery(o),[l]=n.parseQueryResponse(d),p=l?A(l):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:p,brand:h},t.ttl),{warp:p,brand:h}}async getUserWarpInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserWarps",arguments:[new s.AddressValue(new s.Address(t))]}),o=await a.runQuery(n),[d]=a.parseQueryResponse(o);return d.map(A)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserBrands",arguments:[new s.AddressValue(new s.Address(t))]}),o=await a.runQuery(n),[d]=a.parseQueryResponse(o),l=d.map(g=>g.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(l.map(g=>this.fetchBrand(g,p)))).filter(g=>g!==null)}async fetchBrand(r,t){let e=B.Brand(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),n}let a=new s.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),o=JSON.parse(n.data.toString());return o.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,o,t.ttl),o}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let r=c.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),a=await t.runQuery(e),[n]=t.parseQueryResponse(a),o=BigInt(n.toString());this.unitPrice=o}getFactory(){let r=new s.TransactionsFactoryConfig({chainID:y(this.config.env)}),t=s.AbiRegistry.create(q);return new s.SmartContractTransactionsFactory({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env),t=new s.ApiNetworkProvider(r,{timeout:3e4}),e=new s.QueryRunnerAdapter({networkProvider:t}),a=s.AbiRegistry.create(q);return new s.SmartContractQueriesController({queryRunner:e,abi:a})}};var S="xwarp",I=":",k="alias",E=class{constructor(r){this.config=r;this.config=r}async detect(r){let a=new URL(r).searchParams.get(S);if(!a)return{match:!1,warp:null,brand:null};let n=decodeURIComponent(a),o=n.includes(I)?n:`${k}${I}${n}`,[d,l]=o.split(I),p=new W(this.config),h=new v(this.config),g=null,P=null;if(d==="hash"){let[b,{brand:R}]=await Promise.all([p.createFromTransactionHash(l),h.getInfoByHash(l)]);g=b,P=R}else if(d==="alias"){let{warp:b,brand:R}=await h.getInfoByAlias(l);b&&(g=await p.createFromTransactionHash(b.hash),P=R)}return g?{match:!0,warp:g,brand:P}:{match:!1,warp:null,brand:null}}build(r,t){let e=this.config.clientUrl||c.DefaultClientUrl(this.config.env);return r===k?`${e}?${S}=${encodeURIComponent(t)}`:`${e}?${S}=${encodeURIComponent(r+I+t)}`}generateQrCode(r,t,e=512,a="white",n="black",o="#23F7DD"){let d=this.build(r,t);return new D.default({type:"svg",width:e,height:e,data:String(d),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},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>`})}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry});
1
+ "use strict";var O=Object.create;var C=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var j=(i,r)=>{for(var t in r)C(i,t,{get:r[t],enumerable:!0})},L=(i,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of _(r))!H.call(i,n)&&n!==t&&C(i,n,{get:()=>r[n],enumerable:!(e=$(r,n))||e.enumerable});return i};var F=(i,r,t)=>(t=i!=null?O(Q(i)):{},L(r||!i||!i.__esModule?C(t,"default",{value:i,enumerable:!0}):t,i)),K=i=>L(C({},"__esModule",{value:!0}),i);var J={};j(J,{BrandBuilder:()=>x,Config:()=>u,WarpActionExecutor:()=>U,WarpBuilder:()=>W,WarpLink:()=>E,WarpRegistry:()=>T});module.exports=K(J);var m=require("@multiversx/sdk-core"),k=F(require("ajv"));var u={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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 y=i=>i==="devnet"?"D":i==="testnet"?"T":"1",b=i=>`${i}:${u.LatestProtocolVersion}`,A=i=>{var r,t;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null}};var x=class{config;pendingBrand={protocol:b(u.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new m.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new m.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:m.Address.newFromBech32(this.config.userAddress),receiver:m.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new m.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}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.brandSchemaUrl||u.LatestBrandSchemaUrl,n=await(await fetch(t)).json(),a=new k.default,o=a.compile(n);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out");var U=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new c.TransactionsFactoryConfig({chainID:y(this.config.env)}),a=new c.SmartContractTransactionsFactory({config:n}),o=this.getTypedArgsFromInput(t),d=this.getPositionValueFromUrl(r,"value"),l=BigInt(d||r.value||0),p=this.getCombinedTokenTransfers(r,e);return a.createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:o,tokenTransfers:p,nativeTransferAmount:l})}getPositionValueFromUrl(r,t){var o,d;let e=new URLSearchParams(this.url.search),n=(o=r.inputs)==null?void 0:o.filter(l=>l.source==="query"),a=(d=n==null?void 0:n.find(l=>l.position===t))==null?void 0:d.name;return a?e.get(a):null}getCombinedTokenTransfers(r,t){var n;return[...((n=r.transfers)==null?void 0:n.map(this.toTypedTransfer))||[],...t]}getTypedArgsFromInput(r){return r.map(t=>{let[e,n]=t.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(r){return new c.TokenTransfer({token:new c.Token({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return c.BytesValue.fromUTF8(r);if(t==="uint8")return new c.U8Value(Number(r));if(t==="uint16")return new c.U16Value(Number(r));if(t==="uint32")return new c.U32Value(Number(r));if(t==="uint64")return new c.U64Value(BigInt(r));if(t==="biguint")return new c.BigUIntValue(BigInt(r));if(t==="boolean")return new c.BooleanValue(r==="true");if(t==="address")return new c.AddressValue(c.Address.newFromBech32(r));if(t==="hex")return c.BytesValue.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};var f=require("@multiversx/sdk-core"),N=F(require("ajv"));var B={Warp:i=>`warp:${i}`,WarpInfo:i=>`warp-info:${i}`,Brand:i=>`brand:${i}`},w=class{cache=new Map;set(r,t,e){let n=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:n})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var W=class{config;cache=new w;pendingWarp={protocol:b(u.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new f.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new f.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:f.Address.newFromBech32(this.config.userAddress),receiver:f.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=B.Warp(r);if(t){let a=this.cache.get(e);if(a)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),a}let n=new f.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(r),o=await this.createFromTransaction(a);return t&&t.ttl&&o&&this.cache.set(e,o,t.ttl),o}catch(a){return console.error("WarpBuilder: Error creating from transaction hash",a),null}}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.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,n=await(await fetch(t)).json(),a=new N.default,o=a.compile(n);if(!o(r))throw new Error(`WarpBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var D=F(require("qr-code-styling"));var s=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.50.6"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"}],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:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<WarpInfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{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}]}],esdtAttributes:[],hasCallback:!1,types:{WarpInfoView:{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>"}]}}};var T=class{config;unitPrice;cache=new w;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]:[s.BytesValue.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]})}createBrandRegisterTransaction(r){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");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[s.BytesValue.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromHex(t)]})}async getInfoByAlias(r,t){let e=B.WarpInfo(r);if(t){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByAlias): WarpInfo found in cache: ${r}`),g}let n=u.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByAlias",arguments:[s.BytesValue.fromUTF8(r)]}),d=await a.runQuery(o),[l]=a.parseQueryResponse(d),p=l?A(l):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:p,brand:h},t.ttl),{warp:p,brand:h}}async getInfoByHash(r,t){let e=B.WarpInfo(r);if(t){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByHash): WarpInfo found in cache: ${r}`),g}let n=u.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[s.BytesValue.fromHex(r)]}),d=await a.runQuery(o),[l]=a.parseQueryResponse(d),p=l?A(l):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:p,brand:h},t.ttl),{warp:p,brand:h}}async getUserWarpInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:e,function:"getUserWarps",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(a),[d]=n.parseQueryResponse(o);return d.map(A)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:e,function:"getUserBrands",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(a),[d]=n.parseQueryResponse(o),l=d.map(g=>g.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(l.map(g=>this.fetchBrand(g,p)))).filter(g=>g!==null)}async fetchBrand(r,t){let e=B.Brand(r);if(t){let a=this.cache.get(e);if(a)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),a}let n=new s.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(r),o=JSON.parse(a.data.toString());return o.meta={hash:a.hash,creator:a.sender.bech32(),createdAt:new Date(a.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,o,t.ttl),o}catch(a){return console.error("WarpRegistry: Error fetching brand from transaction hash",a),null}}async loadRegistryConfigs(){let r=u.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),n=await t.runQuery(e),[a]=t.parseQueryResponse(n),o=BigInt(a.toString());this.unitPrice=o}getFactory(){let r=new s.TransactionsFactoryConfig({chainID:y(this.config.env)}),t=s.AbiRegistry.create(q);return new s.SmartContractTransactionsFactory({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),t=new s.ApiNetworkProvider(r,{timeout:3e4}),e=new s.QueryRunnerAdapter({networkProvider:t}),n=s.AbiRegistry.create(q);return new s.SmartContractQueriesController({queryRunner:e,abi:n})}};var S="xwarp",I=":",V="alias",E=class{constructor(r){this.config=r;this.config=r}async detect(r){let n=new URL(r).searchParams.get(S);if(!n)return{match:!1,warp:null,brand:null};let a=decodeURIComponent(n),o=a.includes(I)?a:`${V}${I}${a}`,[d,l]=o.split(I),p=new W(this.config),h=new T(this.config),g=null,P=null;if(d==="hash"){g=await p.createFromTransactionHash(l);try{let{brand:v}=await h.getInfoByHash(l);P=v}catch{}}else if(d==="alias"){let{warp:R,brand:v}=await h.getInfoByAlias(l);R&&(g=await p.createFromTransactionHash(R.hash),P=v)}return g?{match:!0,warp:g,brand:P}:{match:!1,warp:null,brand:null}}build(r,t){let e=this.config.clientUrl||u.DefaultClientUrl(this.config.env);return r===V?`${e}?${S}=${encodeURIComponent(t)}`:`${e}?${S}=${encodeURIComponent(r+I+t)}`}generateQrCode(r,t,e=512,n="white",a="black",o="#23F7DD"){let d=this.build(r,t);return new D.default({type:"svg",width:e,height:e,data:String(d),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>`})}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Address as F,ApiNetworkProvider as D,TransactionsFactoryConfig as O,TransferTransactionsFactory as $}from"@multiversx/sdk-core";import _ from"ajv";var o={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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 m=i=>i==="devnet"?"D":i==="testnet"?"T":"1",B=i=>`${i}:${o.LatestProtocolVersion}`,W=i=>{var r,t;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null}};var x=class{config;pendingBrand={protocol:B(o.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new O({chainID:m(this.config.env)}),e=new $({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:F.newFromBech32(this.config.userAddress),receiver:F.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new D(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}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.brandSchemaUrl||o.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),n=new _,s=n.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as I,AddressValue as Q,BigUIntValue as H,BooleanValue as j,BytesValue as U,SmartContractTransactionsFactory as K,TransactionsFactoryConfig as G,U16Value as J,U32Value as z,U64Value as M,U8Value as Z}from"@multiversx/sdk-core/out";var q=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let a=new G({chainID:m(this.config.env)}),n=new K({config:a}),s=this.getTypedArgsFromInput(t),u=this.getPositionValueFromUrl(r,"value"),p=BigInt(u||r.value||0);return n.createTransactionForExecute({sender:I.newFromBech32(this.config.userAddress),contract:I.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:s,tokenTransfers:e,nativeTransferAmount:p})}getPositionValueFromUrl(r,t){var s,u;let e=new URLSearchParams(this.url.search),a=(s=r.inputs)==null?void 0:s.filter(p=>p.source==="query"),n=(u=a==null?void 0:a.find(p=>p.position===t))==null?void 0:u.name;return n?e.get(n):null}getTypedArgsFromInput(r){return r.map(t=>{let[e,a]=t.split(":");return this.toTypedArg(a,e)})}toTypedArg(r,t){if(t==="string")return U.fromUTF8(r);if(t==="uint8")return new Z(Number(r));if(t==="uint16")return new J(Number(r));if(t==="uint32")return new z(Number(r));if(t==="uint64")return new M(BigInt(r));if(t==="biguint")return new H(BigInt(r));if(t==="boolean")return new j(r==="true");if(t==="address")return new Q(I.newFromBech32(r));if(t==="hex")return U.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};import{Address as S,ApiNetworkProvider as X,TransactionsFactoryConfig as Y,TransferTransactionsFactory as rr}from"@multiversx/sdk-core";import tr from"ajv";var y={Warp:i=>`warp:${i}`,WarpInfo:i=>`warp-info:${i}`,Brand:i=>`brand:${i}`},f=class{cache=new Map;set(r,t,e){let a=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:a})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var v=class{config;cache=new f;pendingWarp={protocol:B(o.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new Y({chainID:m(this.config.env)}),e=new rr({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:S.newFromBech32(this.config.userAddress),receiver:S.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=y.Warp(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),n}let a=new X(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=await this.createFromTransaction(n);return t&&t.ttl&&s&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}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.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),n=new tr,s=n.compile(a);if(!s(r))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import or from"qr-code-styling";import{AbiRegistry as E,Address as l,AddressValue as L,ApiNetworkProvider as N,BytesValue as g,QueryRunnerAdapter as nr,SmartContractQueriesController as ar,SmartContractTransactionsFactory as ir,TransactionsFactoryConfig as sr}from"@multiversx/sdk-core/out";var P={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.50.6"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"}],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:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<WarpInfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{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}]}],esdtAttributes:[],hasCallback:!1,types:{WarpInfoView:{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>"}]}}};var b=class{config;unitPrice;cache=new f;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[g.fromHex(r),g.fromUTF8(t)]:[g.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r),g.fromUTF8(t)]})}createBrandRegisterTransaction(r){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");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r),g.fromHex(t)]})}async getInfoByAlias(r,t){let e=y.WarpInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByAlias): WarpInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByAlias",arguments:[g.fromUTF8(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?W(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:c,brand:h},t.ttl),{warp:c,brand:h}}async getInfoByHash(r,t){let e=y.WarpInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByHash): WarpInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByHash",arguments:[g.fromHex(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?W(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:c,brand:h},t.ttl),{warp:c,brand:h}}async getUserWarpInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserWarps",arguments:[new L(new l(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s);return u.map(W)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserBrands",arguments:[new L(new l(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s),p=u.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(r,t){let e=y.Brand(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),n}let a=new N(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let r=o.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),a=await t.runQuery(e),[n]=t.parseQueryResponse(a),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let r=new sr({chainID:m(this.config.env)}),t=E.create(P);return new ir({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),t=new N(r,{timeout:3e4}),e=new nr({networkProvider:t}),a=E.create(P);return new ar({queryRunner:e,abi:a})}};var R="xwarp",C=":",V="alias",k=class{constructor(r){this.config=r;this.config=r}async detect(r){let a=new URL(r).searchParams.get(R);if(!a)return{match:!1,warp:null,brand:null};let n=decodeURIComponent(a),s=n.includes(C)?n:`${V}${C}${n}`,[u,p]=s.split(C),c=new v(this.config),h=new b(this.config),d=null,T=null;if(u==="hash"){let[w,{brand:A}]=await Promise.all([c.createFromTransactionHash(p),h.getInfoByHash(p)]);d=w,T=A}else if(u==="alias"){let{warp:w,brand:A}=await h.getInfoByAlias(p);w&&(d=await c.createFromTransactionHash(w.hash),T=A)}return d?{match:!0,warp:d,brand:T}:{match:!1,warp:null,brand:null}}build(r,t){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env);return r===V?`${e}?${R}=${encodeURIComponent(t)}`:`${e}?${R}=${encodeURIComponent(r+C+t)}`}generateQrCode(r,t,e=512,a="white",n="black",s="#23F7DD"){let u=this.build(r,t);return new or({type:"svg",width:e,height:e,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};export{x as BrandBuilder,o as Config,q as WarpActionExecutor,v as WarpBuilder,k as WarpLink,b as WarpRegistry};
1
+ import{Address as F,ApiNetworkProvider as D,TransactionsFactoryConfig as O,TransferTransactionsFactory as $}from"@multiversx/sdk-core";import _ from"ajv";var o={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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 m=i=>i==="devnet"?"D":i==="testnet"?"T":"1",B=i=>`${i}:${o.LatestProtocolVersion}`,W=i=>{var r,t;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null}};var x=class{config;pendingBrand={protocol:B(o.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new O({chainID:m(this.config.env)}),e=new $({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:F.newFromBech32(this.config.userAddress),receiver:F.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new D(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}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.brandSchemaUrl||o.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),n=new _,s=n.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as I,AddressValue as Q,BigUIntValue as H,BooleanValue as j,BytesValue as U,SmartContractTransactionsFactory as K,Token as G,TokenTransfer as J,TransactionsFactoryConfig as z,U16Value as M,U32Value as Z,U64Value as X,U8Value as Y}from"@multiversx/sdk-core/out";var q=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let a=new z({chainID:m(this.config.env)}),n=new K({config:a}),s=this.getTypedArgsFromInput(t),u=this.getPositionValueFromUrl(r,"value"),p=BigInt(u||r.value||0),c=this.getCombinedTokenTransfers(r,e);return n.createTransactionForExecute({sender:I.newFromBech32(this.config.userAddress),contract:I.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:s,tokenTransfers:c,nativeTransferAmount:p})}getPositionValueFromUrl(r,t){var s,u;let e=new URLSearchParams(this.url.search),a=(s=r.inputs)==null?void 0:s.filter(p=>p.source==="query"),n=(u=a==null?void 0:a.find(p=>p.position===t))==null?void 0:u.name;return n?e.get(n):null}getCombinedTokenTransfers(r,t){var a;return[...((a=r.transfers)==null?void 0:a.map(this.toTypedTransfer))||[],...t]}getTypedArgsFromInput(r){return r.map(t=>{let[e,a]=t.split(":");return this.toTypedArg(a,e)})}toTypedTransfer(r){return new J({token:new G({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return U.fromUTF8(r);if(t==="uint8")return new Y(Number(r));if(t==="uint16")return new M(Number(r));if(t==="uint32")return new Z(Number(r));if(t==="uint64")return new X(BigInt(r));if(t==="biguint")return new H(BigInt(r));if(t==="boolean")return new j(r==="true");if(t==="address")return new Q(I.newFromBech32(r));if(t==="hex")return U.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};import{Address as S,ApiNetworkProvider as rr,TransactionsFactoryConfig as tr,TransferTransactionsFactory as er}from"@multiversx/sdk-core";import nr from"ajv";var y={Warp:i=>`warp:${i}`,WarpInfo:i=>`warp-info:${i}`,Brand:i=>`brand:${i}`},f=class{cache=new Map;set(r,t,e){let a=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:a})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var T=class{config;cache=new f;pendingWarp={protocol:B(o.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new tr({chainID:m(this.config.env)}),e=new er({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:S.newFromBech32(this.config.userAddress),receiver:S.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=y.Warp(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),n}let a=new rr(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=await this.createFromTransaction(n);return t&&t.ttl&&s&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}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.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),n=new nr,s=n.compile(a);if(!s(r))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import ur from"qr-code-styling";import{AbiRegistry as E,Address as l,AddressValue as L,ApiNetworkProvider as k,BytesValue as g,QueryRunnerAdapter as ir,SmartContractQueriesController as sr,SmartContractTransactionsFactory as or,TransactionsFactoryConfig as cr}from"@multiversx/sdk-core/out";var P={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.50.6"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"}],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:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<WarpInfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"WarpInfoView"}]},{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}]}],esdtAttributes:[],hasCallback:!1,types:{WarpInfoView:{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>"}]}}};var v=class{config;unitPrice;cache=new f;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[g.fromHex(r),g.fromUTF8(t)]:[g.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r),g.fromUTF8(t)]})}createBrandRegisterTransaction(r){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");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.newFromBech32(this.config.userAddress),contract:l.newFromBech32(o.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[g.fromHex(r),g.fromHex(t)]})}async getInfoByAlias(r,t){let e=y.WarpInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByAlias): WarpInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByAlias",arguments:[g.fromUTF8(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?W(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:c,brand:h},t.ttl),{warp:c,brand:h}}async getInfoByHash(r,t){let e=y.WarpInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByHash): WarpInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByHash",arguments:[g.fromHex(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?W(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{warp:c,brand:h},t.ttl),{warp:c,brand:h}}async getUserWarpInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserWarps",arguments:[new L(new l(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s);return u.map(W)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserBrands",arguments:[new L(new l(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s),p=u.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(r,t){let e=y.Brand(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),n}let a=new k(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let r=o.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),a=await t.runQuery(e),[n]=t.parseQueryResponse(a),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let r=new cr({chainID:m(this.config.env)}),t=E.create(P);return new or({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),t=new k(r,{timeout:3e4}),e=new ir({networkProvider:t}),a=E.create(P);return new sr({queryRunner:e,abi:a})}};var R="xwarp",C=":",N="alias",V=class{constructor(r){this.config=r;this.config=r}async detect(r){let a=new URL(r).searchParams.get(R);if(!a)return{match:!1,warp:null,brand:null};let n=decodeURIComponent(a),s=n.includes(C)?n:`${N}${C}${n}`,[u,p]=s.split(C),c=new T(this.config),h=new v(this.config),d=null,b=null;if(u==="hash"){d=await c.createFromTransactionHash(p);try{let{brand:w}=await h.getInfoByHash(p);b=w}catch{}}else if(u==="alias"){let{warp:A,brand:w}=await h.getInfoByAlias(p);A&&(d=await c.createFromTransactionHash(A.hash),b=w)}return d?{match:!0,warp:d,brand:b}:{match:!1,warp:null,brand:null}}build(r,t){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env);return r===N?`${e}?${R}=${encodeURIComponent(t)}`:`${e}?${R}=${encodeURIComponent(r+C+t)}`}generateQrCode(r,t,e=512,a="white",n="black",s="#23F7DD"){let u=this.build(r,t);return new ur({type:"svg",width:e,height:e,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};export{x as BrandBuilder,o as Config,q as WarpActionExecutor,T as WarpBuilder,V as WarpLink,v as WarpRegistry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "0.0.64",
3
+ "version": "0.0.66",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",