@joai/warps-adapter-sui 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -226,6 +226,7 @@ declare class WarpSuiWallet implements AdapterWarpWallet {
226
226
  importFromPrivateKey(privateKey: string): Promise<WarpWalletDetails>;
227
227
  export(provider: WarpWalletProvider): Promise<WarpWalletDetails>;
228
228
  generate(provider: WarpWalletProvider): Promise<WarpWalletDetails>;
229
+ delete(provider: WarpWalletProvider, externalId: string): Promise<void>;
229
230
  getAddress(): string | null;
230
231
  getPublicKey(): string | null;
231
232
  private createProvider;
package/dist/index.d.ts CHANGED
@@ -226,6 +226,7 @@ declare class WarpSuiWallet implements AdapterWarpWallet {
226
226
  importFromPrivateKey(privateKey: string): Promise<WarpWalletDetails>;
227
227
  export(provider: WarpWalletProvider): Promise<WarpWalletDetails>;
228
228
  generate(provider: WarpWalletProvider): Promise<WarpWalletDetails>;
229
+ delete(provider: WarpWalletProvider, externalId: string): Promise<void>;
229
230
  getAddress(): string | null;
230
231
  getPublicKey(): string | null;
231
232
  private createProvider;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var wr=Object.create;var H=Object.defineProperty;var Cr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var Ar=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var Er=(o,r)=>{for(var e in r)H(o,e,{get:r[e],enumerable:!0})},X=(o,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of br(r))!Sr.call(o,n)&&n!==e&&H(o,n,{get:()=>r[n],enumerable:!(t=Cr(r,n))||t.enumerable});return o};var Pr=(o,r,e)=>(e=o!=null?wr(Ar(o)):{},X(r||!o||!o.__esModule?H(e,"default",{value:o,enumerable:!0}):e,o)),Ir=o=>X(H({},"__esModule",{value:!0}),o);var kr={};Er(kr,{ExplorerUrls:()=>C,KnownTokens:()=>lr,NativeTokenSui:()=>V,SuiAdapter:()=>Rr,SuiExplorers:()=>Y,SuiExplorersConfig:()=>G,WarpSuiAbiBuilder:()=>S,WarpSuiBrandBuilder:()=>D,WarpSuiBuilder:()=>$,WarpSuiConstants:()=>xr,WarpSuiContractLoader:()=>q,WarpSuiDataLoader:()=>O,WarpSuiExecutor:()=>j,WarpSuiExplorer:()=>F,WarpSuiOutput:()=>E,WarpSuiRegistry:()=>z,WarpSuiSerializer:()=>w,WarpSuiWallet:()=>_,findKnownTokenById:()=>L,getConfiguredSuiClient:()=>Q,getSuiRegistryObjectId:()=>Tr,getSuiRegistryPackageId:()=>K,toRegistryMoveTarget:()=>p,toTypedRegistryInfo:()=>N});module.exports=Ir(kr);var K=o=>{if(o==="devnet")throw new Error("Sui registry package id is not available for devnet");if(o==="testnet")return"0xc8824c98b09d36eec6c8b69ae7083e0b012b5e516e2f7a54c75bfa8a80105753";throw new Error("Sui registry package id is not available for mainnet")},Tr=o=>{if(o==="devnet")throw new Error("Sui registry object id is not available for devnet");if(o==="testnet")return"";throw new Error("Sui registry object id is not available for mainnet")};var xr={Sui:{Identifier:"SUI",DisplayName:"Sui",Decimals:9}},Y=(a=>(a.SuiVision="suivision",a.SuiVisionTestnet="suivision_testnet",a.SuiVisionDevnet="suivision_devnet",a.SuiScan="suiscan",a.SuiScanTestnet="suiscan_testnet",a.SuiScanDevnet="suiscan_devnet",a))(Y||{}),G={sui:{mainnet:["suivision","suiscan"],testnet:["suivision_testnet","suiscan_testnet"],devnet:["suivision_devnet","suiscan_devnet"]}},C={suivision:"https://suivision.xyz",suivision_testnet:"https://testnet.suivision.xyz",suivision_devnet:"https://devnet.suivision.xyz",suiscan:"https://suiscan.xyz",suiscan_testnet:"https://testnet.suiscan.xyz",suiscan_devnet:"https://devnet.suiscan.xyz"};var Z=require("@mysten/sui/client"),rr=require("@joai/warps"),Q=(o,r)=>{let e=(0,rr.getProviderConfig)(o,r.name,o.env,r.defaultApiUrl);return new Z.SuiClient({url:e.url})};var p=(o,r)=>`${K(o)}::${r}`,Br=o=>{let r=Buffer.from(o).toString();return r==="unverified"||r==="verified"||r==="blacklisted"?r:"unverified"},N=o=>({hash:Buffer.from(o.hash).toString("hex"),alias:o.alias?Buffer.from(o.alias).toString():null,trust:Br(o.trust),owner:o.owner,createdAt:Number(o.created_at),upgradedAt:Number(o.upgraded_at),brand:o.brand?Buffer.from(o.brand).toString("hex"):null,upgrade:o.upgrade?Buffer.from(o.upgrade).toString("hex"):null});var k=require("@joai/warps");var er=require("@mysten/sui/client"),tr=require("@joai/warps"),S=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,tr.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new er.SuiClient({url:t.url})}async createInscriptionTransaction(r){throw new Error("WarpSuiAbiBuilder: createInscriptionTransaction not implemented")}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t):null}catch{return null}}async getModuleAbi(r,e){return this.client.getNormalizedMoveModule({package:r,module:e})}async getFunctionAbi(r,e,t){return this.client.getNormalizedMoveFunction({package:r,module:e,function:t})}};var nr=require("@mysten/sui/client"),ir=require("@mysten/sui/transactions"),ar=require("@joai/warps"),D=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,ar.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new nr.SuiClient({url:t.url})}createInscriptionTransaction(r){return new ir.Transaction}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r,e){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t,!1):null}catch{return null}}};var sr=require("@mysten/sui/client"),or=require("@mysten/sui/transactions"),b=require("@joai/warps");var $=class extends b.WarpBuilder{constructor(e,t){super(e);this.config=e;this.chain=t;this.cache=new b.WarpCache(e.env,e.cache);let n=(0,b.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new sr.SuiClient({url:n.url}),this.userWallet=(0,b.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async createInscriptionTransaction(e,t){if(!t)throw new Error("WarpSuiBuilder: registryObjectId is required");if(!this.userWallet)throw new Error("WarpSuiBuilder: user address not set");if(!e.meta||!e.meta.hash)throw new Error("WarpSuiBuilder: warp.meta.hash is required");let n=Array.from(Buffer.from(e.meta.hash,"hex")),i=e.meta?.alias??void 0,a=e.meta?.brand?Array.from(Buffer.from(e.meta.brand,"hex")):void 0,s=new or.Transaction;return s.moveCall({target:p(this.config.env,"register_warp"),arguments:[s.object(t),s.pure.vector("u8",n),i?s.pure.option("string",i):s.pure.option("string",void 0),a?s.pure.option("vector<u8>",a):s.pure.option("vector<u8>",void 0),s.gas,s.pure.address(this.userWallet)]}),s}async createFromNetwork(e,t){let n=`sui:warp:${e}`;if(t){let i=this.cache.get(n);if(i)return i}try{let i=await this.client.call(`${p(this.config.env,"get_info_by_hash")}`,[e,Array.from(Buffer.from(e,"hex"))]);if(!i||!Object.prototype.hasOwnProperty.call(i,"hash")||!i.hash)return null;let a=this.createFromRaw(i);return t&&t.ttl&&a&&this.cache.set(n,a,t.ttl),a}catch{return null}}async createFromTransaction(e){return this.createFromRaw(e)}async createFromTransactionHash(e,t){return this.createFromNetwork(e,t)}};var pr=require("@mysten/sui/client"),A=require("@joai/warps");var cr=require("@joai/warps"),v=cr.WarpChainName.Sui,lr=[{chain:v,identifier:"0x2::sui::SUI",name:"Sui",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/small/sui-logo.png"},{chain:v,identifier:"0xa198f3be41cda8c07c3bf1c4e0bb88b8e9827b7c063f36b1e6c3d6da1c4e8753::usdc::USDC",name:"USD Coin",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"},{chain:v,identifier:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48ace0cdd97::usdt::USDT",name:"Tether USD",symbol:"USDT",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/325/small/Tether.png"},{chain:v,identifier:"0xaf8cd5edc19c4512f4259f0bee101a7c94d8a5c0e7c90c7a7c8c8c8c8c8c8c8c8::wbtc::WBTC",name:"Wrapped Bitcoin",symbol:"WBTC",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/7598/small/wrapped_bitcoin_wbtc.png"},{chain:v,identifier:"0xb8a6a9b7c7a6f4a3e2d1c0b9a8f7e6d5c4b3a2b1c0d9e8f7a6b5c4d3e2f1a0b::weth::WETH",name:"Wrapped Ether",symbol:"WETH",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/2518/small/weth.png"},{chain:v,identifier:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a15e0e9::ocean::OCEAN",name:"Ocean Protocol",symbol:"OCEAN",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/3687/small/ocean-protocol-logo.png"},{chain:v,identifier:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c35569693fd50fb8b7::deep::DEEP",name:"DeepBook",symbol:"DEEP",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/30169/small/deepbook.png"},{chain:v,identifier:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47ba3::hasui::HASUI",name:"Haedal Staked SUI",symbol:"HASUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/30027/small/haSUI.png"},{chain:v,identifier:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e935::usdc::USDC",name:"USD Coin (Wormhole)",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"}],L=o=>lr.find(r=>r.identifier===o)||null;var O=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,A.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new pr.SuiClient({url:t.url}),this.cache=new A.WarpCache(r.env,r.cache)}async getAccount(r){let e=await this.client.getBalance({owner:r,coinType:"0x2::sui::SUI"});return{chain:this.chain.name,address:r,balance:BigInt(e.totalBalance)}}async getAccountAssets(r){let e=await this.client.getAllBalances({owner:r});console.log("WarpSuiDataLoader.getAccountAssets",e);let t=e.find(a=>a.coinType==="0x2::sui::SUI"),n=e.filter(a=>a.coinType!=="0x2::sui::SUI"&&BigInt(a.totalBalance)>0n),i=[];if(t&&BigInt(t.totalBalance)>0n&&i.push({...this.chain.nativeToken,amount:BigInt(t.totalBalance)}),n.length>0){let a=await Promise.all(n.map(s=>this.getAsset(s.coinType)));i.push(...a.filter(s=>s!==null).map(s=>({...s,amount:BigInt(n.find(c=>c.coinType===s.identifier)?.totalBalance||0)})))}return i}async getAsset(r){let e=A.WarpCacheKey.Asset(this.config.env,this.chain.name,r),t=this.cache.get(e);if(t)return t;let n=L(r);if(n)return{chain:this.chain.name,identifier:r,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};try{let i=await this.client.getCoinMetadata({coinType:r}),a={chain:this.chain.name,identifier:r,name:i?.name||r.split("::").pop()||r,symbol:i?.symbol||r.split("::").pop()||r,amount:0n,decimals:i?.decimals||9,logoUrl:i?.iconUrl||""};return this.cache.set(e,a,A.CacheTtl.OneHour),a}catch{return null}}async getAction(r,e=!1){return null}async getAccountActions(r,e){return[]}};var fr=require("@mysten/sui/client"),J=require("@mysten/sui/transactions"),f=require("@joai/warps");var dr=require("@mysten/sui/client"),u=require("@joai/warps");var ur=require("@mysten/sui/transactions"),gr=require("@joai/warps"),w=class{constructor(){this.coreSerializer=new gr.WarpSerializer}typedToString(r){if(r==null)return"option:null";if(typeof r=="string")return`string:${r}`;if(typeof r=="boolean")return`bool:${r}`;if(typeof r=="number")return`uint64:${r.toString()}`;if(typeof r=="bigint")return`uint64:${r.toString()}`;if(r&&typeof r=="object"&&r.address)return`address:${r.address}`;if(Array.isArray(r)){if(r.length===0)return"vector:u8:";let e=this.typeToString(typeof r[0]),t=r.map(n=>this.typedToString(n).split(":")[1]);return`vector:${e}:${t.join(",")}`}if(r&&typeof r=="object"&&r.type&&r.value&&r.type==="option")return r.value===null||r.value===void 0?"option:null":`option:${this.typedToString(r.value)}`;throw new Error(`WarpSuiSerializer (typedToString): Unsupported input type: ${typeof r}`)}typedToNative(r){let e=this.typedToString(r);return this.coreSerializer.stringToNative(e)}nativeToTyped(r,e){let t=this.coreSerializer.nativeToString(r,e);return this.stringToTyped(t)}stringToTyped(r,e){let t=e||new ur.Transaction,[n,i]=r.split(/:(.*)/,2);if(n==="object")return t.object(i);if(n==="string")return t.pure.string(i);if(n==="bool")return t.pure.bool(i==="true");if(n==="u8")return t.pure.u8(Number(i));if(n==="u16")return t.pure.u16(Number(i));if(n==="u32")return t.pure.u32(Number(i));if(n==="u64"||n==="uint64")return t.pure.u64(BigInt(i));if(n==="u128")return t.pure.u128(BigInt(i));if(n==="u256")return t.pure.u256(BigInt(i));if(n==="address")return t.pure.address(i);throw new Error(`WarpSuiSerializer (stringToTyped): Unsupported type: ${n}`)}typeToString(r){if(r==="string")return"string";if(r==="bool")return"bool";if(r==="u8")return"u8";if(r==="u16")return"u16";if(r==="u32")return"u32";if(r==="u64"||r==="bigint"||r==="number")return"u64";if(r==="u128")return"u128";if(r==="u256")return"u256";if(r==="address")return"address";if(r==="vector")return"vector";if(r==="option")return"option";throw new Error(`WarpSuiSerializer (typeToString): Unsupported input type: ${r}`)}nativeToType(r){throw new Error("Not implemented")}};var E=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new w;let t=(0,u.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new dr.SuiClient({url:t.url})}async getActionExecution(r,e,t){let n=await this.extractContractOutput(r,e,t,[]),i=(0,u.getNextInfo)(this.config,[],r,e,n.output),a=(0,u.applyOutputToMessages)(r,n.output,this.config);return{status:t.effects?.status?.status==="success"?"success":"error",warp:r,action:e,user:(0,u.getWarpWalletAddressFromConfig)(this.config,this.chain.name),txHash:t.digest,tx:t,next:i,values:n.values,output:n.output,messages:a,destination:null,resolvedInputs:[]}}async extractContractOutput(r,e,t,n){let i=[],a=[],s={};if(!r.output)return{values:{string:i,native:a,mapped:{}},output:s};for(let[c,d]of Object.entries(r.output)){if(d.startsWith(u.WarpConstants.Transform.Prefix))continue;if(d.startsWith("input.")){s[c]=d;continue}let h=(0,u.parseOutputOutIndex)(d);if(h!==null&&h!==e){s[c]=null;continue}if(d.startsWith("out.")){let W=t.returnValues?t.returnValues[c]:null;s[c]=W,i.push(String(W)),a.push(W)}else s[c]=d}return{values:{string:i,native:a,mapped:{}},output:await(0,u.evaluateOutputCommon)(r,s,a,e,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(r,e,t,n){let i=e.map(d=>String(d)),a=e,s={string:i,native:a,mapped:{}},c={};if(!r.output)return{values:s,output:c};for(let[d,h]of Object.entries(r.output)){if(h.startsWith(u.WarpConstants.Transform.Prefix))continue;let W=(0,u.parseOutputOutIndex)(h);if(W!==null&&W!==t){c[d]=null;continue}if(h.startsWith("out.")||h==="out")if(Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null){let vr=h.replace(/^out\./,"");c[d]=e[0][vr]}else c[d]=e[0];else c[d]=h}return{values:s,output:await(0,u.evaluateOutputCommon)(r,c,a,t,n,this.serializer.coreSerializer,this.config)}}};var j=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new w,this.output=new E(this.config,this.chain);let t=(0,f.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new fr.SuiClient({url:t.url}),this.userWallet=(0,f.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async createTransaction(r){let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(e.type==="transfer")return this.createTransferTransaction(r);if(e.type==="contract")return this.createContractCallTransaction(r);throw e.type==="query"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeQuery instead"):e.type==="collect"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeCollect instead"):new Error(`WarpSuiExecutor: Invalid action type (${e.type})`)}async createTransferTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createTransfer - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid destination address");if(r.value<0)throw new Error(`WarpSuiExecutor: Transfer value cannot be negative: ${r.value}`);let e=new J.Transaction,t=[];if(r.value>0){let n=await this.handleCoinTransfer(e,"0x2::sui::SUI",r.value);t.push(n)}for(let n of r.transfers){let i=await this.handleCoinTransfer(e,n.identifier,n.amount);t.push(i)}return t.length>0&&e.transferObjects(t,e.pure.address(r.destination)),e}async createContractCallTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createContractCall - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid contract address");if(r.value<0)throw new Error(`WarpSuiExecutor: Contract call value cannot be negative: ${r.value}`);let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(!e.func)throw new Error("WarpSuiExecutor: createContractCall - function not set");let t=new J.Transaction;t.setSender(this.userWallet);let n=[];r.value>0&&n.push(await this.handleCoinTransfer(t,"0x2::sui::SUI",r.value));for(let c of r.transfers)n.push(await this.handleCoinTransfer(t,c.identifier,c.amount));let{target:i,typeArguments:a}=this.parseMoveCallTarget(e),s=r.args.map(c=>this.serializer.stringToTyped(c,t));return i==="0x2::transfer::public_transfer"?n.push(...await this.buildPublicTransferArgs(t,r,s)):n.push(...s),t.moveCall({target:i,arguments:n,typeArguments:a}),t.setGasBudget(1e8),t}async executeQuery(r){if(!r.destination)throw new Error("WarpSuiExecutor: executeQuery - destination not set");let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(e.type!=="query")throw new Error(`WarpSuiExecutor: Invalid action type for executeQuery: ${e.type}`);let t=await this.client.getObject({id:r.destination,options:{showContent:!0}}),n=[t],{values:i,output:a}=await this.output.extractQueryOutput(r.warp,n,r.action,r.resolvedInputs),s=(0,f.getNextInfo)(this.config,[],r.warp,r.action,a),d=r.resolvedInputs.find(W=>W.input.position==="receiver"||W.input.position==="destination")?.value||r.destination,h=(0,f.extractResolvedInputValues)(r.resolvedInputs);return{status:"success",warp:r.warp,action:r.action,user:this.userWallet,txHash:null,tx:null,next:s,values:i,output:{...a,_DATA:t},resolvedInputs:h,messages:(0,f.applyOutputToMessages)(r.warp,a,this.config),destination:d}}async signMessage(r,e){throw new Error("Not implemented")}parseMoveCallTarget(r){if(!r.func)throw new Error("WarpSuiExecutor: Function not set");let e=`${r.address}::${r.func}`,t=r.typeArguments;if(!t&&r.func.includes("<")&&r.func.includes(">")){let n=r.func.match(/<([^>]+)>/);n&&(t=[n[1]],e=`${r.address}::${r.func.replace(/<[^>]+>/,"")}`)}return{target:e,typeArguments:t}}async buildPublicTransferArgs(r,e,t){let n=e.resolvedInputs.find(s=>String(s.input.position)==="arg:0")?.value||e.args[0],i=e.resolvedInputs.find(s=>String(s.input.position)==="arg:1")?.value||e.resolvedInputs.find(s=>s.input.type==="address"&&String(s.input.position)!=="arg:0")?.value||e.args[1],a=this.extractObjectId(n);if(!a)return t;try{if(!(await this.client.getObject({id:a,options:{showType:!0,showContent:!0}})).data?.type?.startsWith("0x2::coin::Coin<"))return t;let c=i?this.serializer.stringToTyped(i.includes(":")?i:`address:${i}`,r):t[1]||r.pure.address(this.userWallet);return[r.object(a),c]}catch{return t}}extractObjectId(r){if(!r||typeof r!="string")return null;let e=r.startsWith("object:")?r.substring(7):r;return e.startsWith("0x")?e:null}async handleCoinTransfer(r,e,t){if(e==="0x2::sui::SUI")try{return r.splitCoins(r.gas,[t.toString()])[0]}catch{}return this.createCoinTransferFromObjects(r,e,t)}async createCoinTransferFromObjects(r,e,t){let n=await this.getCoinObjectsForTransfer(e,t);if(n.length===0)throw new Error(`No coin objects found for ${e}`);let i=r.object(n[0].coinObjectId);return n.length>1&&r.mergeCoins(i,n.slice(1).map(a=>r.object(a.coinObjectId))),r.splitCoins(i,[t.toString()])[0]}async getCoinObjectsForTransfer(r,e){if(!this.userWallet)throw new Error("User wallet not set");let{data:t}=await this.client.getCoins({owner:this.userWallet,coinType:r}),n=t.map(s=>({coinObjectId:s.coinObjectId,balance:s.balance})).sort((s,c)=>BigInt(c.balance)>BigInt(s.balance)?1:-1),i=BigInt(0),a=[];for(let s of n)if(a.push(s),i+=BigInt(s.balance),i>=e)return a;throw new Error(`Insufficient ${r} balance. Required: ${e}, Available: ${i}`)}};var F=class{constructor(r,e){this.config=r;this.chain=e}getExplorers(){let r=G[this.chain.name];if(!r)return["suivision"];let e=r[this.config.env];return e||["suivision"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(r){let e=this.config.preferences?.explorers?.[this.chain.name];if(e&&!r){let i=C[e];if(i)return i}if(r){let i=C[r];if(i)return i}let t=this.getPrimaryExplorer();return C[t]||C[t]}getAccountUrl(r,e){return`${this.getExplorerUrlByName(e)}/account/${r}`}getTransactionUrl(r,e){return`${this.getExplorerUrlByName(e)}/txblock/${r}`}getBlockUrl(r,e){return`${this.getExplorerUrlByName(e)}/block/${r}`}getAssetUrl(r,e){return`${this.getExplorerUrlByName(e)}/coin/${r}`}getContractUrl(r,e){return`${this.getExplorerUrlByName(e)}/object/${r}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(r){return this.getExplorers().find(t=>t.toLowerCase()===r.toLowerCase())}getAccountUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(n=>{let i=C[n];i&&(t[n]=`${i}/account/${r}`)}),t}getTransactionUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(n=>{let i=C[n];i&&(t[n]=`${i}/txblock/${r}`)}),t}};var hr=require("@mysten/sui/client"),m=require("@mysten/sui/transactions"),l=require("@joai/warps");var z=class{constructor(r,e){this.config=r;this.chain=e;this.registryConfig={unitPrice:BigInt(0),admins:[]};let t=(0,l.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new hr.SuiClient({url:t.url}),this.cache=new l.WarpCache(r.env,r.cache),this.userWallet=(0,l.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async loadRegistryConfigs(){try{let r=`${K(this.config.env)}::registry::get_config`;console.log("-- Loading registry configs",r);let e=new m.Transaction;e.moveCall({target:r,arguments:[]});let t=await this.client.devInspectTransactionBlock({transactionBlock:e,sender:"0x0000000000000000000000000000000000000000000000000000000000000000"});console.log("-- Registry configs loaded",t);let n=t.results?.[0]?.returnValues?.[0],i=n&&Array.isArray(n)&&n[0]?JSON.parse(String.fromCharCode(...n[0])):{};this.registryConfig={unitPrice:i.unit_price!==void 0?BigInt(i.unit_price):BigInt(0),admins:Array.isArray(i.admins)?i.admins:[]}}catch(r){l.WarpLogger.error("WarpSuiRegistry: Failed to load registry config",r),this.registryConfig={unitPrice:BigInt(0),admins:[]}}}async createWarpRegisterTransaction(r,e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=new m.Transaction;return n.moveCall({target:p(this.config.env,"register_warp"),arguments:[n.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e?n.pure.option("string",e):n.pure.option("string",void 0),t?n.pure.option("vector<u8>",Array.from(Buffer.from(t,"hex"))):n.pure.option("vector<u8>",void 0),n.gas,n.pure.address(this.userWallet)]}),n}async createWarpUnregisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new m.Transaction;return e.moveCall({target:p(this.config.env,"unregister_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpUpgradeTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new m.Transaction;return t.moveCall({target:p(this.config.env,"upgrade_warp"),arguments:[t.pure.string(r),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpAliasSetTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new m.Transaction;return t.moveCall({target:p(this.config.env,"set_warp_alias"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.string(e),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpVerifyTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new m.Transaction;return e.moveCall({target:p(this.config.env,"verify_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpTransferOwnershipTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new m.Transaction;return t.moveCall({target:p(this.config.env,"transfer_ownership"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.address(e),t.gas,t.pure.address(this.userWallet)]}),t}async createBrandRegisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new m.Transaction;return e.moveCall({target:p(this.config.env,"register_brand"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpBrandingTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new m.Transaction;return t.moveCall({target:p(this.config.env,"brand_warp"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async getInfoByAlias(r,e){let t=l.WarpCacheKey.RegistryInfo(this.config.env,r),n=e?this.cache.get(t):null;if(n)return l.WarpLogger.info(`WarpSuiRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),n;try{let i=await this.client.call(p(this.config.env,"get_info_by_alias"),[r]),a=i||null,s=a?N(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(i){return l.WarpLogger.error("WarpSuiRegistry (getInfoByAlias):",i),{registryInfo:null,brand:null}}}async getInfoByHash(r,e){let t=l.WarpCacheKey.RegistryInfo(this.config.env,r),n=e?this.cache.get(t):null;if(n)return l.WarpLogger.info(`WarpSuiRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),n;try{let i=await this.client.call(p(this.config.env,"get_info_by_hash"),[Array.from(Buffer.from(r,"hex"))]),a=i||null,s=a?N(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(i){return l.WarpLogger.error("WarpSuiRegistry (getInfoByHash):",i),{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(r){let e=`sui:registry:user:${r||this.userWallet}`,t=this.cache.get(e);if(t)return l.WarpLogger.info(`WarpSuiRegistry (getUserWarpRegistryInfos): RegistryInfos found in cache for user: ${r||this.userWallet}`),t;try{let n=r||this.userWallet;if(!n)throw new Error("WarpRegistry: user address not set");let i=await this.client.call(p(this.config.env,"get_user_warps"),[n]),a=Array.isArray(i)?i.map(N):[];return r&&this.cache.set(e,a,300),a}catch(n){return l.WarpLogger.error("WarpSuiRegistry (getUserWarpRegistryInfos):",n),[]}}async getUserBrands(r){let e=`sui:registry:user:brands:${r||this.userWallet}`,t=this.cache.get(e);if(t)return l.WarpLogger.info(`WarpSuiRegistry (getUserBrands): Brands found in cache for user: ${r||this.userWallet}`),t;try{let n=r||this.userWallet;if(!n)throw new Error("WarpRegistry: user address not set");let i=await this.client.call(p(this.config.env,"get_user_brands"),[n]);if(!Array.isArray(i))return[];let s=(await Promise.all(i.map(c=>this.fetchBrand(c)))).filter(c=>c!==null);return r&&this.cache.set(e,s,300),s}catch(n){return l.WarpLogger.error("WarpSuiRegistry (getUserBrands):",n),[]}}async fetchBrand(r,e){let t=l.WarpCacheKey.Brand(this.config.env,r),n=e?this.cache.get(t):null;if(n)return l.WarpLogger.info(`WarpSuiRegistry (fetchBrand): Brand found in cache: ${r}`),n;try{let i=await this.client.getTransactionBlock({digest:r});if(!i||!i.effects)return null;let a=null;if(i.events&&Array.isArray(i.events)){for(let s of i.events)if(s.type&&typeof s.type=="string"&&s.type.includes("BrandRegistered"))try{a=s.parsedJson;break}catch{}}if(!a&&i.objectChanges&&Array.isArray(i.objectChanges)){for(let s of i.objectChanges)if(s.type==="created"&&s.objectType&&s.objectType.includes("Brand"))try{break}catch{}}return a?(a.meta={hash:r,creator:i.transaction&&i.transaction.data&&i.transaction.data.sender?i.transaction.data.sender:void 0,createdAt:i.timestampMs?new Date(Number(i.timestampMs)).toISOString():void 0},e&&e.ttl&&this.cache.set(t,a,e.ttl),a):null}catch(i){return l.WarpLogger.error("WarpSuiRegistry (fetchBrand):",i),null}}};var Wr=require("@joai/warps");var M=require("@mysten/sui/keypairs/ed25519"),mr=Pr(require("@scure/bip39"),1),yr=require("@scure/bip39/wordlists/english.js"),g=require("@joai/warps"),P=class P{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return(0,g.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),n=await e.signPersonalMessage(t);return{...r,signature:n.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=(0,g.normalizeAndValidateMnemonic)(r),n=M.Ed25519Keypair.deriveKeypair(e).getPublicKey().toSuiAddress(),i={provider:P.PROVIDER_NAME,address:n,privateKey:null,mnemonic:e};return(0,g.setWarpWalletInConfig)(this.config,this.chain.name,i),i}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let i=M.Ed25519Keypair.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:P.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return(0,g.setWarpWalletInConfig)(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=(0,g.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name),t=(0,g.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);return{provider:P.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:t||null,mnemonic:e||null}}async generate(){let r=mr.generateMnemonic(yr.wordlist,256),e=(0,g.normalizeMnemonic)(r);(0,g.validateMnemonicLength)(e);let n=M.Ed25519Keypair.deriveKeypair(e).getPublicKey().toSuiAddress();return{provider:P.PROVIDER_NAME,address:n,privateKey:null,mnemonic:e}}getKeypair(){if(this.keypair)return this.keypair;let r=(0,g.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);if(!r)throw new Error("No mnemonic provided");return this.keypair=M.Ed25519Keypair.deriveKeypair(r.trim()),this.keypair}};P.PROVIDER_NAME="mnemonic";var x=P;var B=require("@joai/warps"),I=class{constructor(r,e){this.config=r;this.chain=e}async getAddress(){return(0,B.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async signMessage(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromMnemonic(r){let e=(0,B.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromPrivateKey(r){let e=(0,B.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async export(){let r=(0,B.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async generate(){let r=(0,B.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}};var U=require("@mysten/sui/keypairs/ed25519"),y=require("@joai/warps"),T=class T{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return(0,y.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),n=await e.signPersonalMessage(t);return{...r,signature:n.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=U.Ed25519Keypair.deriveKeypair(r.trim()),t=e.getPublicKey().toSuiAddress(),n=Buffer.from(e.getSecretKey()).toString("hex"),i={provider:T.PROVIDER_NAME,address:t,privateKey:n,mnemonic:r};return(0,y.setWarpWalletInConfig)(this.config,this.chain.name,i),i}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let i=U.Ed25519Keypair.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:T.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return(0,y.setWarpWalletInConfig)(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=(0,y.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name),t=(0,y.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);return{provider:T.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:e||null,mnemonic:t||null}}async generate(){let r=U.Ed25519Keypair.generate(),e=r.getPublicKey().toSuiAddress(),t=Buffer.from(r.getSecretKey()).toString("hex");return{provider:T.PROVIDER_NAME,address:e,privateKey:t,mnemonic:null}}getKeypair(){if(this.keypair)return this.keypair;let r=(0,y.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);if(!r)throw new Error("Wallet not initialized - no private key provided");try{let e=Buffer.from(r,"hex");if(e.length===70){let t=new Uint8Array(e.subarray(1,33));return this.keypair=U.Ed25519Keypair.fromSecretKey(t),this.keypair}else{if(e.length===32)return this.keypair=U.Ed25519Keypair.fromSecretKey(new Uint8Array(e)),this.keypair;throw new Error(`Unsupported private key length: ${e.length} bytes`)}}catch(e){throw e}}};T.PROVIDER_NAME="privateKey";var R=T;var _=class{constructor(r,e){this.config=r;this.chain=e;this.cachedAddress=null;this.cachedPublicKey=null;this.client=Q(r,e),this.walletProvider=this.createProvider(),this.isInitializedPromise=new Promise(t=>{this.isInitializedResolve=t}),this.initializeCache()}async waitUntilInitialized(){await this.isInitializedPromise}async signTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof I)throw new Error(`Wallet (${this.chain.name}) is read-only`);return(this.walletProvider instanceof R||this.walletProvider instanceof x)&&r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function"?r:await this.walletProvider.signTransaction(r)}async signMessage(r){if(await this.waitUntilInitialized(),!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof I)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(r)}async signTransactions(r){return await this.waitUntilInitialized(),r}async sendTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(r.transactionHash)return r.transactionHash;if(r&&typeof r=="object"&&"bytes"in r&&"signature"in r)return(await this.client.executeTransactionBlock({transactionBlock:r.bytes,signature:Array.isArray(r.signature)?r.signature:[r.signature],options:{showEffects:!0,showEvents:!0}})).digest;if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof R||this.walletProvider instanceof x){let e=this.walletProvider.getKeypairInstance();if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return(await this.client.signAndExecuteTransaction({transaction:r,signer:e,options:{showEffects:!0,showEvents:!0}})).digest;throw new Error(`Transaction must be a Transaction object or have bytes and signature. Got: ${typeof r}, has sign: ${r&&typeof r=="object"&&"sign"in r}, has bytes: ${r&&typeof r=="object"&&"bytes"in r}, has signature: ${r&&typeof r=="object"&&"signature"in r}`)}throw new Error("Remote wallet provider must return signed payload (bytes + signature) or transactionHash for Sui transactions")}async sendTransactions(r){return await this.waitUntilInitialized(),Promise.all(r.map(async e=>this.sendTransaction(e)))}async importFromMnemonic(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("mnemonic").importFromMnemonic(r)}async importFromPrivateKey(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("privateKey").importFromPrivateKey(r)}async export(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).export()}async generate(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let r=this.config.user?.wallets?.[this.chain.name];return r?typeof r=="string"?new I(this.config,this.chain):r.provider?this.createProviderForOperation(r.provider):new I(this.config,this.chain):null}async initializeCache(){let r=await(0,Wr.initializeWalletCache)(this.walletProvider);this.cachedAddress=r.address,this.cachedPublicKey=r.publicKey,this.isInitializedResolve()}createProviderForOperation(r){let t=this.config.walletProviders?.[this.chain.name]?.[r];if(t){let n=t(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${r}`);return n}if(r==="privateKey")return new R(this.config,this.chain);if(r==="mnemonic")return new x(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${r}`)}};var V={chain:k.WarpChainName.Sui,identifier:"0x2::sui::SUI",name:"SUI",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/standard/sui-ocean-square.png?1727791290"};function Ur(o,r){return(e,t)=>{let n=r[e.env];if(!n)throw new Error(`SuiAdapter: chain info not found for chain ${o}`);return{chainInfo:n,builder:()=>new $(e,n),executor:new j(e,n),output:new E(e,n),serializer:new w,registry:new z(e,n),explorer:new F(e,n),abiBuilder:()=>new S(e,n),brandBuilder:()=>new D(e,n),dataLoader:new O(e,n),wallet:new _(e,n)}}}var Rr=Ur(k.WarpChainName.Sui,{mainnet:{name:k.WarpChainName.Sui,displayName:"Sui",chainId:"1",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.mainnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V},testnet:{name:k.WarpChainName.Sui,displayName:"Sui Testnet",chainId:"testnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.testnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V},devnet:{name:k.WarpChainName.Sui,displayName:"Sui Devnet",chainId:"devnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.devnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V}});var q=class{constructor(r,e){this.abi=new S(r,e)}async loadModuleAbi(r,e){return this.abi.getModuleAbi(r,e)}async loadFunctionAbi(r,e,t){return this.abi.getFunctionAbi(r,e,t)}};0&&(module.exports={ExplorerUrls,KnownTokens,NativeTokenSui,SuiAdapter,SuiExplorers,SuiExplorersConfig,WarpSuiAbiBuilder,WarpSuiBrandBuilder,WarpSuiBuilder,WarpSuiConstants,WarpSuiContractLoader,WarpSuiDataLoader,WarpSuiExecutor,WarpSuiExplorer,WarpSuiOutput,WarpSuiRegistry,WarpSuiSerializer,WarpSuiWallet,findKnownTokenById,getConfiguredSuiClient,getSuiRegistryObjectId,getSuiRegistryPackageId,toRegistryMoveTarget,toTypedRegistryInfo});
1
+ "use strict";var wr=Object.create;var H=Object.defineProperty;var Cr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var Ar=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var Pr=(o,r)=>{for(var e in r)H(o,e,{get:r[e],enumerable:!0})},X=(o,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of br(r))!Sr.call(o,i)&&i!==e&&H(o,i,{get:()=>r[i],enumerable:!(t=Cr(r,i))||t.enumerable});return o};var Er=(o,r,e)=>(e=o!=null?wr(Ar(o)):{},X(r||!o||!o.__esModule?H(e,"default",{value:o,enumerable:!0}):e,o)),Ir=o=>X(H({},"__esModule",{value:!0}),o);var kr={};Pr(kr,{ExplorerUrls:()=>C,KnownTokens:()=>lr,NativeTokenSui:()=>V,SuiAdapter:()=>Rr,SuiExplorers:()=>Y,SuiExplorersConfig:()=>G,WarpSuiAbiBuilder:()=>P,WarpSuiBrandBuilder:()=>D,WarpSuiBuilder:()=>$,WarpSuiConstants:()=>xr,WarpSuiContractLoader:()=>q,WarpSuiDataLoader:()=>O,WarpSuiExecutor:()=>F,WarpSuiExplorer:()=>j,WarpSuiOutput:()=>E,WarpSuiRegistry:()=>z,WarpSuiSerializer:()=>w,WarpSuiWallet:()=>_,findKnownTokenById:()=>L,getConfiguredSuiClient:()=>Q,getSuiRegistryObjectId:()=>Tr,getSuiRegistryPackageId:()=>K,toRegistryMoveTarget:()=>u,toTypedRegistryInfo:()=>N});module.exports=Ir(kr);var K=o=>{if(o==="devnet")throw new Error("Sui registry package id is not available for devnet");if(o==="testnet")return"0xc8824c98b09d36eec6c8b69ae7083e0b012b5e516e2f7a54c75bfa8a80105753";throw new Error("Sui registry package id is not available for mainnet")},Tr=o=>{if(o==="devnet")throw new Error("Sui registry object id is not available for devnet");if(o==="testnet")return"";throw new Error("Sui registry object id is not available for mainnet")};var xr={Sui:{Identifier:"SUI",DisplayName:"Sui",Decimals:9}},Y=(a=>(a.SuiVision="suivision",a.SuiVisionTestnet="suivision_testnet",a.SuiVisionDevnet="suivision_devnet",a.SuiScan="suiscan",a.SuiScanTestnet="suiscan_testnet",a.SuiScanDevnet="suiscan_devnet",a))(Y||{}),G={sui:{mainnet:["suivision","suiscan"],testnet:["suivision_testnet","suiscan_testnet"],devnet:["suivision_devnet","suiscan_devnet"]}},C={suivision:"https://suivision.xyz",suivision_testnet:"https://testnet.suivision.xyz",suivision_devnet:"https://devnet.suivision.xyz",suiscan:"https://suiscan.xyz",suiscan_testnet:"https://testnet.suiscan.xyz",suiscan_devnet:"https://devnet.suiscan.xyz"};var Z=require("@mysten/sui/client"),rr=require("@joai/warps"),Q=(o,r)=>{let e=(0,rr.getProviderConfig)(o,r.name,o.env,r.defaultApiUrl);return new Z.SuiClient({url:e.url})};var u=(o,r)=>`${K(o)}::${r}`,Br=o=>{let r=Buffer.from(o).toString();return r==="unverified"||r==="verified"||r==="blacklisted"?r:"unverified"},N=o=>({hash:Buffer.from(o.hash).toString("hex"),alias:o.alias?Buffer.from(o.alias).toString():null,trust:Br(o.trust),owner:o.owner,createdAt:Number(o.created_at),upgradedAt:Number(o.upgraded_at),brand:o.brand?Buffer.from(o.brand).toString("hex"):null,upgrade:o.upgrade?Buffer.from(o.upgrade).toString("hex"):null});var k=require("@joai/warps");var er=require("@mysten/sui/client"),tr=require("@joai/warps"),P=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,tr.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new er.SuiClient({url:t.url})}async createInscriptionTransaction(r){throw new Error("WarpSuiAbiBuilder: createInscriptionTransaction not implemented")}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t):null}catch{return null}}async getModuleAbi(r,e){return this.client.getNormalizedMoveModule({package:r,module:e})}async getFunctionAbi(r,e,t){return this.client.getNormalizedMoveFunction({package:r,module:e,function:t})}};var ir=require("@mysten/sui/client"),nr=require("@mysten/sui/transactions"),ar=require("@joai/warps"),D=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,ar.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new ir.SuiClient({url:t.url})}createInscriptionTransaction(r){return new nr.Transaction}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r,e){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t,!1):null}catch{return null}}};var sr=require("@mysten/sui/client"),or=require("@mysten/sui/transactions"),b=require("@joai/warps");var $=class extends b.WarpBuilder{constructor(e,t){super(e);this.config=e;this.chain=t;this.cache=new b.WarpCache(e.env,e.cache);let i=(0,b.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new sr.SuiClient({url:i.url}),this.userWallet=(0,b.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async createInscriptionTransaction(e,t){if(!t)throw new Error("WarpSuiBuilder: registryObjectId is required");if(!this.userWallet)throw new Error("WarpSuiBuilder: user address not set");if(!e.meta||!e.meta.hash)throw new Error("WarpSuiBuilder: warp.meta.hash is required");let i=Array.from(Buffer.from(e.meta.hash,"hex")),n=e.meta?.alias??void 0,a=e.meta?.brand?Array.from(Buffer.from(e.meta.brand,"hex")):void 0,s=new or.Transaction;return s.moveCall({target:u(this.config.env,"register_warp"),arguments:[s.object(t),s.pure.vector("u8",i),n?s.pure.option("string",n):s.pure.option("string",void 0),a?s.pure.option("vector<u8>",a):s.pure.option("vector<u8>",void 0),s.gas,s.pure.address(this.userWallet)]}),s}async createFromNetwork(e,t){let i=`sui:warp:${e}`;if(t){let n=await this.cache.get(i);if(n)return n}try{let n=await this.client.call(`${u(this.config.env,"get_info_by_hash")}`,[e,Array.from(Buffer.from(e,"hex"))]);if(!n||!Object.prototype.hasOwnProperty.call(n,"hash")||!n.hash)return null;let a=this.createFromRaw(n);return t&&t.ttl&&a&&await this.cache.set(i,a,t.ttl),a}catch{return null}}async createFromTransaction(e){return this.createFromRaw(e)}async createFromTransactionHash(e,t){return this.createFromNetwork(e,t)}};var pr=require("@mysten/sui/client"),A=require("@joai/warps");var cr=require("@joai/warps"),v=cr.WarpChainName.Sui,lr=[{chain:v,identifier:"0x2::sui::SUI",name:"Sui",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/small/sui-logo.png"},{chain:v,identifier:"0xa198f3be41cda8c07c3bf1c4e0bb88b8e9827b7c063f36b1e6c3d6da1c4e8753::usdc::USDC",name:"USD Coin",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"},{chain:v,identifier:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48ace0cdd97::usdt::USDT",name:"Tether USD",symbol:"USDT",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/325/small/Tether.png"},{chain:v,identifier:"0xaf8cd5edc19c4512f4259f0bee101a7c94d8a5c0e7c90c7a7c8c8c8c8c8c8c8c8::wbtc::WBTC",name:"Wrapped Bitcoin",symbol:"WBTC",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/7598/small/wrapped_bitcoin_wbtc.png"},{chain:v,identifier:"0xb8a6a9b7c7a6f4a3e2d1c0b9a8f7e6d5c4b3a2b1c0d9e8f7a6b5c4d3e2f1a0b::weth::WETH",name:"Wrapped Ether",symbol:"WETH",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/2518/small/weth.png"},{chain:v,identifier:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a15e0e9::ocean::OCEAN",name:"Ocean Protocol",symbol:"OCEAN",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/3687/small/ocean-protocol-logo.png"},{chain:v,identifier:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c35569693fd50fb8b7::deep::DEEP",name:"DeepBook",symbol:"DEEP",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/30169/small/deepbook.png"},{chain:v,identifier:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47ba3::hasui::HASUI",name:"Haedal Staked SUI",symbol:"HASUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/30027/small/haSUI.png"},{chain:v,identifier:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e935::usdc::USDC",name:"USD Coin (Wormhole)",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"}],L=o=>lr.find(r=>r.identifier===o)||null;var O=class{constructor(r,e){this.config=r;this.chain=e;let t=(0,A.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new pr.SuiClient({url:t.url}),this.cache=new A.WarpCache(r.env,r.cache)}async getAccount(r){let e=await this.client.getBalance({owner:r,coinType:"0x2::sui::SUI"});return{chain:this.chain.name,address:r,balance:BigInt(e.totalBalance)}}async getAccountAssets(r){let e=await this.client.getAllBalances({owner:r});console.log("WarpSuiDataLoader.getAccountAssets",e);let t=e.find(a=>a.coinType==="0x2::sui::SUI"),i=e.filter(a=>a.coinType!=="0x2::sui::SUI"&&BigInt(a.totalBalance)>0n),n=[];if(t&&BigInt(t.totalBalance)>0n&&n.push({...this.chain.nativeToken,amount:BigInt(t.totalBalance)}),i.length>0){let a=await Promise.all(i.map(s=>this.getAsset(s.coinType)));n.push(...a.filter(s=>s!==null).map(s=>({...s,amount:BigInt(i.find(c=>c.coinType===s.identifier)?.totalBalance||0)})))}return n}async getAsset(r){let e=A.WarpCacheKey.Asset(this.config.env,this.chain.name,r),t=await this.cache.get(e);if(t)return t;let i=L(r);if(i)return{chain:this.chain.name,identifier:r,name:i.name,symbol:i.symbol,amount:0n,decimals:i.decimals,logoUrl:i.logoUrl};try{let n=await this.client.getCoinMetadata({coinType:r}),a={chain:this.chain.name,identifier:r,name:n?.name||r.split("::").pop()||r,symbol:n?.symbol||r.split("::").pop()||r,amount:0n,decimals:n?.decimals||9,logoUrl:n?.iconUrl||""};return await this.cache.set(e,a,A.CacheTtl.OneHour),a}catch{return null}}async getAction(r,e=!1){return null}async getAccountActions(r,e){return[]}};var fr=require("@mysten/sui/client"),J=require("@mysten/sui/transactions"),f=require("@joai/warps");var dr=require("@mysten/sui/client"),g=require("@joai/warps");var ur=require("@mysten/sui/transactions"),gr=require("@joai/warps"),w=class{constructor(){this.coreSerializer=new gr.WarpSerializer}typedToString(r){if(r==null)return"option:null";if(typeof r=="string")return`string:${r}`;if(typeof r=="boolean")return`bool:${r}`;if(typeof r=="number")return`uint64:${r.toString()}`;if(typeof r=="bigint")return`uint64:${r.toString()}`;if(r&&typeof r=="object"&&r.address)return`address:${r.address}`;if(Array.isArray(r)){if(r.length===0)return"vector:u8:";let e=this.typeToString(typeof r[0]),t=r.map(i=>this.typedToString(i).split(":")[1]);return`vector:${e}:${t.join(",")}`}if(r&&typeof r=="object"&&r.type&&r.value&&r.type==="option")return r.value===null||r.value===void 0?"option:null":`option:${this.typedToString(r.value)}`;throw new Error(`WarpSuiSerializer (typedToString): Unsupported input type: ${typeof r}`)}typedToNative(r){let e=this.typedToString(r);return this.coreSerializer.stringToNative(e)}nativeToTyped(r,e){let t=this.coreSerializer.nativeToString(r,e);return this.stringToTyped(t)}stringToTyped(r,e){let t=e||new ur.Transaction,[i,n]=r.split(/:(.*)/,2);if(i==="object")return t.object(n);if(i==="string")return t.pure.string(n);if(i==="bool")return t.pure.bool(n==="true");if(i==="u8")return t.pure.u8(Number(n));if(i==="u16")return t.pure.u16(Number(n));if(i==="u32")return t.pure.u32(Number(n));if(i==="u64"||i==="uint64")return t.pure.u64(BigInt(n));if(i==="u128")return t.pure.u128(BigInt(n));if(i==="u256")return t.pure.u256(BigInt(n));if(i==="address")return t.pure.address(n);throw new Error(`WarpSuiSerializer (stringToTyped): Unsupported type: ${i}`)}typeToString(r){if(r==="string")return"string";if(r==="bool")return"bool";if(r==="u8")return"u8";if(r==="u16")return"u16";if(r==="u32")return"u32";if(r==="u64"||r==="bigint"||r==="number")return"u64";if(r==="u128")return"u128";if(r==="u256")return"u256";if(r==="address")return"address";if(r==="vector")return"vector";if(r==="option")return"option";throw new Error(`WarpSuiSerializer (typeToString): Unsupported input type: ${r}`)}nativeToType(r){throw new Error("Not implemented")}};var E=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new w;let t=(0,g.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new dr.SuiClient({url:t.url})}async getActionExecution(r,e,t){let i=await this.extractContractOutput(r,e,t,[]),n=(0,g.getNextInfo)(this.config,[],r,e,i.output),a=(0,g.applyOutputToMessages)(r,i.output,this.config);return{status:t.effects?.status?.status==="success"?"success":"error",warp:r,action:e,user:(0,g.getWarpWalletAddressFromConfig)(this.config,this.chain.name),txHash:t.digest,tx:t,next:n,values:i.values,output:i.output,messages:a,destination:null,resolvedInputs:[]}}async extractContractOutput(r,e,t,i){let n=[],a=[],s={};if(!r.output)return{values:{string:n,native:a,mapped:{}},output:s};for(let[c,d]of Object.entries(r.output)){if(d.startsWith(g.WarpConstants.Transform.Prefix))continue;if(d.startsWith("input.")){s[c]=d;continue}let m=(0,g.parseOutputOutIndex)(d);if(m!==null&&m!==e){s[c]=null;continue}if(d.startsWith("out.")){let W=t.returnValues?t.returnValues[c]:null;s[c]=W,n.push(String(W)),a.push(W)}else s[c]=d}return{values:{string:n,native:a,mapped:{}},output:await(0,g.evaluateOutputCommon)(r,s,a,e,i,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(r,e,t,i){let n=e.map(d=>String(d)),a=e,s={string:n,native:a,mapped:{}},c={};if(!r.output)return{values:s,output:c};for(let[d,m]of Object.entries(r.output)){if(m.startsWith(g.WarpConstants.Transform.Prefix))continue;let W=(0,g.parseOutputOutIndex)(m);if(W!==null&&W!==t){c[d]=null;continue}if(m.startsWith("out.")||m==="out")if(Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null){let vr=m.replace(/^out\./,"");c[d]=e[0][vr]}else c[d]=e[0];else c[d]=m}return{values:s,output:await(0,g.evaluateOutputCommon)(r,c,a,t,i,this.serializer.coreSerializer,this.config)}}};var F=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new w,this.output=new E(this.config,this.chain);let t=(0,f.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new fr.SuiClient({url:t.url}),this.userWallet=(0,f.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async createTransaction(r){let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(e.type==="transfer")return this.createTransferTransaction(r);if(e.type==="contract")return this.createContractCallTransaction(r);throw e.type==="query"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeQuery instead"):e.type==="collect"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeCollect instead"):new Error(`WarpSuiExecutor: Invalid action type (${e.type})`)}async createTransferTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createTransfer - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid destination address");if(r.value<0)throw new Error(`WarpSuiExecutor: Transfer value cannot be negative: ${r.value}`);let e=new J.Transaction,t=[];if(r.value>0){let i=await this.handleCoinTransfer(e,"0x2::sui::SUI",r.value);t.push(i)}for(let i of r.transfers){let n=await this.handleCoinTransfer(e,i.identifier,i.amount);t.push(n)}return t.length>0&&e.transferObjects(t,e.pure.address(r.destination)),e}async createContractCallTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createContractCall - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid contract address");if(r.value<0)throw new Error(`WarpSuiExecutor: Contract call value cannot be negative: ${r.value}`);let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(!e.func)throw new Error("WarpSuiExecutor: createContractCall - function not set");let t=new J.Transaction;t.setSender(this.userWallet);let i=[];r.value>0&&i.push(await this.handleCoinTransfer(t,"0x2::sui::SUI",r.value));for(let c of r.transfers)i.push(await this.handleCoinTransfer(t,c.identifier,c.amount));let{target:n,typeArguments:a}=this.parseMoveCallTarget(e),s=r.args.map(c=>this.serializer.stringToTyped(c,t));return n==="0x2::transfer::public_transfer"?i.push(...await this.buildPublicTransferArgs(t,r,s)):i.push(...s),t.moveCall({target:n,arguments:i,typeArguments:a}),t.setGasBudget(1e8),t}async executeQuery(r){if(!r.destination)throw new Error("WarpSuiExecutor: executeQuery - destination not set");let e=(0,f.getWarpActionByIndex)(r.warp,r.action);if(e.type!=="query")throw new Error(`WarpSuiExecutor: Invalid action type for executeQuery: ${e.type}`);let t=await this.client.getObject({id:r.destination,options:{showContent:!0}}),i=[t],{values:n,output:a}=await this.output.extractQueryOutput(r.warp,i,r.action,r.resolvedInputs),s=(0,f.getNextInfo)(this.config,[],r.warp,r.action,a),d=r.resolvedInputs.find(W=>W.input.position==="receiver"||W.input.position==="destination")?.value||r.destination,m=(0,f.extractResolvedInputValues)(r.resolvedInputs);return{status:"success",warp:r.warp,action:r.action,user:this.userWallet,txHash:null,tx:null,next:s,values:n,output:{...a,_DATA:t},resolvedInputs:m,messages:(0,f.applyOutputToMessages)(r.warp,a,this.config),destination:d}}async signMessage(r,e){throw new Error("Not implemented")}parseMoveCallTarget(r){if(!r.func)throw new Error("WarpSuiExecutor: Function not set");let e=`${r.address}::${r.func}`,t=r.typeArguments;if(!t&&r.func.includes("<")&&r.func.includes(">")){let i=r.func.match(/<([^>]+)>/);i&&(t=[i[1]],e=`${r.address}::${r.func.replace(/<[^>]+>/,"")}`)}return{target:e,typeArguments:t}}async buildPublicTransferArgs(r,e,t){let i=e.resolvedInputs.find(s=>String(s.input.position)==="arg:0")?.value||e.args[0],n=e.resolvedInputs.find(s=>String(s.input.position)==="arg:1")?.value||e.resolvedInputs.find(s=>s.input.type==="address"&&String(s.input.position)!=="arg:0")?.value||e.args[1],a=this.extractObjectId(i);if(!a)return t;try{if(!(await this.client.getObject({id:a,options:{showType:!0,showContent:!0}})).data?.type?.startsWith("0x2::coin::Coin<"))return t;let c=n?this.serializer.stringToTyped(n.includes(":")?n:`address:${n}`,r):t[1]||r.pure.address(this.userWallet);return[r.object(a),c]}catch{return t}}extractObjectId(r){if(!r||typeof r!="string")return null;let e=r.startsWith("object:")?r.substring(7):r;return e.startsWith("0x")?e:null}async handleCoinTransfer(r,e,t){if(e==="0x2::sui::SUI")try{return r.splitCoins(r.gas,[t.toString()])[0]}catch{}return this.createCoinTransferFromObjects(r,e,t)}async createCoinTransferFromObjects(r,e,t){let i=await this.getCoinObjectsForTransfer(e,t);if(i.length===0)throw new Error(`No coin objects found for ${e}`);let n=r.object(i[0].coinObjectId);return i.length>1&&r.mergeCoins(n,i.slice(1).map(a=>r.object(a.coinObjectId))),r.splitCoins(n,[t.toString()])[0]}async getCoinObjectsForTransfer(r,e){if(!this.userWallet)throw new Error("User wallet not set");let{data:t}=await this.client.getCoins({owner:this.userWallet,coinType:r}),i=t.map(s=>({coinObjectId:s.coinObjectId,balance:s.balance})).sort((s,c)=>BigInt(c.balance)>BigInt(s.balance)?1:-1),n=BigInt(0),a=[];for(let s of i)if(a.push(s),n+=BigInt(s.balance),n>=e)return a;throw new Error(`Insufficient ${r} balance. Required: ${e}, Available: ${n}`)}};var j=class{constructor(r,e){this.config=r;this.chain=e}getExplorers(){let r=G[this.chain.name];if(!r)return["suivision"];let e=r[this.config.env];return e||["suivision"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(r){let e=this.config.preferences?.explorers?.[this.chain.name];if(e&&!r){let n=C[e];if(n)return n}if(r){let n=C[r];if(n)return n}let t=this.getPrimaryExplorer();return C[t]||C[t]}getAccountUrl(r,e){return`${this.getExplorerUrlByName(e)}/account/${r}`}getTransactionUrl(r,e){return`${this.getExplorerUrlByName(e)}/txblock/${r}`}getBlockUrl(r,e){return`${this.getExplorerUrlByName(e)}/block/${r}`}getAssetUrl(r,e){return`${this.getExplorerUrlByName(e)}/coin/${r}`}getContractUrl(r,e){return`${this.getExplorerUrlByName(e)}/object/${r}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(r){return this.getExplorers().find(t=>t.toLowerCase()===r.toLowerCase())}getAccountUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(i=>{let n=C[i];n&&(t[i]=`${n}/account/${r}`)}),t}getTransactionUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(i=>{let n=C[i];n&&(t[i]=`${n}/txblock/${r}`)}),t}};var hr=require("@mysten/sui/client"),y=require("@mysten/sui/transactions"),l=require("@joai/warps");var z=class{constructor(r,e){this.config=r;this.chain=e;this.registryConfig={unitPrice:BigInt(0),admins:[]};let t=(0,l.getProviderConfig)(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new hr.SuiClient({url:t.url}),this.cache=new l.WarpCache(r.env,r.cache),this.userWallet=(0,l.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async loadRegistryConfigs(){try{let r=`${K(this.config.env)}::registry::get_config`;console.log("-- Loading registry configs",r);let e=new y.Transaction;e.moveCall({target:r,arguments:[]});let t=await this.client.devInspectTransactionBlock({transactionBlock:e,sender:"0x0000000000000000000000000000000000000000000000000000000000000000"});console.log("-- Registry configs loaded",t);let i=t.results?.[0]?.returnValues?.[0],n=i&&Array.isArray(i)&&i[0]?JSON.parse(String.fromCharCode(...i[0])):{};this.registryConfig={unitPrice:n.unit_price!==void 0?BigInt(n.unit_price):BigInt(0),admins:Array.isArray(n.admins)?n.admins:[]}}catch(r){l.WarpLogger.error("WarpSuiRegistry: Failed to load registry config",r),this.registryConfig={unitPrice:BigInt(0),admins:[]}}}async createWarpRegisterTransaction(r,e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let i=new y.Transaction;return i.moveCall({target:u(this.config.env,"register_warp"),arguments:[i.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e?i.pure.option("string",e):i.pure.option("string",void 0),t?i.pure.option("vector<u8>",Array.from(Buffer.from(t,"hex"))):i.pure.option("vector<u8>",void 0),i.gas,i.pure.address(this.userWallet)]}),i}async createWarpUnregisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new y.Transaction;return e.moveCall({target:u(this.config.env,"unregister_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpUpgradeTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new y.Transaction;return t.moveCall({target:u(this.config.env,"upgrade_warp"),arguments:[t.pure.string(r),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpAliasSetTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new y.Transaction;return t.moveCall({target:u(this.config.env,"set_warp_alias"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.string(e),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpVerifyTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new y.Transaction;return e.moveCall({target:u(this.config.env,"verify_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpTransferOwnershipTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new y.Transaction;return t.moveCall({target:u(this.config.env,"transfer_ownership"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.address(e),t.gas,t.pure.address(this.userWallet)]}),t}async createBrandRegisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new y.Transaction;return e.moveCall({target:u(this.config.env,"register_brand"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpBrandingTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new y.Transaction;return t.moveCall({target:u(this.config.env,"brand_warp"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async getInfoByAlias(r,e){let t=l.WarpCacheKey.RegistryInfo(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return l.WarpLogger.info(`WarpSuiRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),i;try{let n=await this.client.call(u(this.config.env,"get_info_by_alias"),[r]),a=n||null,s=a?N(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&await this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(n){return l.WarpLogger.error("WarpSuiRegistry (getInfoByAlias):",n),{registryInfo:null,brand:null}}}async getInfoByHash(r,e){let t=l.WarpCacheKey.RegistryInfo(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return l.WarpLogger.info(`WarpSuiRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),i;try{let n=await this.client.call(u(this.config.env,"get_info_by_hash"),[Array.from(Buffer.from(r,"hex"))]),a=n||null,s=a?N(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&await this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(n){return l.WarpLogger.error("WarpSuiRegistry (getInfoByHash):",n),{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(r){let e=`sui:registry:user:${r||this.userWallet}`,t=await this.cache.get(e);if(t)return l.WarpLogger.info(`WarpSuiRegistry (getUserWarpRegistryInfos): RegistryInfos found in cache for user: ${r||this.userWallet}`),t;try{let i=r||this.userWallet;if(!i)throw new Error("WarpRegistry: user address not set");let n=await this.client.call(u(this.config.env,"get_user_warps"),[i]),a=Array.isArray(n)?n.map(N):[];return r&&await this.cache.set(e,a,300),a}catch(i){return l.WarpLogger.error("WarpSuiRegistry (getUserWarpRegistryInfos):",i),[]}}async getUserBrands(r){let e=`sui:registry:user:brands:${r||this.userWallet}`,t=await this.cache.get(e);if(t)return l.WarpLogger.info(`WarpSuiRegistry (getUserBrands): Brands found in cache for user: ${r||this.userWallet}`),t;try{let i=r||this.userWallet;if(!i)throw new Error("WarpRegistry: user address not set");let n=await this.client.call(u(this.config.env,"get_user_brands"),[i]);if(!Array.isArray(n))return[];let s=(await Promise.all(n.map(c=>this.fetchBrand(c)))).filter(c=>c!==null);return r&&await this.cache.set(e,s,300),s}catch(i){return l.WarpLogger.error("WarpSuiRegistry (getUserBrands):",i),[]}}async fetchBrand(r,e){let t=l.WarpCacheKey.Brand(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return l.WarpLogger.info(`WarpSuiRegistry (fetchBrand): Brand found in cache: ${r}`),i;try{let n=await this.client.getTransactionBlock({digest:r});if(!n||!n.effects)return null;let a=null;if(n.events&&Array.isArray(n.events)){for(let s of n.events)if(s.type&&typeof s.type=="string"&&s.type.includes("BrandRegistered"))try{a=s.parsedJson;break}catch{}}if(!a&&n.objectChanges&&Array.isArray(n.objectChanges)){for(let s of n.objectChanges)if(s.type==="created"&&s.objectType&&s.objectType.includes("Brand"))try{break}catch{}}return a?(a.meta={hash:r,creator:n.transaction&&n.transaction.data&&n.transaction.data.sender?n.transaction.data.sender:void 0,createdAt:n.timestampMs?new Date(Number(n.timestampMs)).toISOString():void 0},e&&e.ttl&&await this.cache.set(t,a,e.ttl),a):null}catch(n){return l.WarpLogger.error("WarpSuiRegistry (fetchBrand):",n),null}}};var Wr=require("@joai/warps");var M=require("@mysten/sui/keypairs/ed25519"),mr=Er(require("@scure/bip39"),1),yr=require("@scure/bip39/wordlists/english.js"),p=require("@joai/warps"),I=class I{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return(0,p.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),i=await e.signPersonalMessage(t);return{...r,signature:i.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=(0,p.normalizeAndValidateMnemonic)(r),i=M.Ed25519Keypair.deriveKeypair(e).getPublicKey().toSuiAddress(),n={provider:I.PROVIDER_NAME,address:i,privateKey:null,mnemonic:e};return(0,p.setWarpWalletInConfig)(this.config,this.chain.name,n),n}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let n=M.Ed25519Keypair.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:I.PROVIDER_NAME,address:n,privateKey:r,mnemonic:null};return(0,p.setWarpWalletInConfig)(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=(0,p.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name),t=(0,p.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);return{provider:I.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:t||null,mnemonic:e||null}}async generate(){let r=mr.generateMnemonic(yr.wordlist,256),e=(0,p.normalizeMnemonic)(r);(0,p.validateMnemonicLength)(e);let i=M.Ed25519Keypair.deriveKeypair(e).getPublicKey().toSuiAddress();return{provider:I.PROVIDER_NAME,address:i,privateKey:null,mnemonic:e}}async delete(r){(0,p.removeWarpWalletFromConfig)(this.config,this.chain.name)}getKeypair(){if(this.keypair)return this.keypair;let r=(0,p.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);if(!r)throw new Error("No mnemonic provided");return this.keypair=M.Ed25519Keypair.deriveKeypair(r.trim()),this.keypair}};I.PROVIDER_NAME="mnemonic";var B=I;var S=require("@joai/warps"),T=class{constructor(r,e){this.config=r;this.chain=e}async getAddress(){return(0,S.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async signMessage(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromMnemonic(r){let e=(0,S.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromPrivateKey(r){let e=(0,S.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async export(){let r=(0,S.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async generate(){let r=(0,S.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async delete(r){(0,S.removeWarpWalletFromConfig)(this.config,this.chain.name)}};var U=require("@mysten/sui/keypairs/ed25519"),h=require("@joai/warps"),x=class x{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return(0,h.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),i=await e.signPersonalMessage(t);return{...r,signature:i.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=U.Ed25519Keypair.deriveKeypair(r.trim()),t=e.getPublicKey().toSuiAddress(),i=Buffer.from(e.getSecretKey()).toString("hex"),n={provider:x.PROVIDER_NAME,address:t,privateKey:i,mnemonic:r};return(0,h.setWarpWalletInConfig)(this.config,this.chain.name,n),n}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let n=U.Ed25519Keypair.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:x.PROVIDER_NAME,address:n,privateKey:r,mnemonic:null};return(0,h.setWarpWalletInConfig)(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=(0,h.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name),t=(0,h.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);return{provider:x.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:e||null,mnemonic:t||null}}async generate(){let r=U.Ed25519Keypair.generate(),e=r.getPublicKey().toSuiAddress(),t=Buffer.from(r.getSecretKey()).toString("hex");return{provider:x.PROVIDER_NAME,address:e,privateKey:t,mnemonic:null}}async delete(r){(0,h.removeWarpWalletFromConfig)(this.config,this.chain.name)}getKeypair(){if(this.keypair)return this.keypair;let r=(0,h.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);if(!r)throw new Error("Wallet not initialized - no private key provided");try{let e=Buffer.from(r,"hex");if(e.length===70){let t=new Uint8Array(e.subarray(1,33));return this.keypair=U.Ed25519Keypair.fromSecretKey(t),this.keypair}else{if(e.length===32)return this.keypair=U.Ed25519Keypair.fromSecretKey(new Uint8Array(e)),this.keypair;throw new Error(`Unsupported private key length: ${e.length} bytes`)}}catch(e){throw e}}};x.PROVIDER_NAME="privateKey";var R=x;var _=class{constructor(r,e){this.config=r;this.chain=e;this.cachedAddress=null;this.cachedPublicKey=null;this.client=Q(r,e),this.walletProvider=this.createProvider(),this.isInitializedPromise=new Promise(t=>{this.isInitializedResolve=t}),this.initializeCache()}async waitUntilInitialized(){await this.isInitializedPromise}async signTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof T)throw new Error(`Wallet (${this.chain.name}) is read-only`);return(this.walletProvider instanceof R||this.walletProvider instanceof B)&&r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function"?r:await this.walletProvider.signTransaction(r)}async signMessage(r){if(await this.waitUntilInitialized(),!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof T)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(r)}async signTransactions(r){return await this.waitUntilInitialized(),r}async sendTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(r.transactionHash)return r.transactionHash;if(r&&typeof r=="object"&&"bytes"in r&&"signature"in r)return(await this.client.executeTransactionBlock({transactionBlock:r.bytes,signature:Array.isArray(r.signature)?r.signature:[r.signature],options:{showEffects:!0,showEvents:!0}})).digest;if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof R||this.walletProvider instanceof B){let e=this.walletProvider.getKeypairInstance();if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return(await this.client.signAndExecuteTransaction({transaction:r,signer:e,options:{showEffects:!0,showEvents:!0}})).digest;throw new Error(`Transaction must be a Transaction object or have bytes and signature. Got: ${typeof r}, has sign: ${r&&typeof r=="object"&&"sign"in r}, has bytes: ${r&&typeof r=="object"&&"bytes"in r}, has signature: ${r&&typeof r=="object"&&"signature"in r}`)}throw new Error("Remote wallet provider must return signed payload (bytes + signature) or transactionHash for Sui transactions")}async sendTransactions(r){return await this.waitUntilInitialized(),Promise.all(r.map(async e=>this.sendTransaction(e)))}async importFromMnemonic(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("mnemonic").importFromMnemonic(r)}async importFromPrivateKey(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("privateKey").importFromPrivateKey(r)}async export(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).export()}async generate(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).generate()}async delete(r,e){await this.waitUntilInitialized(),await this.createProviderForOperation(r).delete(e)}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let r=this.config.user?.wallets?.[this.chain.name];return r?typeof r=="string"?new T(this.config,this.chain):r.provider?this.createProviderForOperation(r.provider):new T(this.config,this.chain):null}async initializeCache(){let r=await(0,Wr.initializeWalletCache)(this.walletProvider);this.cachedAddress=r.address,this.cachedPublicKey=r.publicKey,this.isInitializedResolve()}createProviderForOperation(r){let t=this.config.walletProviders?.[this.chain.name]?.[r];if(t){let i=t(this.config,this.chain);if(!i)throw new Error(`Custom wallet provider factory returned null for ${r}`);return i}if(r==="privateKey")return new R(this.config,this.chain);if(r==="mnemonic")return new B(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${r}`)}};var V={chain:k.WarpChainName.Sui,identifier:"0x2::sui::SUI",name:"SUI",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/standard/sui-ocean-square.png?1727791290"};function Ur(o,r){return(e,t)=>{let i=r[e.env];if(!i)throw new Error(`SuiAdapter: chain info not found for chain ${o}`);return{chainInfo:i,builder:()=>new $(e,i),executor:new F(e,i),output:new E(e,i),serializer:new w,registry:new z(e,i),explorer:new j(e,i),abiBuilder:()=>new P(e,i),brandBuilder:()=>new D(e,i),dataLoader:new O(e,i),wallet:new _(e,i)}}}var Rr=Ur(k.WarpChainName.Sui,{mainnet:{name:k.WarpChainName.Sui,displayName:"Sui",chainId:"1",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.mainnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V},testnet:{name:k.WarpChainName.Sui,displayName:"Sui Testnet",chainId:"testnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.testnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V},devnet:{name:k.WarpChainName.Sui,displayName:"Sui Devnet",chainId:"devnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.devnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:V}});var q=class{constructor(r,e){this.abi=new P(r,e)}async loadModuleAbi(r,e){return this.abi.getModuleAbi(r,e)}async loadFunctionAbi(r,e,t){return this.abi.getFunctionAbi(r,e,t)}};0&&(module.exports={ExplorerUrls,KnownTokens,NativeTokenSui,SuiAdapter,SuiExplorers,SuiExplorersConfig,WarpSuiAbiBuilder,WarpSuiBrandBuilder,WarpSuiBuilder,WarpSuiConstants,WarpSuiContractLoader,WarpSuiDataLoader,WarpSuiExecutor,WarpSuiExplorer,WarpSuiOutput,WarpSuiRegistry,WarpSuiSerializer,WarpSuiWallet,findKnownTokenById,getConfiguredSuiClient,getSuiRegistryObjectId,getSuiRegistryPackageId,toRegistryMoveTarget,toTypedRegistryInfo});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var T=o=>{if(o==="devnet")throw new Error("Sui registry package id is not available for devnet");if(o==="testnet")return"0xc8824c98b09d36eec6c8b69ae7083e0b012b5e516e2f7a54c75bfa8a80105753";throw new Error("Sui registry package id is not available for mainnet")},qr=o=>{if(o==="devnet")throw new Error("Sui registry object id is not available for devnet");if(o==="testnet")return"";throw new Error("Sui registry object id is not available for mainnet")};var Yr={Sui:{Identifier:"SUI",DisplayName:"Sui",Decimals:9}},er=(a=>(a.SuiVision="suivision",a.SuiVisionTestnet="suivision_testnet",a.SuiVisionDevnet="suivision_devnet",a.SuiScan="suiscan",a.SuiScanTestnet="suiscan_testnet",a.SuiScanDevnet="suiscan_devnet",a))(er||{}),z={sui:{mainnet:["suivision","suiscan"],testnet:["suivision_testnet","suiscan_testnet"],devnet:["suivision_devnet","suiscan_devnet"]}},y={suivision:"https://suivision.xyz",suivision_testnet:"https://testnet.suivision.xyz",suivision_devnet:"https://devnet.suivision.xyz",suiscan:"https://suiscan.xyz",suiscan_testnet:"https://testnet.suiscan.xyz",suiscan_devnet:"https://devnet.suiscan.xyz"};import{SuiClient as tr}from"@mysten/sui/client";import{getProviderConfig as nr}from"@joai/warps";var M=(o,r)=>{let e=nr(o,r.name,o.env,r.defaultApiUrl);return new tr({url:e.url})};var l=(o,r)=>`${T(o)}::${r}`,ir=o=>{let r=Buffer.from(o).toString();return r==="unverified"||r==="verified"||r==="blacklisted"?r:"unverified"},x=o=>({hash:Buffer.from(o.hash).toString("hex"),alias:o.alias?Buffer.from(o.alias).toString():null,trust:ir(o.trust),owner:o.owner,createdAt:Number(o.created_at),upgradedAt:Number(o.upgraded_at),brand:o.brand?Buffer.from(o.brand).toString("hex"):null,upgrade:o.upgrade?Buffer.from(o.upgrade).toString("hex"):null});import{WarpChainName as I}from"@joai/warps";import{SuiClient as ar}from"@mysten/sui/client";import{getProviderConfig as sr}from"@joai/warps";var C=class{constructor(r,e){this.config=r;this.chain=e;let t=sr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new ar({url:t.url})}async createInscriptionTransaction(r){throw new Error("WarpSuiAbiBuilder: createInscriptionTransaction not implemented")}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t):null}catch{return null}}async getModuleAbi(r,e){return this.client.getNormalizedMoveModule({package:r,module:e})}async getFunctionAbi(r,e,t){return this.client.getNormalizedMoveFunction({package:r,module:e,function:t})}};import{SuiClient as or}from"@mysten/sui/client";import{Transaction as cr}from"@mysten/sui/transactions";import{getProviderConfig as lr}from"@joai/warps";var B=class{constructor(r,e){this.config=r;this.chain=e;let t=lr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new or({url:t.url})}createInscriptionTransaction(r){return new cr}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r,e){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t,!1):null}catch{return null}}};import{SuiClient as pr}from"@mysten/sui/client";import{Transaction as ur}from"@mysten/sui/transactions";import{getProviderConfig as gr,getWarpWalletAddressFromConfig as dr,WarpBuilder as fr,WarpCache as hr}from"@joai/warps";var U=class extends fr{constructor(e,t){super(e);this.config=e;this.chain=t;this.cache=new hr(e.env,e.cache);let n=gr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new pr({url:n.url}),this.userWallet=dr(this.config,this.chain.name)}async createInscriptionTransaction(e,t){if(!t)throw new Error("WarpSuiBuilder: registryObjectId is required");if(!this.userWallet)throw new Error("WarpSuiBuilder: user address not set");if(!e.meta||!e.meta.hash)throw new Error("WarpSuiBuilder: warp.meta.hash is required");let n=Array.from(Buffer.from(e.meta.hash,"hex")),i=e.meta?.alias??void 0,a=e.meta?.brand?Array.from(Buffer.from(e.meta.brand,"hex")):void 0,s=new ur;return s.moveCall({target:l(this.config.env,"register_warp"),arguments:[s.object(t),s.pure.vector("u8",n),i?s.pure.option("string",i):s.pure.option("string",void 0),a?s.pure.option("vector<u8>",a):s.pure.option("vector<u8>",void 0),s.gas,s.pure.address(this.userWallet)]}),s}async createFromNetwork(e,t){let n=`sui:warp:${e}`;if(t){let i=this.cache.get(n);if(i)return i}try{let i=await this.client.call(`${l(this.config.env,"get_info_by_hash")}`,[e,Array.from(Buffer.from(e,"hex"))]);if(!i||!Object.prototype.hasOwnProperty.call(i,"hash")||!i.hash)return null;let a=this.createFromRaw(i);return t&&t.ttl&&a&&this.cache.set(n,a,t.ttl),a}catch{return null}}async createFromTransaction(e){return this.createFromRaw(e)}async createFromTransactionHash(e,t){return this.createFromNetwork(e,t)}};import{SuiClient as Wr}from"@mysten/sui/client";import{CacheTtl as vr,getProviderConfig as wr,WarpCache as Cr,WarpCacheKey as br}from"@joai/warps";import{WarpChainName as mr}from"@joai/warps";var f=mr.Sui,yr=[{chain:f,identifier:"0x2::sui::SUI",name:"Sui",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/small/sui-logo.png"},{chain:f,identifier:"0xa198f3be41cda8c07c3bf1c4e0bb88b8e9827b7c063f36b1e6c3d6da1c4e8753::usdc::USDC",name:"USD Coin",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"},{chain:f,identifier:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48ace0cdd97::usdt::USDT",name:"Tether USD",symbol:"USDT",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/325/small/Tether.png"},{chain:f,identifier:"0xaf8cd5edc19c4512f4259f0bee101a7c94d8a5c0e7c90c7a7c8c8c8c8c8c8c8c8::wbtc::WBTC",name:"Wrapped Bitcoin",symbol:"WBTC",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/7598/small/wrapped_bitcoin_wbtc.png"},{chain:f,identifier:"0xb8a6a9b7c7a6f4a3e2d1c0b9a8f7e6d5c4b3a2b1c0d9e8f7a6b5c4d3e2f1a0b::weth::WETH",name:"Wrapped Ether",symbol:"WETH",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/2518/small/weth.png"},{chain:f,identifier:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a15e0e9::ocean::OCEAN",name:"Ocean Protocol",symbol:"OCEAN",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/3687/small/ocean-protocol-logo.png"},{chain:f,identifier:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c35569693fd50fb8b7::deep::DEEP",name:"DeepBook",symbol:"DEEP",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/30169/small/deepbook.png"},{chain:f,identifier:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47ba3::hasui::HASUI",name:"Haedal Staked SUI",symbol:"HASUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/30027/small/haSUI.png"},{chain:f,identifier:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e935::usdc::USDC",name:"USD Coin (Wormhole)",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"}],_=o=>yr.find(r=>r.identifier===o)||null;var R=class{constructor(r,e){this.config=r;this.chain=e;let t=wr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Wr({url:t.url}),this.cache=new Cr(r.env,r.cache)}async getAccount(r){let e=await this.client.getBalance({owner:r,coinType:"0x2::sui::SUI"});return{chain:this.chain.name,address:r,balance:BigInt(e.totalBalance)}}async getAccountAssets(r){let e=await this.client.getAllBalances({owner:r});console.log("WarpSuiDataLoader.getAccountAssets",e);let t=e.find(a=>a.coinType==="0x2::sui::SUI"),n=e.filter(a=>a.coinType!=="0x2::sui::SUI"&&BigInt(a.totalBalance)>0n),i=[];if(t&&BigInt(t.totalBalance)>0n&&i.push({...this.chain.nativeToken,amount:BigInt(t.totalBalance)}),n.length>0){let a=await Promise.all(n.map(s=>this.getAsset(s.coinType)));i.push(...a.filter(s=>s!==null).map(s=>({...s,amount:BigInt(n.find(c=>c.coinType===s.identifier)?.totalBalance||0)})))}return i}async getAsset(r){let e=br.Asset(this.config.env,this.chain.name,r),t=this.cache.get(e);if(t)return t;let n=_(r);if(n)return{chain:this.chain.name,identifier:r,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};try{let i=await this.client.getCoinMetadata({coinType:r}),a={chain:this.chain.name,identifier:r,name:i?.name||r.split("::").pop()||r,symbol:i?.symbol||r.split("::").pop()||r,amount:0n,decimals:i?.decimals||9,logoUrl:i?.iconUrl||""};return this.cache.set(e,a,vr.OneHour),a}catch{return null}}async getAction(r,e=!1){return null}async getAccountActions(r,e){return[]}};import{SuiClient as Br}from"@mysten/sui/client";import{Transaction as Q}from"@mysten/sui/transactions";import{applyOutputToMessages as Ur,extractResolvedInputValues as Rr,getNextInfo as kr,getProviderConfig as Kr,getWarpActionByIndex as O,getWarpWalletAddressFromConfig as Nr}from"@joai/warps";import{SuiClient as Er}from"@mysten/sui/client";import{applyOutputToMessages as Pr,evaluateOutputCommon as H,getNextInfo as Ir,getProviderConfig as Tr,getWarpWalletAddressFromConfig as xr,parseOutputOutIndex as V,WarpConstants as G}from"@joai/warps";import{Transaction as Ar}from"@mysten/sui/transactions";import{WarpSerializer as Sr}from"@joai/warps";var m=class{constructor(){this.coreSerializer=new Sr}typedToString(r){if(r==null)return"option:null";if(typeof r=="string")return`string:${r}`;if(typeof r=="boolean")return`bool:${r}`;if(typeof r=="number")return`uint64:${r.toString()}`;if(typeof r=="bigint")return`uint64:${r.toString()}`;if(r&&typeof r=="object"&&r.address)return`address:${r.address}`;if(Array.isArray(r)){if(r.length===0)return"vector:u8:";let e=this.typeToString(typeof r[0]),t=r.map(n=>this.typedToString(n).split(":")[1]);return`vector:${e}:${t.join(",")}`}if(r&&typeof r=="object"&&r.type&&r.value&&r.type==="option")return r.value===null||r.value===void 0?"option:null":`option:${this.typedToString(r.value)}`;throw new Error(`WarpSuiSerializer (typedToString): Unsupported input type: ${typeof r}`)}typedToNative(r){let e=this.typedToString(r);return this.coreSerializer.stringToNative(e)}nativeToTyped(r,e){let t=this.coreSerializer.nativeToString(r,e);return this.stringToTyped(t)}stringToTyped(r,e){let t=e||new Ar,[n,i]=r.split(/:(.*)/,2);if(n==="object")return t.object(i);if(n==="string")return t.pure.string(i);if(n==="bool")return t.pure.bool(i==="true");if(n==="u8")return t.pure.u8(Number(i));if(n==="u16")return t.pure.u16(Number(i));if(n==="u32")return t.pure.u32(Number(i));if(n==="u64"||n==="uint64")return t.pure.u64(BigInt(i));if(n==="u128")return t.pure.u128(BigInt(i));if(n==="u256")return t.pure.u256(BigInt(i));if(n==="address")return t.pure.address(i);throw new Error(`WarpSuiSerializer (stringToTyped): Unsupported type: ${n}`)}typeToString(r){if(r==="string")return"string";if(r==="bool")return"bool";if(r==="u8")return"u8";if(r==="u16")return"u16";if(r==="u32")return"u32";if(r==="u64"||r==="bigint"||r==="number")return"u64";if(r==="u128")return"u128";if(r==="u256")return"u256";if(r==="address")return"address";if(r==="vector")return"vector";if(r==="option")return"option";throw new Error(`WarpSuiSerializer (typeToString): Unsupported input type: ${r}`)}nativeToType(r){throw new Error("Not implemented")}};var b=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new m;let t=Tr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Er({url:t.url})}async getActionExecution(r,e,t){let n=await this.extractContractOutput(r,e,t,[]),i=Ir(this.config,[],r,e,n.output),a=Pr(r,n.output,this.config);return{status:t.effects?.status?.status==="success"?"success":"error",warp:r,action:e,user:xr(this.config,this.chain.name),txHash:t.digest,tx:t,next:i,values:n.values,output:n.output,messages:a,destination:null,resolvedInputs:[]}}async extractContractOutput(r,e,t,n){let i=[],a=[],s={};if(!r.output)return{values:{string:i,native:a,mapped:{}},output:s};for(let[c,p]of Object.entries(r.output)){if(p.startsWith(G.Transform.Prefix))continue;if(p.startsWith("input.")){s[c]=p;continue}let u=V(p);if(u!==null&&u!==e){s[c]=null;continue}if(p.startsWith("out.")){let d=t.returnValues?t.returnValues[c]:null;s[c]=d,i.push(String(d)),a.push(d)}else s[c]=p}return{values:{string:i,native:a,mapped:{}},output:await H(r,s,a,e,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(r,e,t,n){let i=e.map(p=>String(p)),a=e,s={string:i,native:a,mapped:{}},c={};if(!r.output)return{values:s,output:c};for(let[p,u]of Object.entries(r.output)){if(u.startsWith(G.Transform.Prefix))continue;let d=V(u);if(d!==null&&d!==t){c[p]=null;continue}if(u.startsWith("out.")||u==="out")if(Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null){let rr=u.replace(/^out\./,"");c[p]=e[0][rr]}else c[p]=e[0];else c[p]=u}return{values:s,output:await H(r,c,a,t,n,this.serializer.coreSerializer,this.config)}}};var k=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new m,this.output=new b(this.config,this.chain);let t=Kr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Br({url:t.url}),this.userWallet=Nr(this.config,this.chain.name)}async createTransaction(r){let e=O(r.warp,r.action);if(e.type==="transfer")return this.createTransferTransaction(r);if(e.type==="contract")return this.createContractCallTransaction(r);throw e.type==="query"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeQuery instead"):e.type==="collect"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeCollect instead"):new Error(`WarpSuiExecutor: Invalid action type (${e.type})`)}async createTransferTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createTransfer - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid destination address");if(r.value<0)throw new Error(`WarpSuiExecutor: Transfer value cannot be negative: ${r.value}`);let e=new Q,t=[];if(r.value>0){let n=await this.handleCoinTransfer(e,"0x2::sui::SUI",r.value);t.push(n)}for(let n of r.transfers){let i=await this.handleCoinTransfer(e,n.identifier,n.amount);t.push(i)}return t.length>0&&e.transferObjects(t,e.pure.address(r.destination)),e}async createContractCallTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createContractCall - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid contract address");if(r.value<0)throw new Error(`WarpSuiExecutor: Contract call value cannot be negative: ${r.value}`);let e=O(r.warp,r.action);if(!e.func)throw new Error("WarpSuiExecutor: createContractCall - function not set");let t=new Q;t.setSender(this.userWallet);let n=[];r.value>0&&n.push(await this.handleCoinTransfer(t,"0x2::sui::SUI",r.value));for(let c of r.transfers)n.push(await this.handleCoinTransfer(t,c.identifier,c.amount));let{target:i,typeArguments:a}=this.parseMoveCallTarget(e),s=r.args.map(c=>this.serializer.stringToTyped(c,t));return i==="0x2::transfer::public_transfer"?n.push(...await this.buildPublicTransferArgs(t,r,s)):n.push(...s),t.moveCall({target:i,arguments:n,typeArguments:a}),t.setGasBudget(1e8),t}async executeQuery(r){if(!r.destination)throw new Error("WarpSuiExecutor: executeQuery - destination not set");let e=O(r.warp,r.action);if(e.type!=="query")throw new Error(`WarpSuiExecutor: Invalid action type for executeQuery: ${e.type}`);let t=await this.client.getObject({id:r.destination,options:{showContent:!0}}),n=[t],{values:i,output:a}=await this.output.extractQueryOutput(r.warp,n,r.action,r.resolvedInputs),s=kr(this.config,[],r.warp,r.action,a),p=r.resolvedInputs.find(d=>d.input.position==="receiver"||d.input.position==="destination")?.value||r.destination,u=Rr(r.resolvedInputs);return{status:"success",warp:r.warp,action:r.action,user:this.userWallet,txHash:null,tx:null,next:s,values:i,output:{...a,_DATA:t},resolvedInputs:u,messages:Ur(r.warp,a,this.config),destination:p}}async signMessage(r,e){throw new Error("Not implemented")}parseMoveCallTarget(r){if(!r.func)throw new Error("WarpSuiExecutor: Function not set");let e=`${r.address}::${r.func}`,t=r.typeArguments;if(!t&&r.func.includes("<")&&r.func.includes(">")){let n=r.func.match(/<([^>]+)>/);n&&(t=[n[1]],e=`${r.address}::${r.func.replace(/<[^>]+>/,"")}`)}return{target:e,typeArguments:t}}async buildPublicTransferArgs(r,e,t){let n=e.resolvedInputs.find(s=>String(s.input.position)==="arg:0")?.value||e.args[0],i=e.resolvedInputs.find(s=>String(s.input.position)==="arg:1")?.value||e.resolvedInputs.find(s=>s.input.type==="address"&&String(s.input.position)!=="arg:0")?.value||e.args[1],a=this.extractObjectId(n);if(!a)return t;try{if(!(await this.client.getObject({id:a,options:{showType:!0,showContent:!0}})).data?.type?.startsWith("0x2::coin::Coin<"))return t;let c=i?this.serializer.stringToTyped(i.includes(":")?i:`address:${i}`,r):t[1]||r.pure.address(this.userWallet);return[r.object(a),c]}catch{return t}}extractObjectId(r){if(!r||typeof r!="string")return null;let e=r.startsWith("object:")?r.substring(7):r;return e.startsWith("0x")?e:null}async handleCoinTransfer(r,e,t){if(e==="0x2::sui::SUI")try{return r.splitCoins(r.gas,[t.toString()])[0]}catch{}return this.createCoinTransferFromObjects(r,e,t)}async createCoinTransferFromObjects(r,e,t){let n=await this.getCoinObjectsForTransfer(e,t);if(n.length===0)throw new Error(`No coin objects found for ${e}`);let i=r.object(n[0].coinObjectId);return n.length>1&&r.mergeCoins(i,n.slice(1).map(a=>r.object(a.coinObjectId))),r.splitCoins(i,[t.toString()])[0]}async getCoinObjectsForTransfer(r,e){if(!this.userWallet)throw new Error("User wallet not set");let{data:t}=await this.client.getCoins({owner:this.userWallet,coinType:r}),n=t.map(s=>({coinObjectId:s.coinObjectId,balance:s.balance})).sort((s,c)=>BigInt(c.balance)>BigInt(s.balance)?1:-1),i=BigInt(0),a=[];for(let s of n)if(a.push(s),i+=BigInt(s.balance),i>=e)return a;throw new Error(`Insufficient ${r} balance. Required: ${e}, Available: ${i}`)}};var K=class{constructor(r,e){this.config=r;this.chain=e}getExplorers(){let r=z[this.chain.name];if(!r)return["suivision"];let e=r[this.config.env];return e||["suivision"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(r){let e=this.config.preferences?.explorers?.[this.chain.name];if(e&&!r){let i=y[e];if(i)return i}if(r){let i=y[r];if(i)return i}let t=this.getPrimaryExplorer();return y[t]||y[t]}getAccountUrl(r,e){return`${this.getExplorerUrlByName(e)}/account/${r}`}getTransactionUrl(r,e){return`${this.getExplorerUrlByName(e)}/txblock/${r}`}getBlockUrl(r,e){return`${this.getExplorerUrlByName(e)}/block/${r}`}getAssetUrl(r,e){return`${this.getExplorerUrlByName(e)}/coin/${r}`}getContractUrl(r,e){return`${this.getExplorerUrlByName(e)}/object/${r}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(r){return this.getExplorers().find(t=>t.toLowerCase()===r.toLowerCase())}getAccountUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(n=>{let i=y[n];i&&(t[n]=`${i}/account/${r}`)}),t}getTransactionUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(n=>{let i=y[n];i&&(t[n]=`${i}/txblock/${r}`)}),t}};import{SuiClient as Dr}from"@mysten/sui/client";import{Transaction as h}from"@mysten/sui/transactions";import{getProviderConfig as $r,getWarpWalletAddressFromConfig as Or,WarpCache as jr,WarpCacheKey as j,WarpLogger as g}from"@joai/warps";var N=class{constructor(r,e){this.config=r;this.chain=e;this.registryConfig={unitPrice:BigInt(0),admins:[]};let t=$r(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Dr({url:t.url}),this.cache=new jr(r.env,r.cache),this.userWallet=Or(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async loadRegistryConfigs(){try{let r=`${T(this.config.env)}::registry::get_config`;console.log("-- Loading registry configs",r);let e=new h;e.moveCall({target:r,arguments:[]});let t=await this.client.devInspectTransactionBlock({transactionBlock:e,sender:"0x0000000000000000000000000000000000000000000000000000000000000000"});console.log("-- Registry configs loaded",t);let n=t.results?.[0]?.returnValues?.[0],i=n&&Array.isArray(n)&&n[0]?JSON.parse(String.fromCharCode(...n[0])):{};this.registryConfig={unitPrice:i.unit_price!==void 0?BigInt(i.unit_price):BigInt(0),admins:Array.isArray(i.admins)?i.admins:[]}}catch(r){g.error("WarpSuiRegistry: Failed to load registry config",r),this.registryConfig={unitPrice:BigInt(0),admins:[]}}}async createWarpRegisterTransaction(r,e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=new h;return n.moveCall({target:l(this.config.env,"register_warp"),arguments:[n.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e?n.pure.option("string",e):n.pure.option("string",void 0),t?n.pure.option("vector<u8>",Array.from(Buffer.from(t,"hex"))):n.pure.option("vector<u8>",void 0),n.gas,n.pure.address(this.userWallet)]}),n}async createWarpUnregisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"unregister_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpUpgradeTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"upgrade_warp"),arguments:[t.pure.string(r),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpAliasSetTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"set_warp_alias"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.string(e),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpVerifyTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"verify_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpTransferOwnershipTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"transfer_ownership"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.address(e),t.gas,t.pure.address(this.userWallet)]}),t}async createBrandRegisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"register_brand"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpBrandingTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"brand_warp"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async getInfoByAlias(r,e){let t=j.RegistryInfo(this.config.env,r),n=e?this.cache.get(t):null;if(n)return g.info(`WarpSuiRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),n;try{let i=await this.client.call(l(this.config.env,"get_info_by_alias"),[r]),a=i||null,s=a?x(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(i){return g.error("WarpSuiRegistry (getInfoByAlias):",i),{registryInfo:null,brand:null}}}async getInfoByHash(r,e){let t=j.RegistryInfo(this.config.env,r),n=e?this.cache.get(t):null;if(n)return g.info(`WarpSuiRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),n;try{let i=await this.client.call(l(this.config.env,"get_info_by_hash"),[Array.from(Buffer.from(r,"hex"))]),a=i||null,s=a?x(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(i){return g.error("WarpSuiRegistry (getInfoByHash):",i),{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(r){let e=`sui:registry:user:${r||this.userWallet}`,t=this.cache.get(e);if(t)return g.info(`WarpSuiRegistry (getUserWarpRegistryInfos): RegistryInfos found in cache for user: ${r||this.userWallet}`),t;try{let n=r||this.userWallet;if(!n)throw new Error("WarpRegistry: user address not set");let i=await this.client.call(l(this.config.env,"get_user_warps"),[n]),a=Array.isArray(i)?i.map(x):[];return r&&this.cache.set(e,a,300),a}catch(n){return g.error("WarpSuiRegistry (getUserWarpRegistryInfos):",n),[]}}async getUserBrands(r){let e=`sui:registry:user:brands:${r||this.userWallet}`,t=this.cache.get(e);if(t)return g.info(`WarpSuiRegistry (getUserBrands): Brands found in cache for user: ${r||this.userWallet}`),t;try{let n=r||this.userWallet;if(!n)throw new Error("WarpRegistry: user address not set");let i=await this.client.call(l(this.config.env,"get_user_brands"),[n]);if(!Array.isArray(i))return[];let s=(await Promise.all(i.map(c=>this.fetchBrand(c)))).filter(c=>c!==null);return r&&this.cache.set(e,s,300),s}catch(n){return g.error("WarpSuiRegistry (getUserBrands):",n),[]}}async fetchBrand(r,e){let t=j.Brand(this.config.env,r),n=e?this.cache.get(t):null;if(n)return g.info(`WarpSuiRegistry (fetchBrand): Brand found in cache: ${r}`),n;try{let i=await this.client.getTransactionBlock({digest:r});if(!i||!i.effects)return null;let a=null;if(i.events&&Array.isArray(i.events)){for(let s of i.events)if(s.type&&typeof s.type=="string"&&s.type.includes("BrandRegistered"))try{a=s.parsedJson;break}catch{}}if(!a&&i.objectChanges&&Array.isArray(i.objectChanges)){for(let s of i.objectChanges)if(s.type==="created"&&s.objectType&&s.objectType.includes("Brand"))try{break}catch{}}return a?(a.meta={hash:r,creator:i.transaction&&i.transaction.data&&i.transaction.data.sender?i.transaction.data.sender:void 0,createdAt:i.timestampMs?new Date(Number(i.timestampMs)).toISOString():void 0},e&&e.ttl&&this.cache.set(t,a,e.ttl),a):null}catch(i){return g.error("WarpSuiRegistry (fetchBrand):",i),null}}};import{initializeWalletCache as Lr}from"@joai/warps";import{Ed25519Keypair as D}from"@mysten/sui/keypairs/ed25519";import*as q from"@scure/bip39";import{wordlist as Fr}from"@scure/bip39/wordlists/english.js";import{getWarpWalletAddressFromConfig as zr,getWarpWalletMnemonicFromConfig as L,getWarpWalletPrivateKeyFromConfig as Mr,normalizeAndValidateMnemonic as _r,normalizeMnemonic as Hr,setWarpWalletInConfig as J,validateMnemonicLength as Vr}from"@joai/warps";var W=class W{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return zr(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),n=await e.signPersonalMessage(t);return{...r,signature:n.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=_r(r),n=D.deriveKeypair(e).getPublicKey().toSuiAddress(),i={provider:W.PROVIDER_NAME,address:n,privateKey:null,mnemonic:e};return J(this.config,this.chain.name,i),i}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let i=D.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:W.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return J(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=L(this.config,this.chain.name),t=Mr(this.config,this.chain.name);return{provider:W.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:t||null,mnemonic:e||null}}async generate(){let r=q.generateMnemonic(Fr,256),e=Hr(r);Vr(e);let n=D.deriveKeypair(e).getPublicKey().toSuiAddress();return{provider:W.PROVIDER_NAME,address:n,privateKey:null,mnemonic:e}}getKeypair(){if(this.keypair)return this.keypair;let r=L(this.config,this.chain.name);if(!r)throw new Error("No mnemonic provided");return this.keypair=D.deriveKeypair(r.trim()),this.keypair}};W.PROVIDER_NAME="mnemonic";var A=W;import{getWarpWalletAddressFromConfig as E}from"@joai/warps";var v=class{constructor(r,e){this.config=r;this.chain=e}async getAddress(){return E(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async signMessage(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromMnemonic(r){let e=E(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromPrivateKey(r){let e=E(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async export(){let r=E(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async generate(){let r=E(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}};import{Ed25519Keypair as P}from"@mysten/sui/keypairs/ed25519";import{getWarpWalletAddressFromConfig as Gr,getWarpWalletMnemonicFromConfig as Qr,getWarpWalletPrivateKeyFromConfig as X,setWarpWalletInConfig as Y}from"@joai/warps";var w=class w{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return Gr(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),n=await e.signPersonalMessage(t);return{...r,signature:n.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=P.deriveKeypair(r.trim()),t=e.getPublicKey().toSuiAddress(),n=Buffer.from(e.getSecretKey()).toString("hex"),i={provider:w.PROVIDER_NAME,address:t,privateKey:n,mnemonic:r};return Y(this.config,this.chain.name,i),i}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let i=P.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:w.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return Y(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=X(this.config,this.chain.name),t=Qr(this.config,this.chain.name);return{provider:w.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:e||null,mnemonic:t||null}}async generate(){let r=P.generate(),e=r.getPublicKey().toSuiAddress(),t=Buffer.from(r.getSecretKey()).toString("hex");return{provider:w.PROVIDER_NAME,address:e,privateKey:t,mnemonic:null}}getKeypair(){if(this.keypair)return this.keypair;let r=X(this.config,this.chain.name);if(!r)throw new Error("Wallet not initialized - no private key provided");try{let e=Buffer.from(r,"hex");if(e.length===70){let t=new Uint8Array(e.subarray(1,33));return this.keypair=P.fromSecretKey(t),this.keypair}else{if(e.length===32)return this.keypair=P.fromSecretKey(new Uint8Array(e)),this.keypair;throw new Error(`Unsupported private key length: ${e.length} bytes`)}}catch(e){throw e}}};w.PROVIDER_NAME="privateKey";var S=w;var $=class{constructor(r,e){this.config=r;this.chain=e;this.cachedAddress=null;this.cachedPublicKey=null;this.client=M(r,e),this.walletProvider=this.createProvider(),this.isInitializedPromise=new Promise(t=>{this.isInitializedResolve=t}),this.initializeCache()}async waitUntilInitialized(){await this.isInitializedPromise}async signTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof v)throw new Error(`Wallet (${this.chain.name}) is read-only`);return(this.walletProvider instanceof S||this.walletProvider instanceof A)&&r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function"?r:await this.walletProvider.signTransaction(r)}async signMessage(r){if(await this.waitUntilInitialized(),!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof v)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(r)}async signTransactions(r){return await this.waitUntilInitialized(),r}async sendTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(r.transactionHash)return r.transactionHash;if(r&&typeof r=="object"&&"bytes"in r&&"signature"in r)return(await this.client.executeTransactionBlock({transactionBlock:r.bytes,signature:Array.isArray(r.signature)?r.signature:[r.signature],options:{showEffects:!0,showEvents:!0}})).digest;if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof S||this.walletProvider instanceof A){let e=this.walletProvider.getKeypairInstance();if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return(await this.client.signAndExecuteTransaction({transaction:r,signer:e,options:{showEffects:!0,showEvents:!0}})).digest;throw new Error(`Transaction must be a Transaction object or have bytes and signature. Got: ${typeof r}, has sign: ${r&&typeof r=="object"&&"sign"in r}, has bytes: ${r&&typeof r=="object"&&"bytes"in r}, has signature: ${r&&typeof r=="object"&&"signature"in r}`)}throw new Error("Remote wallet provider must return signed payload (bytes + signature) or transactionHash for Sui transactions")}async sendTransactions(r){return await this.waitUntilInitialized(),Promise.all(r.map(async e=>this.sendTransaction(e)))}async importFromMnemonic(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("mnemonic").importFromMnemonic(r)}async importFromPrivateKey(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("privateKey").importFromPrivateKey(r)}async export(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).export()}async generate(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let r=this.config.user?.wallets?.[this.chain.name];return r?typeof r=="string"?new v(this.config,this.chain):r.provider?this.createProviderForOperation(r.provider):new v(this.config,this.chain):null}async initializeCache(){let r=await Lr(this.walletProvider);this.cachedAddress=r.address,this.cachedPublicKey=r.publicKey,this.isInitializedResolve()}createProviderForOperation(r){let t=this.config.walletProviders?.[this.chain.name]?.[r];if(t){let n=t(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${r}`);return n}if(r==="privateKey")return new S(this.config,this.chain);if(r==="mnemonic")return new A(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${r}`)}};var F={chain:I.Sui,identifier:"0x2::sui::SUI",name:"SUI",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/standard/sui-ocean-square.png?1727791290"};function Jr(o,r){return(e,t)=>{let n=r[e.env];if(!n)throw new Error(`SuiAdapter: chain info not found for chain ${o}`);return{chainInfo:n,builder:()=>new U(e,n),executor:new k(e,n),output:new b(e,n),serializer:new m,registry:new N(e,n),explorer:new K(e,n),abiBuilder:()=>new C(e,n),brandBuilder:()=>new B(e,n),dataLoader:new R(e,n),wallet:new $(e,n)}}}var Vn=Jr(I.Sui,{mainnet:{name:I.Sui,displayName:"Sui",chainId:"1",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.mainnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:F},testnet:{name:I.Sui,displayName:"Sui Testnet",chainId:"testnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.testnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:F},devnet:{name:I.Sui,displayName:"Sui Devnet",chainId:"devnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.devnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:F}});var Z=class{constructor(r,e){this.abi=new C(r,e)}async loadModuleAbi(r,e){return this.abi.getModuleAbi(r,e)}async loadFunctionAbi(r,e,t){return this.abi.getFunctionAbi(r,e,t)}};export{y as ExplorerUrls,yr as KnownTokens,F as NativeTokenSui,Vn as SuiAdapter,er as SuiExplorers,z as SuiExplorersConfig,C as WarpSuiAbiBuilder,B as WarpSuiBrandBuilder,U as WarpSuiBuilder,Yr as WarpSuiConstants,Z as WarpSuiContractLoader,R as WarpSuiDataLoader,k as WarpSuiExecutor,K as WarpSuiExplorer,b as WarpSuiOutput,N as WarpSuiRegistry,m as WarpSuiSerializer,$ as WarpSuiWallet,_ as findKnownTokenById,M as getConfiguredSuiClient,qr as getSuiRegistryObjectId,T as getSuiRegistryPackageId,l as toRegistryMoveTarget,x as toTypedRegistryInfo};
1
+ var T=o=>{if(o==="devnet")throw new Error("Sui registry package id is not available for devnet");if(o==="testnet")return"0xc8824c98b09d36eec6c8b69ae7083e0b012b5e516e2f7a54c75bfa8a80105753";throw new Error("Sui registry package id is not available for mainnet")},Zr=o=>{if(o==="devnet")throw new Error("Sui registry object id is not available for devnet");if(o==="testnet")return"";throw new Error("Sui registry object id is not available for mainnet")};var ee={Sui:{Identifier:"SUI",DisplayName:"Sui",Decimals:9}},er=(a=>(a.SuiVision="suivision",a.SuiVisionTestnet="suivision_testnet",a.SuiVisionDevnet="suivision_devnet",a.SuiScan="suiscan",a.SuiScanTestnet="suiscan_testnet",a.SuiScanDevnet="suiscan_devnet",a))(er||{}),z={sui:{mainnet:["suivision","suiscan"],testnet:["suivision_testnet","suiscan_testnet"],devnet:["suivision_devnet","suiscan_devnet"]}},y={suivision:"https://suivision.xyz",suivision_testnet:"https://testnet.suivision.xyz",suivision_devnet:"https://devnet.suivision.xyz",suiscan:"https://suiscan.xyz",suiscan_testnet:"https://testnet.suiscan.xyz",suiscan_devnet:"https://devnet.suiscan.xyz"};import{SuiClient as tr}from"@mysten/sui/client";import{getProviderConfig as ir}from"@joai/warps";var M=(o,r)=>{let e=ir(o,r.name,o.env,r.defaultApiUrl);return new tr({url:e.url})};var l=(o,r)=>`${T(o)}::${r}`,nr=o=>{let r=Buffer.from(o).toString();return r==="unverified"||r==="verified"||r==="blacklisted"?r:"unverified"},x=o=>({hash:Buffer.from(o.hash).toString("hex"),alias:o.alias?Buffer.from(o.alias).toString():null,trust:nr(o.trust),owner:o.owner,createdAt:Number(o.created_at),upgradedAt:Number(o.upgraded_at),brand:o.brand?Buffer.from(o.brand).toString("hex"):null,upgrade:o.upgrade?Buffer.from(o.upgrade).toString("hex"):null});import{WarpChainName as I}from"@joai/warps";import{SuiClient as ar}from"@mysten/sui/client";import{getProviderConfig as sr}from"@joai/warps";var C=class{constructor(r,e){this.config=r;this.chain=e;let t=sr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new ar({url:t.url})}async createInscriptionTransaction(r){throw new Error("WarpSuiAbiBuilder: createInscriptionTransaction not implemented")}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t):null}catch{return null}}async getModuleAbi(r,e){return this.client.getNormalizedMoveModule({package:r,module:e})}async getFunctionAbi(r,e,t){return this.client.getNormalizedMoveFunction({package:r,module:e,function:t})}};import{SuiClient as or}from"@mysten/sui/client";import{Transaction as cr}from"@mysten/sui/transactions";import{getProviderConfig as lr}from"@joai/warps";var B=class{constructor(r,e){this.config=r;this.chain=e;let t=lr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new or({url:t.url})}createInscriptionTransaction(r){return new cr}async createFromRaw(r){return JSON.parse(r)}async createFromTransaction(r,e){return this.createFromRaw(r.data||"{}")}async createFromTransactionHash(r,e){try{let t=await this.client.getTransactionBlock({digest:r});return t?this.createFromTransaction(t,!1):null}catch{return null}}};import{SuiClient as pr}from"@mysten/sui/client";import{Transaction as ur}from"@mysten/sui/transactions";import{getProviderConfig as gr,getWarpWalletAddressFromConfig as dr,WarpBuilder as fr,WarpCache as hr}from"@joai/warps";var U=class extends fr{constructor(e,t){super(e);this.config=e;this.chain=t;this.cache=new hr(e.env,e.cache);let i=gr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new pr({url:i.url}),this.userWallet=dr(this.config,this.chain.name)}async createInscriptionTransaction(e,t){if(!t)throw new Error("WarpSuiBuilder: registryObjectId is required");if(!this.userWallet)throw new Error("WarpSuiBuilder: user address not set");if(!e.meta||!e.meta.hash)throw new Error("WarpSuiBuilder: warp.meta.hash is required");let i=Array.from(Buffer.from(e.meta.hash,"hex")),n=e.meta?.alias??void 0,a=e.meta?.brand?Array.from(Buffer.from(e.meta.brand,"hex")):void 0,s=new ur;return s.moveCall({target:l(this.config.env,"register_warp"),arguments:[s.object(t),s.pure.vector("u8",i),n?s.pure.option("string",n):s.pure.option("string",void 0),a?s.pure.option("vector<u8>",a):s.pure.option("vector<u8>",void 0),s.gas,s.pure.address(this.userWallet)]}),s}async createFromNetwork(e,t){let i=`sui:warp:${e}`;if(t){let n=await this.cache.get(i);if(n)return n}try{let n=await this.client.call(`${l(this.config.env,"get_info_by_hash")}`,[e,Array.from(Buffer.from(e,"hex"))]);if(!n||!Object.prototype.hasOwnProperty.call(n,"hash")||!n.hash)return null;let a=this.createFromRaw(n);return t&&t.ttl&&a&&await this.cache.set(i,a,t.ttl),a}catch{return null}}async createFromTransaction(e){return this.createFromRaw(e)}async createFromTransactionHash(e,t){return this.createFromNetwork(e,t)}};import{SuiClient as Wr}from"@mysten/sui/client";import{CacheTtl as vr,getProviderConfig as wr,WarpCache as Cr,WarpCacheKey as br}from"@joai/warps";import{WarpChainName as mr}from"@joai/warps";var f=mr.Sui,yr=[{chain:f,identifier:"0x2::sui::SUI",name:"Sui",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/small/sui-logo.png"},{chain:f,identifier:"0xa198f3be41cda8c07c3bf1c4e0bb88b8e9827b7c063f36b1e6c3d6da1c4e8753::usdc::USDC",name:"USD Coin",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"},{chain:f,identifier:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48ace0cdd97::usdt::USDT",name:"Tether USD",symbol:"USDT",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/325/small/Tether.png"},{chain:f,identifier:"0xaf8cd5edc19c4512f4259f0bee101a7c94d8a5c0e7c90c7a7c8c8c8c8c8c8c8c8::wbtc::WBTC",name:"Wrapped Bitcoin",symbol:"WBTC",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/7598/small/wrapped_bitcoin_wbtc.png"},{chain:f,identifier:"0xb8a6a9b7c7a6f4a3e2d1c0b9a8f7e6d5c4b3a2b1c0d9e8f7a6b5c4d3e2f1a0b::weth::WETH",name:"Wrapped Ether",symbol:"WETH",decimals:8,logoUrl:"https://assets.coingecko.com/coins/images/2518/small/weth.png"},{chain:f,identifier:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a15e0e9::ocean::OCEAN",name:"Ocean Protocol",symbol:"OCEAN",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/3687/small/ocean-protocol-logo.png"},{chain:f,identifier:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c35569693fd50fb8b7::deep::DEEP",name:"DeepBook",symbol:"DEEP",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/30169/small/deepbook.png"},{chain:f,identifier:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47ba3::hasui::HASUI",name:"Haedal Staked SUI",symbol:"HASUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/30027/small/haSUI.png"},{chain:f,identifier:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e935::usdc::USDC",name:"USD Coin (Wormhole)",symbol:"USDC",decimals:6,logoUrl:"https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png"}],_=o=>yr.find(r=>r.identifier===o)||null;var R=class{constructor(r,e){this.config=r;this.chain=e;let t=wr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Wr({url:t.url}),this.cache=new Cr(r.env,r.cache)}async getAccount(r){let e=await this.client.getBalance({owner:r,coinType:"0x2::sui::SUI"});return{chain:this.chain.name,address:r,balance:BigInt(e.totalBalance)}}async getAccountAssets(r){let e=await this.client.getAllBalances({owner:r});console.log("WarpSuiDataLoader.getAccountAssets",e);let t=e.find(a=>a.coinType==="0x2::sui::SUI"),i=e.filter(a=>a.coinType!=="0x2::sui::SUI"&&BigInt(a.totalBalance)>0n),n=[];if(t&&BigInt(t.totalBalance)>0n&&n.push({...this.chain.nativeToken,amount:BigInt(t.totalBalance)}),i.length>0){let a=await Promise.all(i.map(s=>this.getAsset(s.coinType)));n.push(...a.filter(s=>s!==null).map(s=>({...s,amount:BigInt(i.find(c=>c.coinType===s.identifier)?.totalBalance||0)})))}return n}async getAsset(r){let e=br.Asset(this.config.env,this.chain.name,r),t=await this.cache.get(e);if(t)return t;let i=_(r);if(i)return{chain:this.chain.name,identifier:r,name:i.name,symbol:i.symbol,amount:0n,decimals:i.decimals,logoUrl:i.logoUrl};try{let n=await this.client.getCoinMetadata({coinType:r}),a={chain:this.chain.name,identifier:r,name:n?.name||r.split("::").pop()||r,symbol:n?.symbol||r.split("::").pop()||r,amount:0n,decimals:n?.decimals||9,logoUrl:n?.iconUrl||""};return await this.cache.set(e,a,vr.OneHour),a}catch{return null}}async getAction(r,e=!1){return null}async getAccountActions(r,e){return[]}};import{SuiClient as Br}from"@mysten/sui/client";import{Transaction as Q}from"@mysten/sui/transactions";import{applyOutputToMessages as Ur,extractResolvedInputValues as Rr,getNextInfo as kr,getProviderConfig as Kr,getWarpActionByIndex as O,getWarpWalletAddressFromConfig as Nr}from"@joai/warps";import{SuiClient as Pr}from"@mysten/sui/client";import{applyOutputToMessages as Er,evaluateOutputCommon as H,getNextInfo as Ir,getProviderConfig as Tr,getWarpWalletAddressFromConfig as xr,parseOutputOutIndex as V,WarpConstants as G}from"@joai/warps";import{Transaction as Ar}from"@mysten/sui/transactions";import{WarpSerializer as Sr}from"@joai/warps";var m=class{constructor(){this.coreSerializer=new Sr}typedToString(r){if(r==null)return"option:null";if(typeof r=="string")return`string:${r}`;if(typeof r=="boolean")return`bool:${r}`;if(typeof r=="number")return`uint64:${r.toString()}`;if(typeof r=="bigint")return`uint64:${r.toString()}`;if(r&&typeof r=="object"&&r.address)return`address:${r.address}`;if(Array.isArray(r)){if(r.length===0)return"vector:u8:";let e=this.typeToString(typeof r[0]),t=r.map(i=>this.typedToString(i).split(":")[1]);return`vector:${e}:${t.join(",")}`}if(r&&typeof r=="object"&&r.type&&r.value&&r.type==="option")return r.value===null||r.value===void 0?"option:null":`option:${this.typedToString(r.value)}`;throw new Error(`WarpSuiSerializer (typedToString): Unsupported input type: ${typeof r}`)}typedToNative(r){let e=this.typedToString(r);return this.coreSerializer.stringToNative(e)}nativeToTyped(r,e){let t=this.coreSerializer.nativeToString(r,e);return this.stringToTyped(t)}stringToTyped(r,e){let t=e||new Ar,[i,n]=r.split(/:(.*)/,2);if(i==="object")return t.object(n);if(i==="string")return t.pure.string(n);if(i==="bool")return t.pure.bool(n==="true");if(i==="u8")return t.pure.u8(Number(n));if(i==="u16")return t.pure.u16(Number(n));if(i==="u32")return t.pure.u32(Number(n));if(i==="u64"||i==="uint64")return t.pure.u64(BigInt(n));if(i==="u128")return t.pure.u128(BigInt(n));if(i==="u256")return t.pure.u256(BigInt(n));if(i==="address")return t.pure.address(n);throw new Error(`WarpSuiSerializer (stringToTyped): Unsupported type: ${i}`)}typeToString(r){if(r==="string")return"string";if(r==="bool")return"bool";if(r==="u8")return"u8";if(r==="u16")return"u16";if(r==="u32")return"u32";if(r==="u64"||r==="bigint"||r==="number")return"u64";if(r==="u128")return"u128";if(r==="u256")return"u256";if(r==="address")return"address";if(r==="vector")return"vector";if(r==="option")return"option";throw new Error(`WarpSuiSerializer (typeToString): Unsupported input type: ${r}`)}nativeToType(r){throw new Error("Not implemented")}};var b=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new m;let t=Tr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Pr({url:t.url})}async getActionExecution(r,e,t){let i=await this.extractContractOutput(r,e,t,[]),n=Ir(this.config,[],r,e,i.output),a=Er(r,i.output,this.config);return{status:t.effects?.status?.status==="success"?"success":"error",warp:r,action:e,user:xr(this.config,this.chain.name),txHash:t.digest,tx:t,next:n,values:i.values,output:i.output,messages:a,destination:null,resolvedInputs:[]}}async extractContractOutput(r,e,t,i){let n=[],a=[],s={};if(!r.output)return{values:{string:n,native:a,mapped:{}},output:s};for(let[c,p]of Object.entries(r.output)){if(p.startsWith(G.Transform.Prefix))continue;if(p.startsWith("input.")){s[c]=p;continue}let u=V(p);if(u!==null&&u!==e){s[c]=null;continue}if(p.startsWith("out.")){let d=t.returnValues?t.returnValues[c]:null;s[c]=d,n.push(String(d)),a.push(d)}else s[c]=p}return{values:{string:n,native:a,mapped:{}},output:await H(r,s,a,e,i,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(r,e,t,i){let n=e.map(p=>String(p)),a=e,s={string:n,native:a,mapped:{}},c={};if(!r.output)return{values:s,output:c};for(let[p,u]of Object.entries(r.output)){if(u.startsWith(G.Transform.Prefix))continue;let d=V(u);if(d!==null&&d!==t){c[p]=null;continue}if(u.startsWith("out.")||u==="out")if(Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null){let rr=u.replace(/^out\./,"");c[p]=e[0][rr]}else c[p]=e[0];else c[p]=u}return{values:s,output:await H(r,c,a,t,i,this.serializer.coreSerializer,this.config)}}};var k=class{constructor(r,e){this.config=r;this.chain=e;this.serializer=new m,this.output=new b(this.config,this.chain);let t=Kr(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Br({url:t.url}),this.userWallet=Nr(this.config,this.chain.name)}async createTransaction(r){let e=O(r.warp,r.action);if(e.type==="transfer")return this.createTransferTransaction(r);if(e.type==="contract")return this.createContractCallTransaction(r);throw e.type==="query"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeQuery instead"):e.type==="collect"?new Error("WarpSuiExecutor: Invalid action type for createTransaction; Use executeCollect instead"):new Error(`WarpSuiExecutor: Invalid action type (${e.type})`)}async createTransferTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createTransfer - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid destination address");if(r.value<0)throw new Error(`WarpSuiExecutor: Transfer value cannot be negative: ${r.value}`);let e=new Q,t=[];if(r.value>0){let i=await this.handleCoinTransfer(e,"0x2::sui::SUI",r.value);t.push(i)}for(let i of r.transfers){let n=await this.handleCoinTransfer(e,i.identifier,i.amount);t.push(n)}return t.length>0&&e.transferObjects(t,e.pure.address(r.destination)),e}async createContractCallTransaction(r){if(!this.userWallet)throw new Error("WarpSuiExecutor: createContractCall - user address not set");if(!r.destination)throw new Error("WarpSuiExecutor: Invalid contract address");if(r.value<0)throw new Error(`WarpSuiExecutor: Contract call value cannot be negative: ${r.value}`);let e=O(r.warp,r.action);if(!e.func)throw new Error("WarpSuiExecutor: createContractCall - function not set");let t=new Q;t.setSender(this.userWallet);let i=[];r.value>0&&i.push(await this.handleCoinTransfer(t,"0x2::sui::SUI",r.value));for(let c of r.transfers)i.push(await this.handleCoinTransfer(t,c.identifier,c.amount));let{target:n,typeArguments:a}=this.parseMoveCallTarget(e),s=r.args.map(c=>this.serializer.stringToTyped(c,t));return n==="0x2::transfer::public_transfer"?i.push(...await this.buildPublicTransferArgs(t,r,s)):i.push(...s),t.moveCall({target:n,arguments:i,typeArguments:a}),t.setGasBudget(1e8),t}async executeQuery(r){if(!r.destination)throw new Error("WarpSuiExecutor: executeQuery - destination not set");let e=O(r.warp,r.action);if(e.type!=="query")throw new Error(`WarpSuiExecutor: Invalid action type for executeQuery: ${e.type}`);let t=await this.client.getObject({id:r.destination,options:{showContent:!0}}),i=[t],{values:n,output:a}=await this.output.extractQueryOutput(r.warp,i,r.action,r.resolvedInputs),s=kr(this.config,[],r.warp,r.action,a),p=r.resolvedInputs.find(d=>d.input.position==="receiver"||d.input.position==="destination")?.value||r.destination,u=Rr(r.resolvedInputs);return{status:"success",warp:r.warp,action:r.action,user:this.userWallet,txHash:null,tx:null,next:s,values:n,output:{...a,_DATA:t},resolvedInputs:u,messages:Ur(r.warp,a,this.config),destination:p}}async signMessage(r,e){throw new Error("Not implemented")}parseMoveCallTarget(r){if(!r.func)throw new Error("WarpSuiExecutor: Function not set");let e=`${r.address}::${r.func}`,t=r.typeArguments;if(!t&&r.func.includes("<")&&r.func.includes(">")){let i=r.func.match(/<([^>]+)>/);i&&(t=[i[1]],e=`${r.address}::${r.func.replace(/<[^>]+>/,"")}`)}return{target:e,typeArguments:t}}async buildPublicTransferArgs(r,e,t){let i=e.resolvedInputs.find(s=>String(s.input.position)==="arg:0")?.value||e.args[0],n=e.resolvedInputs.find(s=>String(s.input.position)==="arg:1")?.value||e.resolvedInputs.find(s=>s.input.type==="address"&&String(s.input.position)!=="arg:0")?.value||e.args[1],a=this.extractObjectId(i);if(!a)return t;try{if(!(await this.client.getObject({id:a,options:{showType:!0,showContent:!0}})).data?.type?.startsWith("0x2::coin::Coin<"))return t;let c=n?this.serializer.stringToTyped(n.includes(":")?n:`address:${n}`,r):t[1]||r.pure.address(this.userWallet);return[r.object(a),c]}catch{return t}}extractObjectId(r){if(!r||typeof r!="string")return null;let e=r.startsWith("object:")?r.substring(7):r;return e.startsWith("0x")?e:null}async handleCoinTransfer(r,e,t){if(e==="0x2::sui::SUI")try{return r.splitCoins(r.gas,[t.toString()])[0]}catch{}return this.createCoinTransferFromObjects(r,e,t)}async createCoinTransferFromObjects(r,e,t){let i=await this.getCoinObjectsForTransfer(e,t);if(i.length===0)throw new Error(`No coin objects found for ${e}`);let n=r.object(i[0].coinObjectId);return i.length>1&&r.mergeCoins(n,i.slice(1).map(a=>r.object(a.coinObjectId))),r.splitCoins(n,[t.toString()])[0]}async getCoinObjectsForTransfer(r,e){if(!this.userWallet)throw new Error("User wallet not set");let{data:t}=await this.client.getCoins({owner:this.userWallet,coinType:r}),i=t.map(s=>({coinObjectId:s.coinObjectId,balance:s.balance})).sort((s,c)=>BigInt(c.balance)>BigInt(s.balance)?1:-1),n=BigInt(0),a=[];for(let s of i)if(a.push(s),n+=BigInt(s.balance),n>=e)return a;throw new Error(`Insufficient ${r} balance. Required: ${e}, Available: ${n}`)}};var K=class{constructor(r,e){this.config=r;this.chain=e}getExplorers(){let r=z[this.chain.name];if(!r)return["suivision"];let e=r[this.config.env];return e||["suivision"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(r){let e=this.config.preferences?.explorers?.[this.chain.name];if(e&&!r){let n=y[e];if(n)return n}if(r){let n=y[r];if(n)return n}let t=this.getPrimaryExplorer();return y[t]||y[t]}getAccountUrl(r,e){return`${this.getExplorerUrlByName(e)}/account/${r}`}getTransactionUrl(r,e){return`${this.getExplorerUrlByName(e)}/txblock/${r}`}getBlockUrl(r,e){return`${this.getExplorerUrlByName(e)}/block/${r}`}getAssetUrl(r,e){return`${this.getExplorerUrlByName(e)}/coin/${r}`}getContractUrl(r,e){return`${this.getExplorerUrlByName(e)}/object/${r}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(r){return this.getExplorers().find(t=>t.toLowerCase()===r.toLowerCase())}getAccountUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(i=>{let n=y[i];n&&(t[i]=`${n}/account/${r}`)}),t}getTransactionUrls(r){let e=this.getAllExplorers(),t={};return e.forEach(i=>{let n=y[i];n&&(t[i]=`${n}/txblock/${r}`)}),t}};import{SuiClient as Dr}from"@mysten/sui/client";import{Transaction as h}from"@mysten/sui/transactions";import{getProviderConfig as $r,getWarpWalletAddressFromConfig as Or,WarpCache as Fr,WarpCacheKey as F,WarpLogger as g}from"@joai/warps";var N=class{constructor(r,e){this.config=r;this.chain=e;this.registryConfig={unitPrice:BigInt(0),admins:[]};let t=$r(this.config,this.chain.name,this.config.env,this.chain.defaultApiUrl);this.client=new Dr({url:t.url}),this.cache=new Fr(r.env,r.cache),this.userWallet=Or(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async loadRegistryConfigs(){try{let r=`${T(this.config.env)}::registry::get_config`;console.log("-- Loading registry configs",r);let e=new h;e.moveCall({target:r,arguments:[]});let t=await this.client.devInspectTransactionBlock({transactionBlock:e,sender:"0x0000000000000000000000000000000000000000000000000000000000000000"});console.log("-- Registry configs loaded",t);let i=t.results?.[0]?.returnValues?.[0],n=i&&Array.isArray(i)&&i[0]?JSON.parse(String.fromCharCode(...i[0])):{};this.registryConfig={unitPrice:n.unit_price!==void 0?BigInt(n.unit_price):BigInt(0),admins:Array.isArray(n.admins)?n.admins:[]}}catch(r){g.error("WarpSuiRegistry: Failed to load registry config",r),this.registryConfig={unitPrice:BigInt(0),admins:[]}}}async createWarpRegisterTransaction(r,e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let i=new h;return i.moveCall({target:l(this.config.env,"register_warp"),arguments:[i.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e?i.pure.option("string",e):i.pure.option("string",void 0),t?i.pure.option("vector<u8>",Array.from(Buffer.from(t,"hex"))):i.pure.option("vector<u8>",void 0),i.gas,i.pure.address(this.userWallet)]}),i}async createWarpUnregisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"unregister_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpUpgradeTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"upgrade_warp"),arguments:[t.pure.string(r),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpAliasSetTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"set_warp_alias"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.string(e),t.gas,t.pure.address(this.userWallet)]}),t}async createWarpVerifyTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"verify_warp"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpTransferOwnershipTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"transfer_ownership"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.address(e),t.gas,t.pure.address(this.userWallet)]}),t}async createBrandRegisterTransaction(r){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let e=new h;return e.moveCall({target:l(this.config.env,"register_brand"),arguments:[e.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),e.gas,e.pure.address(this.userWallet)]}),e}async createWarpBrandingTransaction(r,e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=new h;return t.moveCall({target:l(this.config.env,"brand_warp"),arguments:[t.pure.vector("u8",Array.from(Buffer.from(r,"hex"))),t.pure.vector("u8",Array.from(Buffer.from(e,"hex"))),t.gas,t.pure.address(this.userWallet)]}),t}async getInfoByAlias(r,e){let t=F.RegistryInfo(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return g.info(`WarpSuiRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),i;try{let n=await this.client.call(l(this.config.env,"get_info_by_alias"),[r]),a=n||null,s=a?x(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&await this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(n){return g.error("WarpSuiRegistry (getInfoByAlias):",n),{registryInfo:null,brand:null}}}async getInfoByHash(r,e){let t=F.RegistryInfo(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return g.info(`WarpSuiRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),i;try{let n=await this.client.call(l(this.config.env,"get_info_by_hash"),[Array.from(Buffer.from(r,"hex"))]),a=n||null,s=a?x(a):null,c=s?.brand?await this.fetchBrand(s.brand,e):null;return e&&e.ttl&&await this.cache.set(t,{registryInfo:s,brand:c},e.ttl),{registryInfo:s,brand:c}}catch(n){return g.error("WarpSuiRegistry (getInfoByHash):",n),{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(r){let e=`sui:registry:user:${r||this.userWallet}`,t=await this.cache.get(e);if(t)return g.info(`WarpSuiRegistry (getUserWarpRegistryInfos): RegistryInfos found in cache for user: ${r||this.userWallet}`),t;try{let i=r||this.userWallet;if(!i)throw new Error("WarpRegistry: user address not set");let n=await this.client.call(l(this.config.env,"get_user_warps"),[i]),a=Array.isArray(n)?n.map(x):[];return r&&await this.cache.set(e,a,300),a}catch(i){return g.error("WarpSuiRegistry (getUserWarpRegistryInfos):",i),[]}}async getUserBrands(r){let e=`sui:registry:user:brands:${r||this.userWallet}`,t=await this.cache.get(e);if(t)return g.info(`WarpSuiRegistry (getUserBrands): Brands found in cache for user: ${r||this.userWallet}`),t;try{let i=r||this.userWallet;if(!i)throw new Error("WarpRegistry: user address not set");let n=await this.client.call(l(this.config.env,"get_user_brands"),[i]);if(!Array.isArray(n))return[];let s=(await Promise.all(n.map(c=>this.fetchBrand(c)))).filter(c=>c!==null);return r&&await this.cache.set(e,s,300),s}catch(i){return g.error("WarpSuiRegistry (getUserBrands):",i),[]}}async fetchBrand(r,e){let t=F.Brand(this.config.env,r),i=e?await this.cache.get(t):null;if(i)return g.info(`WarpSuiRegistry (fetchBrand): Brand found in cache: ${r}`),i;try{let n=await this.client.getTransactionBlock({digest:r});if(!n||!n.effects)return null;let a=null;if(n.events&&Array.isArray(n.events)){for(let s of n.events)if(s.type&&typeof s.type=="string"&&s.type.includes("BrandRegistered"))try{a=s.parsedJson;break}catch{}}if(!a&&n.objectChanges&&Array.isArray(n.objectChanges)){for(let s of n.objectChanges)if(s.type==="created"&&s.objectType&&s.objectType.includes("Brand"))try{break}catch{}}return a?(a.meta={hash:r,creator:n.transaction&&n.transaction.data&&n.transaction.data.sender?n.transaction.data.sender:void 0,createdAt:n.timestampMs?new Date(Number(n.timestampMs)).toISOString():void 0},e&&e.ttl&&await this.cache.set(t,a,e.ttl),a):null}catch(n){return g.error("WarpSuiRegistry (fetchBrand):",n),null}}};import{initializeWalletCache as Xr}from"@joai/warps";import{Ed25519Keypair as D}from"@mysten/sui/keypairs/ed25519";import*as q from"@scure/bip39";import{wordlist as jr}from"@scure/bip39/wordlists/english.js";import{getWarpWalletAddressFromConfig as zr,getWarpWalletMnemonicFromConfig as L,getWarpWalletPrivateKeyFromConfig as Mr,normalizeAndValidateMnemonic as _r,normalizeMnemonic as Hr,removeWarpWalletFromConfig as Vr,setWarpWalletInConfig as J,validateMnemonicLength as Gr}from"@joai/warps";var W=class W{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return zr(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),i=await e.signPersonalMessage(t);return{...r,signature:i.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=_r(r),i=D.deriveKeypair(e).getPublicKey().toSuiAddress(),n={provider:W.PROVIDER_NAME,address:i,privateKey:null,mnemonic:e};return J(this.config,this.chain.name,n),n}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let n=D.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:W.PROVIDER_NAME,address:n,privateKey:r,mnemonic:null};return J(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=L(this.config,this.chain.name),t=Mr(this.config,this.chain.name);return{provider:W.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:t||null,mnemonic:e||null}}async generate(){let r=q.generateMnemonic(jr,256),e=Hr(r);Gr(e);let i=D.deriveKeypair(e).getPublicKey().toSuiAddress();return{provider:W.PROVIDER_NAME,address:i,privateKey:null,mnemonic:e}}async delete(r){Vr(this.config,this.chain.name)}getKeypair(){if(this.keypair)return this.keypair;let r=L(this.config,this.chain.name);if(!r)throw new Error("No mnemonic provided");return this.keypair=D.deriveKeypair(r.trim()),this.keypair}};W.PROVIDER_NAME="mnemonic";var A=W;import{getWarpWalletAddressFromConfig as P,removeWarpWalletFromConfig as Qr}from"@joai/warps";var v=class{constructor(r,e){this.config=r;this.chain=e}async getAddress(){return P(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async signMessage(r){let e=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromMnemonic(r){let e=P(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async importFromPrivateKey(r){let e=P(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async export(){let r=P(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async generate(){let r=P(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${r}`)}async delete(r){Qr(this.config,this.chain.name)}};import{Ed25519Keypair as E}from"@mysten/sui/keypairs/ed25519";import{getWarpWalletAddressFromConfig as Lr,getWarpWalletMnemonicFromConfig as Jr,getWarpWalletPrivateKeyFromConfig as X,removeWarpWalletFromConfig as qr,setWarpWalletInConfig as Y}from"@joai/warps";var w=class w{constructor(r,e){this.config=r;this.chain=e;this.keypair=null}async getAddress(){return Lr(this.config,this.chain.name)}async getPublicKey(){try{let e=this.getKeypair().getPublicKey();return Buffer.from(e.toRawBytes()).toString("hex")}catch{return null}}async signTransaction(r){if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return r;let e=this.getKeypair(),t=new TextEncoder().encode(JSON.stringify(r)),i=await e.signPersonalMessage(t);return{...r,signature:i.signature}}async signMessage(r){let e=this.getKeypair(),t=new TextEncoder().encode(r);return(await e.signPersonalMessage(t)).signature}getKeypairInstance(){return this.getKeypair()}async importFromMnemonic(r){let e=E.deriveKeypair(r.trim()),t=e.getPublicKey().toSuiAddress(),i=Buffer.from(e.getSecretKey()).toString("hex"),n={provider:w.PROVIDER_NAME,address:t,privateKey:i,mnemonic:r};return Y(this.config,this.chain.name,n),n}async importFromPrivateKey(r){let e=Buffer.from(r,"hex"),t;if(e.length===70)t=new Uint8Array(e.subarray(1,33));else if(e.length===32)t=new Uint8Array(e);else throw new Error(`Unsupported private key length: ${e.length} bytes`);let n=E.fromSecretKey(t).getPublicKey().toSuiAddress(),a={provider:w.PROVIDER_NAME,address:n,privateKey:r,mnemonic:null};return Y(this.config,this.chain.name,a),a}async export(){let r=this.getKeypair(),e=X(this.config,this.chain.name),t=Jr(this.config,this.chain.name);return{provider:w.PROVIDER_NAME,address:r.getPublicKey().toSuiAddress(),privateKey:e||null,mnemonic:t||null}}async generate(){let r=E.generate(),e=r.getPublicKey().toSuiAddress(),t=Buffer.from(r.getSecretKey()).toString("hex");return{provider:w.PROVIDER_NAME,address:e,privateKey:t,mnemonic:null}}async delete(r){qr(this.config,this.chain.name)}getKeypair(){if(this.keypair)return this.keypair;let r=X(this.config,this.chain.name);if(!r)throw new Error("Wallet not initialized - no private key provided");try{let e=Buffer.from(r,"hex");if(e.length===70){let t=new Uint8Array(e.subarray(1,33));return this.keypair=E.fromSecretKey(t),this.keypair}else{if(e.length===32)return this.keypair=E.fromSecretKey(new Uint8Array(e)),this.keypair;throw new Error(`Unsupported private key length: ${e.length} bytes`)}}catch(e){throw e}}};w.PROVIDER_NAME="privateKey";var S=w;var $=class{constructor(r,e){this.config=r;this.chain=e;this.cachedAddress=null;this.cachedPublicKey=null;this.client=M(r,e),this.walletProvider=this.createProvider(),this.isInitializedPromise=new Promise(t=>{this.isInitializedResolve=t}),this.initializeCache()}async waitUntilInitialized(){await this.isInitializedPromise}async signTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof v)throw new Error(`Wallet (${this.chain.name}) is read-only`);return(this.walletProvider instanceof S||this.walletProvider instanceof A)&&r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function"?r:await this.walletProvider.signTransaction(r)}async signMessage(r){if(await this.waitUntilInitialized(),!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof v)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(r)}async signTransactions(r){return await this.waitUntilInitialized(),r}async sendTransaction(r){if(await this.waitUntilInitialized(),!r||typeof r!="object")throw new Error("Invalid transaction object");if(r.transactionHash)return r.transactionHash;if(r&&typeof r=="object"&&"bytes"in r&&"signature"in r)return(await this.client.executeTransactionBlock({transactionBlock:r.bytes,signature:Array.isArray(r.signature)?r.signature:[r.signature],options:{showEffects:!0,showEvents:!0}})).digest;if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof S||this.walletProvider instanceof A){let e=this.walletProvider.getKeypairInstance();if(r&&typeof r=="object"&&"sign"in r&&typeof r.sign=="function")return(await this.client.signAndExecuteTransaction({transaction:r,signer:e,options:{showEffects:!0,showEvents:!0}})).digest;throw new Error(`Transaction must be a Transaction object or have bytes and signature. Got: ${typeof r}, has sign: ${r&&typeof r=="object"&&"sign"in r}, has bytes: ${r&&typeof r=="object"&&"bytes"in r}, has signature: ${r&&typeof r=="object"&&"signature"in r}`)}throw new Error("Remote wallet provider must return signed payload (bytes + signature) or transactionHash for Sui transactions")}async sendTransactions(r){return await this.waitUntilInitialized(),Promise.all(r.map(async e=>this.sendTransaction(e)))}async importFromMnemonic(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("mnemonic").importFromMnemonic(r)}async importFromPrivateKey(r){return await this.waitUntilInitialized(),await this.createProviderForOperation("privateKey").importFromPrivateKey(r)}async export(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).export()}async generate(r){return await this.waitUntilInitialized(),await this.createProviderForOperation(r).generate()}async delete(r,e){await this.waitUntilInitialized(),await this.createProviderForOperation(r).delete(e)}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let r=this.config.user?.wallets?.[this.chain.name];return r?typeof r=="string"?new v(this.config,this.chain):r.provider?this.createProviderForOperation(r.provider):new v(this.config,this.chain):null}async initializeCache(){let r=await Xr(this.walletProvider);this.cachedAddress=r.address,this.cachedPublicKey=r.publicKey,this.isInitializedResolve()}createProviderForOperation(r){let t=this.config.walletProviders?.[this.chain.name]?.[r];if(t){let i=t(this.config,this.chain);if(!i)throw new Error(`Custom wallet provider factory returned null for ${r}`);return i}if(r==="privateKey")return new S(this.config,this.chain);if(r==="mnemonic")return new A(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${r}`)}};var j={chain:I.Sui,identifier:"0x2::sui::SUI",name:"SUI",symbol:"SUI",decimals:9,logoUrl:"https://assets.coingecko.com/coins/images/26375/standard/sui-ocean-square.png?1727791290"};function Yr(o,r){return(e,t)=>{let i=r[e.env];if(!i)throw new Error(`SuiAdapter: chain info not found for chain ${o}`);return{chainInfo:i,builder:()=>new U(e,i),executor:new k(e,i),output:new b(e,i),serializer:new m,registry:new N(e,i),explorer:new K(e,i),abiBuilder:()=>new C(e,i),brandBuilder:()=>new B(e,i),dataLoader:new R(e,i),wallet:new $(e,i)}}}var Qi=Yr(I.Sui,{mainnet:{name:I.Sui,displayName:"Sui",chainId:"1",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.mainnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:j},testnet:{name:I.Sui,displayName:"Sui Testnet",chainId:"testnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.testnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:j},devnet:{name:I.Sui,displayName:"Sui Devnet",chainId:"devnet",blockTime:3e3,addressHrp:"sui",defaultApiUrl:"https://fullnode.devnet.sui.io",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/sui.svg",nativeToken:j}});var Z=class{constructor(r,e){this.abi=new C(r,e)}async loadModuleAbi(r,e){return this.abi.getModuleAbi(r,e)}async loadFunctionAbi(r,e,t){return this.abi.getFunctionAbi(r,e,t)}};export{y as ExplorerUrls,yr as KnownTokens,j as NativeTokenSui,Qi as SuiAdapter,er as SuiExplorers,z as SuiExplorersConfig,C as WarpSuiAbiBuilder,B as WarpSuiBrandBuilder,U as WarpSuiBuilder,ee as WarpSuiConstants,Z as WarpSuiContractLoader,R as WarpSuiDataLoader,k as WarpSuiExecutor,K as WarpSuiExplorer,b as WarpSuiOutput,N as WarpSuiRegistry,m as WarpSuiSerializer,$ as WarpSuiWallet,_ as findKnownTokenById,M as getConfiguredSuiClient,Zr as getSuiRegistryObjectId,T as getSuiRegistryPackageId,l as toRegistryMoveTarget,x as toTypedRegistryInfo};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps-adapter-sui",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -38,6 +38,6 @@
38
38
  "dependencies": {
39
39
  "@mysten/sui": "^1.45.2",
40
40
  "@scure/bip39": "^2.0.1",
41
- "@joai/warps": "^4.1.0"
41
+ "@joai/warps": "^4.3.0"
42
42
  }
43
43
  }