dipcoin-cli 0.5.0 → 0.8.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/README.md +215 -543
- package/dist/cli/commands/account.d.ts.map +1 -1
- package/dist/cli/commands/balance.d.ts.map +1 -1
- package/dist/cli/commands/history.d.ts.map +1 -1
- package/dist/cli/commands/market.d.ts.map +1 -1
- package/dist/cli/commands/orders.d.ts +3 -0
- package/dist/cli/commands/orders.d.ts.map +1 -0
- package/dist/cli/commands/position.d.ts.map +1 -1
- package/dist/cli/commands/sub-account.d.ts +3 -0
- package/dist/cli/commands/sub-account.d.ts.map +1 -0
- package/dist/cli/commands/trade.d.ts.map +1 -1
- package/dist/cli/commands/vault.d.ts +0 -1
- package/dist/cli/commands/vault.d.ts.map +1 -1
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/utils/output.d.ts +8 -0
- package/dist/cli/utils/output.d.ts.map +1 -1
- package/dist/cli/utils/sdk-factory.d.ts +35 -2
- package/dist/cli/utils/sdk-factory.d.ts.map +1 -1
- package/dist/cli/utils/vault-index.d.ts +6 -0
- package/dist/cli/utils/vault-index.d.ts.map +1 -0
- package/dist/cli.cjs +1521 -258
- package/dist/cli.cjs.map +1 -0
- package/dist/config/deployed/testnet/main_contract.json +58 -275
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +2 -2
- package/dist/index.esm.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/src/config/index.d.ts.map +1 -1
- package/dist/src/constants/index.d.ts +1 -0
- package/dist/src/constants/index.d.ts.map +1 -1
- package/dist/src/onchain/exchange.d.ts +41 -0
- package/dist/src/onchain/exchange.d.ts.map +1 -0
- package/dist/src/onchain/index.d.ts +5 -0
- package/dist/src/onchain/index.d.ts.map +1 -0
- package/dist/src/onchain/order-signer.d.ts +17 -0
- package/dist/src/onchain/order-signer.d.ts.map +1 -0
- package/dist/src/onchain/transaction-builder.d.ts +46 -0
- package/dist/src/onchain/transaction-builder.d.ts.map +1 -0
- package/dist/src/sdk/sdk.d.ts +117 -4
- package/dist/src/sdk/sdk.d.ts.map +1 -1
- package/dist/src/types/index.d.ts +6 -1
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/src/utils/jwt-cache.d.ts +14 -0
- package/dist/src/utils/jwt-cache.d.ts.map +1 -0
- package/package.json +6 -10
package/dist/index.esm.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"bignumber.js";import{Buffer as t}from"node:buffer";import n from"axios";import{spawn as r}from"child_process";import{Buffer as s}from"buffer";import i from"fs";import a from"path";import{fileURLToPath as o}from"url";import c from"os";const u={mainnet:"https://gray-api.dipcoin.io",testnet:"https://demoapi.dipcoin.io/exchange"};function d(e){return{apiBaseUrl:e.apiBaseUrl||u[e.network],network:e.network,customRpc:e.customRpc,subAccountKey:e.subAccountKey}}const l="1.45.0",h={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class p extends Error{}class f extends p{constructor(e,t){super(e),this.code=t,this.type=h[t]??"ServerError"}}class g extends p{constructor(e,t,n){super(e),this.status=t,this.statusText=n}}var m,y,b,w,v,k,E,S,x,O=e=>{throw TypeError(e)},I=(e,t,n)=>t.has(e)||O("Cannot "+n),T=(e,t,n)=>(I(e,t,"read from private field"),n?n.call(e):t.get(e)),_=(e,t,n)=>t.has(e)?O("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),A=(e,t,n,r)=>(I(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),j=(e,t,n)=>(I(e,t,"access private method"),n);const C={WebSocketConstructor:"undefined"!=typeof WebSocket?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class P{constructor(e,t={}){if(_(this,E),_(this,m,0),_(this,y,0),_(this,b,null),_(this,w,null),_(this,v,new Set),_(this,k,new Map),this.endpoint=e,this.options={...C,...t},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=function(e){const t=new URL(e);return t.protocol=t.protocol.replace("http","ws"),t.toString()}(this.endpoint))}async makeRequest(e,t,n){const r=await j(this,E,S).call(this);return new Promise((s,i)=>{A(this,m,T(this,m)+1),T(this,k).set(T(this,m),{resolve:s,reject:i,timeout:setTimeout(()=>{T(this,k).delete(T(this,m)),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n?.addEventListener("abort",()=>{T(this,k).delete(T(this,m)),i(n.reason)}),r.send(JSON.stringify({jsonrpc:"2.0",id:T(this,m),method:e,params:t}))}).then(({error:e,result:t})=>{if(e)throw new f(e.message,e.code);return t})}async subscribe(e){const t=new B(e);return T(this,v).add(t),await t.subscribe(this),()=>t.unsubscribe(this)}}m=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,v=new WeakMap,k=new WeakMap,E=new WeakSet,S=function(){return T(this,w)||A(this,w,new Promise(e=>{T(this,b)?.close(),A(this,b,new this.options.WebSocketConstructor(this.endpoint)),T(this,b).addEventListener("open",()=>{A(this,y,0),e(T(this,b))}),T(this,b).addEventListener("close",()=>{var e,t,n,r;(e=this,t=y,{set _(r){A(e,t,r,n)},get _(){return T(e,t,r)}})._++,T(this,y)<=this.options.maxReconnects&&setTimeout(()=>{j(this,E,x).call(this)},this.options.reconnectTimeout)}),T(this,b).addEventListener("message",({data:e})=>{let t;try{t=JSON.parse(e)}catch(e){return}if("id"in t&&null!=t.id&&T(this,k).has(t.id)){const{resolve:e,timeout:n}=T(this,k).get(t.id);clearTimeout(n),e(t)}else if("params"in t){const{params:e}=t;T(this,v).forEach(t=>{t.subscriptionId===e.subscription&&e.subscription===t.subscriptionId&&t.onMessage(e.result)})}})})),T(this,w)},x=async function(){return T(this,b)?.close(),A(this,w,null),Promise.allSettled([...T(this,v)].map(e=>e.subscribe(this)))};class B{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:t}=this;return this.subscribed=!1,null!=t&&(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const t=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=t)}}var N,$,R,M,D,U=e=>{throw TypeError(e)},V=(e,t,n)=>t.has(e)||U("Cannot "+n),F=(e,t,n)=>(V(e,t,"read from private field"),n?n.call(e):t.get(e)),L=(e,t,n)=>t.has(e)?U("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),K=(e,t,n,r)=>(V(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class q{constructor(e){L(this,M),L(this,N,0),L(this,$),L(this,R),K(this,$,e)}fetch(e,t){const n=F(this,$).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,t)}async request(e){K(this,N,F(this,N)+1);const t=await this.fetch(F(this,$).rpc?.url??F(this,$).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":l,"Client-Target-Api-Version":"1.61.0","Client-Request-Method":e.method,...F(this,$).rpc?.headers},body:JSON.stringify({jsonrpc:"2.0",id:F(this,N),method:e.method,params:e.params})});if(!t.ok)throw new g(`Unexpected status code: ${t.status}`,t.status,t.statusText);const n=await t.json();if("error"in n&&null!=n.error)throw new f(n.error.message,n.error.code);return n.result}async subscribe(e){const t=await(n=this,r=M,s=D,V(n,r,"access private method"),s).call(this).subscribe(e);var n,r,s;return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{t()})),async()=>!!await t()}}
|
|
2
2
|
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
function W(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function G(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function H(e){if("function"!=typeof e)throw new Error("function expected");return!0}function J(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function Y(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function X(e){if(!Array.isArray(e))throw new Error("array expected")}function Q(e,t){if(!G(!0,t))throw new Error(`${e}: array of strings expected`)}function ee(e,t){if(!G(!1,t))throw new Error(`${e}: array of numbers expected`)}function te(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function ne(e){const t="string"==typeof e?e.split(""):e,n=t.length;Q("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(X(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(X(t),t.map(t=>{J("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function re(e=""){return J("join",e),{encode:t=>(Q("join.decode",t),t.join(e)),decode:t=>(J("join.decode",t),t.split(e))}}function se(e,t="="){return Y(e),J("padding",t),{encode(n){for(Q("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){Q("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--){if((r-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return n.slice(0,r)}}}function ie(e){return H(e),{encode:e=>e,decode:t=>e(t)}}function ae(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(X(e),!e.length)return[];let r=0;const s=[],i=Array.from(e,e=>{if(Y(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e}),a=i.length;for(;;){let e=0,o=!0;for(let s=r;s<a;s++){const a=i[s],c=t*e,u=c+a;if(!Number.isSafeInteger(u)||c/t!==e||u-a!==c)throw new Error("convertRadix: carry overflow");const d=u/n;e=u%n;const l=Math.floor(d);if(i[s]=l,!Number.isSafeInteger(l)||l*n+e!==u)throw new Error("convertRadix: carry overflow");o&&(l?o=!1:r=s)}if(s.push(e),o)break}for(let t=0;t<e.length-1&&0===e[t];t++)s.push(0);return s.reverse()}$=new WeakMap,M=new WeakMap,U=new WeakMap,D=new WeakSet,F=function(){if(!K(this,U)){const e=K(this,M).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");q(this,U,new N(K(this,M).websocket?.url??K(this,M).url,{WebSocketConstructor:e,...K(this,M).websocket}))}return K(this,U)};const oe=(e,t)=>0===t?e:oe(t,e%t),ce=(e,t)=>e+(t-oe(e,t)),ue=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function de(e,t,n,r){if(X(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ce(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ce(t,n)}`);let s=0,i=0;const a=ue[t],o=ue[n]-1,c=[];for(const r of e){if(Y(r),r>=a)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(s=s<<t|r,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=n;i-=n)c.push((s>>i-n&o)>>>0);const e=ue[i];if(void 0===e)throw new Error("invalid carry");s&=e-1}if(s=s<<n-i&o,!r&&i>=t)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&c.push(s>>>0),c}function le(e,t=!1){if(Y(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ce(8,e)>32||ce(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!W(n))throw new Error("radix2.encode input should be Uint8Array");return de(Array.from(n),8,e,!t)},decode:n=>(ee("radix2.decode",n),Uint8Array.from(de(n,e,8,t)))}}function he(e){return H(e),function(...t){try{return e.apply(null,t)}catch(e){}}}te(le(4),ne("0123456789ABCDEF"),re("")),te(le(5),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),se(5),re("")),te(le(5),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),re("")),te(le(5),ne("0123456789ABCDEFGHIJKLMNOPQRSTUV"),se(5),re("")),te(le(5),ne("0123456789ABCDEFGHIJKLMNOPQRSTUV"),re("")),te(le(5),ne("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),re(""),ie(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const fe=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();fe||te(le(6),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),se(6),re("")),te(le(6),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),re("")),fe||te(le(6),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),se(6),re("")),te(le(6),ne("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),re(""));const pe=e=>{return te((Y(t=58),{encode:e=>{if(!W(e))throw new Error("radix.encode input should be Uint8Array");return ae(Array.from(e),256,t)},decode:e=>(ee("radix.decode",e),Uint8Array.from(ae(e,t,256)))}),ne(e),re(""));var t},ge=pe("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");pe("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),pe("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const me=te(ne("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),re("")),ye=[996825010,642813549,513874426,1027748829,705979059];function be(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<ye.length;e++)1==(t>>e&1)&&(n^=ye[e]);return n}function we(e,t,n=1){const r=e.length;let s=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);s=be(s)^n>>5}s=be(s);for(let t=0;t<r;t++)s=be(s)^31&e.charCodeAt(t);for(let e of t)s=be(s)^e;for(let e=0;e<6;e++)s=be(s);return s^=n,me.encode(de([s%ue[30]],30,5,!1))}function ve(e){const t="bech32"===e?1:734539939,n=le(5),r=n.decode,s=n.encode,i=he(r);function a(e,n,r=90){J("bech32.encode prefix",e),W(n)&&(n=Array.from(n)),ee("bech32.encode",n);const s=e.length;if(0===s)throw new TypeError(`Invalid prefix length ${s}`);const i=s+7+n.length;if(!1!==r&&i>r)throw new TypeError(`Length ${i} exceeds limit ${r}`);const a=e.toLowerCase(),o=we(a,n,t);return`${a}1${me.encode(n)}${o}`}function o(e,n=90){J("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const s=e.toLowerCase();if(e!==s&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=s.lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const a=s.slice(0,i),o=s.slice(i+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const c=me.decode(o).slice(0,-6),u=we(a,c,t);if(!o.endsWith(u))throw new Error(`Invalid checksum in ${e}: expected "${u}"`);return{prefix:a,words:c}}return{encode:a,decode:o,encodeFromBytes:function(e,t){return a(e,s(t))},decodeToBytes:function(e){const{prefix:t,words:n}=o(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:he(o),fromWords:r,fromWordsUnsafe:i,toWords:s}}const Ee=ve("bech32");ve("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||te(le(4),ne("0123456789abcdef"),re(""),ie(e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const ke=e=>ge.encode(e),Se=e=>ge.decode(e);function Oe(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}const xe=8192;function Ie(e){if(e.length<xe)return btoa(String.fromCharCode(...e));let t="";for(var n=0;n<e.length;n+=xe){const r=e.slice(n,n+xe);t+=String.fromCharCode(...r)}return btoa(t)}function Te(e){const t=e.startsWith("0x")?e.slice(2):e,n=t.length%2==0?t:`0${t}`,r=n.match(/[0-9a-fA-F]{2}/g)?.map(e=>parseInt(e,16))??[];if(r.length!==n.length/2)throw new Error(`Invalid hex string ${e}`);return Uint8Array.from(r)}function _e(e){return e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Ae(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}class Ce{constructor(e,t){if("function"!=typeof e)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=function(e){const t=!e||!1!==e.batch;if(!t)return 1;const n=e&&e.maxBatchSize;if(void 0===n)return 1/0;if("number"!=typeof n||n<1)throw new TypeError(`maxBatchSize must be a positive number: ${n}`);return n}(t),this._batchScheduleFn=function(e){const t=e&&e.batchScheduleFn;if(void 0===t)return je;if("function"!=typeof t)throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}(t),this._cacheKeyFn=function(e){const t=e&&e.cacheKeyFn;if(void 0===t)return e=>e;if("function"!=typeof t)throw new TypeError(`cacheKeyFn must be a function: ${t}`);return t}(t),this._cacheMap=function(e){const t=!e||!1!==e.cache;if(!t)return null;const n=e&&e.cacheMap;if(void 0===n)return new Map;if(null!==n){const e=["get","set","delete","clear"].filter(e=>n&&"function"!=typeof n[e]);if(0!==e.length)throw new TypeError("Custom cacheMap missing methods: "+e.join(", "))}return n}(t),this._batch=null,this.name=function(e){if(e&&e.name)return e.name;return null}(t)}load(e){if(null==e)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const t=function(e){const t=e._batch;if(null!==t&&!t.hasDispatched&&t.keys.length<e._maxBatchSize)return t;const n={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=n,e._batchScheduleFn(()=>{!function(e,t){if(t.hasDispatched=!0,0===t.keys.length)return void Ne(t);let n;try{n=e._batchLoadFn(t.keys)}catch(n){return Be(e,t,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!n||"function"!=typeof n.then)return Be(e,t,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(n)}.`));Promise.resolve(n).then(e=>{if(!Re(e))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(e)}.`);if(e.length!==t.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.\n\nKeys:\n${String(t.keys)}\n\nValues:\n${String(e)}`);Ne(t);for(let n=0;n<t.callbacks.length;n++){const r=e[n];r instanceof Error?t.callbacks[n].reject(r):t.callbacks[n].resolve(r)}}).catch(n=>{Be(e,t,n)})}(e,n)}),n}(this),n=this._cacheMap;let r;if(n){r=this._cacheKeyFn(e);const s=n.get(r);if(s){const e=t.cacheHits||(t.cacheHits=[]);return new Promise(t=>{e.push(()=>{t(s)})})}}t.keys.push(e);const s=new Promise((e,n)=>{t.callbacks.push({resolve:e,reject:n})});return n&&n.set(r,s),s}loadMany(e){if(!Re(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const t=[];for(let n=0;n<e.length;n++)t.push(this.load(e[n]).catch(e=>e));return Promise.all(t)}clear(e){const t=this._cacheMap;if(t){const n=this._cacheKeyFn(e);t.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,t){const n=this._cacheMap;if(n){const r=this._cacheKeyFn(e);if(void 0===n.get(r)){let e;t instanceof Error?(e=Promise.reject(t),e.catch(()=>{})):e=Promise.resolve(t),n.set(r,e)}}return this}}const je="object"==typeof process&&"function"==typeof process.nextTick?function(e){Pe||(Pe=Promise.resolve()),Pe.then(()=>{process.nextTick(e)})}:"function"==typeof setImmediate?function(e){setImmediate(e)}:function(e){setTimeout(e)};let Pe;function Be(e,t,n){Ne(t);for(let r=0;r<t.keys.length;r++)e.clear(t.keys[r]),t.callbacks[r].reject(n)}function Ne(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Re(e){return"object"==typeof e&&null!==e&&"length"in e&&"number"==typeof e.length&&(0===e.length||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}function $e(e){let t=BigInt(e);const n=[];let r=0;if(0n===t)return[0];for(;t>0;)n[r]=Number(0x7fn&t),t>>=7n,t>0n&&(n[r]|=128),r+=1;return n}class Me{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),t=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+t).toString(10)}read128(){const e=BigInt(this.read64()),t=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+t).toString(10)}read256(){const e=BigInt(this.read128()),t=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+t).toString(10)}readBytes(e){const t=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,t,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,t=new Uint8Array(this.dataView.buffer,e),{value:n,length:r}=function(e){let t=0n,n=0n,r=0;for(;;){if(r>=e.length)throw new Error("ULEB decode error: buffer overflow");const s=e[r];if(r+=1,t+=BigInt(127&s)<<n,!(128&s))break;n+=7n}if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(t),length:r}}(t);return this.shift(r),n}readVec(e){const t=this.readULEB(),n=[];for(let r=0;r<t;r++)n.push(e(this,r,t));return n}}function Ue(e,t=["<",">"]){const[n,r]=t,s=[];let i="",a=0;for(let t=0;t<e.length;t++){const o=e[t];o===n&&a++,o===r&&a--,0!==a||","!==o?i+=o:(s.push(i.trim()),i="")}return s.push(i.trim()),s}class De{constructor({initialSize:e=1024,maxSize:t=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=t,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const t=this.bytePosition+e;if(t>this.size){const e=Math.min(this.maxSize,Math.max(this.size+t,this.size+this.allocateSize));if(t>e)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${t}`);this.size=e;const n=new ArrayBuffer(this.size);new Uint8Array(n).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(n)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}writeBytes(e){this.ensureSizeOrGrow(e.length);for(let t=0;t<e.length;t++)this.dataView.setUint8(this.bytePosition+t,e[t]);return this.shift(e.length)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return Fe(BigInt(e),8).forEach(e=>this.write8(e)),this}write128(e){return Fe(BigInt(e),16).forEach(e=>this.write8(e)),this}write256(e){return Fe(BigInt(e),32).forEach(e=>this.write8(e)),this}writeULEB(e){return $e(e).forEach(e=>this.write8(e)),this}writeVec(e,t){return this.writeULEB(e.length),Array.from(e).forEach((n,r)=>t(this,n,r,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return function(e,t){switch(t){case"base58":return ke(e);case"base64":return Ie(e);case"hex":return _e(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}(this.toBytes(),e)}}function Fe(e,t){const n=new Uint8Array(t);let r=0;for(;e>0;)n[r]=Number(e%BigInt(256)),e/=BigInt(256),r+=1;return n}var Le,Ve,Ke,ze,qe=e=>{throw TypeError(e)},Ze=(e,t,n)=>t.has(e)||qe("Cannot "+n),We=(e,t,n)=>(Ze(e,t,"read from private field"),n?n.call(e):t.get(e)),Ge=(e,t,n)=>t.has(e)?qe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),He=(e,t,n,r)=>(Ze(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);Le=new WeakMap,Ve=new WeakMap;let Je=class e{constructor(e){Ge(this,Le),Ge(this,Ve),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),He(this,Le,e.write),He(this,Ve,e.serialize??((e,t)=>{const n=new De({initialSize:this.serializedSize(e)??void 0,...t});return We(this,Le).call(this,e,n),n.toBytes()})),this.validate=e.validate??(()=>{})}write(e,t){this.validate(e),We(this,Le).call(this,e,t)}serialize(e,t){return this.validate(e),new Qe(this,We(this,Ve).call(this,e,t))}parse(e){const t=new Me(e);return this.read(t)}fromHex(e){return this.parse(Te(e))}fromBase58(e){return this.parse(Se(e))}fromBase64(e){return this.parse(Oe(e))}transform({name:t,input:n,output:r,validate:s}){return new e({name:t??this.name,read:e=>r?r(this.read(e)):this.read(e),write:(e,t)=>We(this,Le).call(this,n?n(e):e,t),serializedSize:e=>this.serializedSize(n?n(e):e),serialize:(e,t)=>We(this,Ve).call(this,n?n(e):e,t),validate:e=>{s?.(e),this.validate(n?n(e):e)}})}};const Ye=Symbol.for("@mysten/serialized-bcs");function Xe(e){return!!e&&"object"==typeof e&&!0===e[Ye]}class Qe{constructor(e,t){Ge(this,Ke),Ge(this,ze),He(this,Ke,e),He(this,ze,t)}get[Ye](){return!0}toBytes(){return We(this,ze)}toHex(){return _e(We(this,ze))}toBase64(){return Ie(We(this,ze))}toBase58(){return ke(We(this,ze))}parse(){return We(this,Ke).parse(We(this,ze))}}function et({size:e,...t}){return new Je({...t,serializedSize:()=>e})}function tt({readMethod:e,writeMethod:t,...n}){return et({...n,read:t=>t[e](),write:(e,n)=>n[t](e),validate:e=>{if(e<0||e>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${e}. Expected value in range 0-${n.maxValue}`);n.validate?.(e)}})}function nt({readMethod:e,writeMethod:t,...n}){return et({...n,read:t=>t[e](),write:(e,n)=>n[t](BigInt(e)),validate:e=>{const t=BigInt(e);if(t<0||t>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${t}. Expected value in range 0-${n.maxValue}`);n.validate?.(t)}})}Ke=new WeakMap,ze=new WeakMap;class rt extends Je{constructor({name:e,fields:t,...n}){const r=Object.entries(t);super({name:e,serializedSize:e=>{let t=0;for(const[n,s]of r){const r=s.serializedSize(e[n]);if(null==r)return null;t+=r}return t},read:e=>{const t={};for(const[n,s]of r)t[n]=s.read(e);return t},write:(e,t)=>{for(const[n,s]of r)s.write(e[n],t)},...n,validate:e=>{if(n?.validate?.(e),"object"!=typeof e||null==e)throw new TypeError("Expected object, found "+typeof e)}})}}class st extends Je{constructor({fields:e,...t}){const n=Object.entries(e);super({read:e=>{const r=e.readULEB(),s=n[r];if(!s)throw new TypeError(`Unknown value ${r} for enum ${t.name}`);const[i,a]=s;return{[i]:a?.read(e)??!0,$kind:i}},write:(t,r)=>{const[s,i]=Object.entries(t).filter(([t])=>Object.hasOwn(e,t))[0];for(let e=0;e<n.length;e++){const[t,a]=n[e];if(t===s)return r.writeULEB(e),void a?.write(i,r)}},...t,validate:n=>{if(t?.validate?.(n),"object"!=typeof n||null==n)throw new TypeError("Expected object, found "+typeof n);const r=Object.keys(n).filter(t=>void 0!==n[t]&&Object.hasOwn(e,t));if(1!==r.length)throw new TypeError(`Expected object with one key, but found ${r.length} for type ${t.name}}`);const[s]=r;if(!Object.hasOwn(e,s))throw new TypeError(`Invalid enum variant ${s}`)}})}}class it extends Je{constructor({fields:e,name:t,...n}){super({name:t??`(${e.map(e=>e.name).join(", ")})`,serializedSize:t=>{let n=0;for(let r=0;r<e.length;r++){const s=e[r].serializedSize(t[r]);if(null==s)return null;n+=s}return n},read:t=>{const n=[];for(const r of e)n.push(r.read(t));return n},write:(t,n)=>{for(let r=0;r<e.length;r++)e[r].write(t[r],n)},...n,validate:t=>{if(n?.validate?.(t),!Array.isArray(t))throw new TypeError("Expected array, found "+typeof t);if(t.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${t.length}`)}})}}const at={u8:e=>tt({readMethod:"read8",writeMethod:"write8",size:1,maxValue:255,...e,name:e?.name??"u8"}),u16:e=>tt({readMethod:"read16",writeMethod:"write16",size:2,maxValue:65535,...e,name:e?.name??"u16"}),u32:e=>tt({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:e?.name??"u32"}),u64:e=>nt({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:e?.name??"u64"}),u128:e=>nt({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:e?.name??"u128"}),u256:e=>nt({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:e?.name??"u256"}),bool:e=>et({size:1,read:e=>1===e.read8(),write:(e,t)=>t.write8(e?1:0),...e,name:e?.name??"bool",validate:t=>{if(e?.validate?.(t),"boolean"!=typeof t)throw new TypeError("Expected boolean, found "+typeof t)}}),uleb128:e=>function({serialize:e,...t}){const n=new Je({...t,serialize:e,write:(e,t)=>{for(const r of n.serialize(e).toBytes())t.write8(r)}});return n}({read:e=>e.readULEB(),serialize:e=>Uint8Array.from($e(e)),...e,name:e?.name??"uleb128"}),bytes:(e,t)=>et({size:e,read:t=>t.readBytes(e),write:(e,t)=>{t.writeBytes(new Uint8Array(e))},...t,name:t?.name??`bytes[${e}]`,validate:n=>{if(t?.validate?.(n),!n||"object"!=typeof n||!("length"in n))throw new TypeError("Expected array, found "+typeof n);if(n.length!==e)throw new TypeError(`Expected array of length ${e}, found ${n.length}`)}}),byteVector:e=>new Je({read:e=>{const t=e.readULEB();return e.readBytes(t)},write:(e,t)=>{const n=new Uint8Array(e);t.writeULEB(n.length),t.writeBytes(n)},...e,name:e?.name??"vector<u8>",serializedSize:e=>{const t="length"in e?e.length:null;return null==t?null:$e(t).length+t},validate:t=>{if(e?.validate?.(t),!t||"object"!=typeof t||!("length"in t))throw new TypeError("Expected array, found "+typeof t)}}),string:e=>function({toBytes:e,fromBytes:t,...n}){return new Je({...n,read:e=>{const n=e.readULEB(),r=e.readBytes(n);return t(r)},write:(t,n)=>{const r=e(t);n.writeULEB(r.length);for(let e=0;e<r.length;e++)n.write8(r[e])},serialize:t=>{const n=e(t),r=$e(n.length),s=new Uint8Array(r.length+n.length);return s.set(r,0),s.set(n,r.length),s},validate:e=>{if("string"!=typeof e)throw new TypeError(`Invalid ${n.name} value: ${e}. Expected string`);n.validate?.(e)}})}({toBytes:e=>(new TextEncoder).encode(e),fromBytes:e=>(new TextDecoder).decode(e),...e,name:e?.name??"string"}),fixedArray:function(e,t,n){return new Je({read:n=>{const r=new Array(e);for(let s=0;s<e;s++)r[s]=t.read(n);return r},write:(e,n)=>{for(const r of e)t.write(r,n)},...n,name:n?.name??`${t.name}[${e}]`,validate:t=>{if(n?.validate?.(t),!t||"object"!=typeof t||!("length"in t))throw new TypeError("Expected array, found "+typeof t);if(t.length!==e)throw new TypeError(`Expected array of length ${e}, found ${t.length}`)}})},option:function(e){return at.enum(`Option<${e.name}>`,{None:null,Some:e}).transform({input:e=>null==e?{None:!0}:{Some:e},output:e=>"Some"===e.$kind?e.Some:null})},vector:function(e,t){return new Je({read:t=>{const n=t.readULEB(),r=new Array(n);for(let s=0;s<n;s++)r[s]=e.read(t);return r},write:(t,n)=>{n.writeULEB(t.length);for(const r of t)e.write(r,n)},...t,name:t?.name??`vector<${e.name}>`,validate:e=>{if(t?.validate?.(e),!e||"object"!=typeof e||!("length"in e))throw new TypeError("Expected array, found "+typeof e)}})},tuple:(e,t)=>new it({fields:e,...t}),struct:(e,t,n)=>new rt({name:e,fields:t,...n}),enum:(e,t,n)=>new st({name:e,fields:t,...n}),map:function(e,t){return at.vector(at.tuple([e,t])).transform({name:`Map<${e.name}, ${t.name}>`,input:e=>[...e.entries()],output:e=>{const t=new Map;for(const[n,r]of e)t.set(n,r);return t}})},lazy:e=>function(e){let t=null;function n(){return t||(t=e()),t}return new Je({name:"lazy",read:e=>n().read(e),serializedSize:e=>n().serializedSize(e),write:(e,t)=>n().write(e,t),serialize:(e,t)=>n().serialize(e,t).toBytes()})}(e)};var ot,ct,ut=e=>{throw TypeError(e)},dt=(e,t,n)=>t.has(e)||ut("Cannot "+n),lt=(e,t,n)=>(dt(e,t,"read from private field"),n?n.call(e):t.get(e)),ht=(e,t,n)=>t.has(e)?ut("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ft=(e,t,n,r)=>(dt(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);ot=new WeakMap,ct=new WeakMap;let pt=class e{constructor({prefix:e,cache:t}={}){ht(this,ot),ht(this,ct),ft(this,ot,e??[]),ft(this,ct,t??new Map)}read(e,t){const n=[lt(this,ot),...e].join(":");if(lt(this,ct).has(n))return lt(this,ct).get(n);const r=t();return lt(this,ct).set(n,r),"object"==typeof r&&null!==r&&"then"in r?Promise.resolve(r).then(e=>(lt(this,ct).set(n,e),e)).catch(e=>{throw lt(this,ct).delete(n),e}):r}readSync(e,t){const n=[lt(this,ot),...e].join(":");if(lt(this,ct).has(n))return lt(this,ct).get(n);const r=t();return lt(this,ct).set(n,r),r}clear(e){const t=[...lt(this,ot),...e??[]].join(":");if(t)for(const e of lt(this,ct).keys())e.startsWith(t)&<(this,ct).delete(e);else lt(this,ct).clear()}scope(t){return new e({prefix:[...lt(this,ot),...Array.isArray(t)?t:[t]],cache:lt(this,ct)})}};class gt{constructor({network:e,base:t,cache:n=t?.cache??new pt}){this.network=e,this.base=t??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(e=>[e.name,{value:e.register(this)}])))}}function mt(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function yt(e,t,n,r,s){const i=s&&"input"in s?s.input:n.value,a=s?.expected??e.expects??null,o=s?.received??mt(i),c={kind:e.kind,type:e.type,input:i,expected:a,received:o,message:`Invalid ${t}: ${a?`Expected ${a} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},u="schema"===e.kind,d=s?.message??e.message??(e.reference,void c.lang)??(u?void c.lang:null)??r.message??void c.lang;d&&(c.message="function"==typeof d?d(c):d),u&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function bt(e,t){return Object.hasOwn(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}var wt=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function vt(e,t){return{kind:"validation",type:"check",reference:vt,async:!1,expects:null,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement(e.value)&&yt(this,"input",e,t),e}}}function Et(e){return{kind:"validation",type:"integer",reference:Et,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(e,t){return e.typed&&!this.requirement(e.value)&&yt(this,"integer",e,t),e}}}function kt(e){return{kind:"transformation",type:"transform",reference:kt,async:!1,operation:e,_run(e){return e.value=this.operation(e.value),e}}}function St(e,t,n){return"function"==typeof e.default?e.default(t,n):e.default}function Ot(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function xt(e,t){return{kind:"schema",type:"array",reference:xt,expects:"Array",async:!1,item:e,message:t,_run(e,t){const n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){const s=n[r],i=this.item._run({typed:!1,value:s},t);if(i.issues){const a={type:"array",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.push(i.value)}}else yt(this,"type",e,t);return e}}}function It(e){return{kind:"schema",type:"bigint",reference:It,expects:"bigint",async:!1,message:e,_run(e,t){return"bigint"==typeof e.value?e.typed=!0:yt(this,"type",e,t),e}}}function Tt(e){return{kind:"schema",type:"boolean",reference:Tt,expects:"boolean",async:!1,message:e,_run(e,t){return"boolean"==typeof e.value?e.typed=!0:yt(this,"type",e,t),e}}}function _t(e){return{kind:"schema",type:"lazy",reference:_t,expects:"unknown",async:!1,getter:e,_run(e,t){return this.getter(e.value)._run(e,t)}}}function At(e,t){return{kind:"schema",type:"literal",reference:At,expects:mt(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:yt(this,"type",e,t),e}}}function Ct(e,...t){const n={kind:"schema",type:"nullable",reference:Ct,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(e,t){return null===e.value&&("default"in this&&(e.value=St(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function jt(e,...t){const n={kind:"schema",type:"nullish",reference:jt,expects:`${e.expects} | null | undefined`,async:!1,wrapped:e,_run(e,t){return null!==e.value&&void 0!==e.value||("default"in this&&(e.value=St(this,e,t)),null!==e.value&&void 0!==e.value)?this.wrapped._run(e,t):(e.typed=!0,e)}};return 0 in t&&(n.default=t[0]),n}function Pt(e){return{kind:"schema",type:"number",reference:Pt,expects:"number",async:!1,message:e,_run(e,t){return"number"!=typeof e.value||isNaN(e.value)?yt(this,"type",e,t):e.typed=!0,e}}}function Bt(e,t){return{kind:"schema",type:"object",reference:Bt,expects:"Object",async:!1,entries:e,message:t,_run(e,t){const n=e.value;if(n&&"object"==typeof n){e.typed=!0,e.value={};for(const r in this.entries){const s=n[r],i=this.entries[r]._run({typed:!1,value:s},t);if(i.issues){const a={type:"object",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),(void 0!==i.value||r in n)&&(e.value[r]=i.value)}}else yt(this,"type",e,t);return e}}}function Nt(e,...t){const n={kind:"schema",type:"optional",reference:Nt,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(e,t){return void 0===e.value&&("default"in this&&(e.value=St(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function Rt(e,t,n){return{kind:"schema",type:"record",reference:Rt,expects:"Object",async:!1,key:e,value:t,message:n,_run(e,t){const n=e.value;if(n&&"object"==typeof n){e.typed=!0,e.value={};for(const r in n)if(bt(n,r)){const s=n[r],i=this.key._run({typed:!1,value:r},t);if(i.issues){const a={type:"object",origin:"key",input:n,key:r,value:s};for(const t of i.issues)t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}const a=this.value._run({typed:!1,value:s},t);if(a.issues){const i={type:"object",origin:"value",input:n,key:r,value:s};for(const t of a.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=a.issues),t.abortEarly){e.typed=!1;break}}i.typed&&a.typed||(e.typed=!1),i.typed&&(e.value[i.value]=a.value)}}else yt(this,"type",e,t);return e}}}function $t(e){return{kind:"schema",type:"string",reference:$t,expects:"string",async:!1,message:e,_run(e,t){return"string"==typeof e.value?e.typed=!0:yt(this,"type",e,t),e}}}function Mt(e,t){return{kind:"schema",type:"tuple",reference:Mt,expects:"Array",async:!1,items:e,message:t,_run(e,t){const n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<this.items.length;r++){const s=n[r],i=this.items[r]._run({typed:!1,value:s},t);if(i.issues){const a={type:"array",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.push(i.value)}}else yt(this,"type",e,t);return e}}}function Ut(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function Dt(e,t){return{kind:"schema",type:"union",reference:Dt,expects:[...new Set(e.map(e=>e.expects))].join(" | ")||"never",async:!1,options:e,message:t,_run(e,t){let n,r,s;for(const i of this.options){const a=i._run({typed:!1,value:e.value},t);if(a.typed){if(!a.issues){n=a;break}r?r.push(a):r=[a]}else s?s.push(a):s=[a]}if(n)return n;if(r){if(1===r.length)return r[0];yt(this,"type",e,t,{issues:Ut(r)}),e.typed=!0}else{if(1===s?.length)return s[0];yt(this,"type",e,t,{issues:Ut(s)})}return e}}}function Ft(){return{kind:"schema",type:"unknown",reference:Ft,expects:"unknown",async:!1,_run:e=>(e.typed=!0,e)}}function Lt(e,t,n){const r=e._run({typed:!1,value:t},function(e){return{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}}(n));if(r.issues)throw new wt(r.issues);return r.value}function Vt(...e){return{...e[0],pipe:e,_run(t,n){for(let r=0;r<e.length;r++){if(t.issues&&("schema"===e[r].kind||"transformation"===e[r].kind)){t.typed=!1;break}t.issues&&(n.abortEarly||n.abortPipeEarly)||(t=e[r]._run(t,n))}return t}}}const Kt=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,zt=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i;const qt=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,Zt=/^\d+$/,Wt=e=>{const t=e.split("/");if(t.length<2||t.length>3)return!1;const[n,r,s]=t;return!(void 0!==s&&!Zt.test(s))&&(!!function(e){return!(e.length>235)&&(e.includes("@")?Kt.test(e):zt.test(e))}(n)&&(qt.test(r)&&r.length<64))},Gt=e=>{const t=e.split(/::|<|>|,/);for(const e of t)if(e.includes("/")&&!Wt(e))return!1;return!0};function Ht(e){try{return 32===Se(e).length}catch{return!1}}const Jt=32;function Yt(e){return function(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2==0}(e)&&function(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}(e)===Jt}function Xt(e){return Yt(e)}function Qt(e){const[t,n]=e.split("::"),r=Wt(t),s=e.slice(t.length+n.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?Ue(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(e=>function(e){return e.includes("::")?Qt(e):e}(e.trim())):[];return{address:r?t:tn(t),module:n,name:i,typeParams:a}}function en(e){const{address:t,module:n,name:r,typeParams:s}="string"==typeof e?Qt(e):e;return`${t}::${n}::${r}${s?.length>0?`<${s.map(e=>"string"==typeof e?e:en(e)).join(",")}>`:""}`}function tn(e,t=!1){let n=e.toLowerCase();return!t&&n.startsWith("0x")&&(n=n.slice(2)),`0x${n.padStart(64,"0")}`}function nn(e,t=!1){return tn(e,t)}function rn(e){return Vt(Dt(Object.entries(e).map(([e,t])=>Bt({[e]:t}))),kt(e=>({...e,$kind:Object.keys(e)[0]})))}const sn=Vt($t(),kt(e=>tn(e)),vt(Yt)),an=sn,on=$t(),cn=Vt(Dt([$t(),Vt(Pt(),Et())]),vt(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),un=Bt({objectId:sn,version:cn,digest:$t()}),dn=Vt(Dt([Bt({GasCoin:At(!0)}),Bt({Input:Vt(Pt(),Et()),type:Nt(At("pure"))}),Bt({Input:Vt(Pt(),Et()),type:Nt(At("object"))}),Bt({Result:Vt(Pt(),Et())}),Bt({NestedResult:Mt([Vt(Pt(),Et()),Vt(Pt(),Et())])})]),kt(e=>({...e,$kind:Object.keys(e)[0]}))),ln=Bt({budget:Ct(cn),price:Ct(cn),owner:Ct(sn),payment:Ct(xt(un))}),hn=Dt([At("address"),At("bool"),At("u8"),At("u16"),At("u32"),At("u64"),At("u128"),At("u256"),Bt({vector:_t(()=>hn)}),Bt({datatype:Bt({package:$t(),module:$t(),type:$t(),typeParameters:xt(_t(()=>hn))})}),Bt({typeParameter:Vt(Pt(),Et())})]),fn=Bt({ref:Ct(Dt([At("&"),At("&mut")])),body:hn}),pn=Bt({package:an,module:$t(),function:$t(),typeArguments:xt($t()),arguments:xt(dn),_argumentTypes:Nt(Ct(xt(fn)))}),gn=Bt({name:$t(),inputs:Rt($t(),Dt([dn,xt(dn)])),data:Rt($t(),Ft())}),mn=rn({MoveCall:pn,TransferObjects:Bt({objects:xt(dn),address:dn}),SplitCoins:Bt({coin:dn,amounts:xt(dn)}),MergeCoins:Bt({destination:dn,sources:xt(dn)}),Publish:Bt({modules:xt(on),dependencies:xt(an)}),MakeMoveVec:Bt({type:Ct($t()),elements:xt(dn)}),Upgrade:Bt({modules:xt(on),dependencies:xt(an),package:an,ticket:dn}),$Intent:gn}),yn=rn({ImmOrOwnedObject:un,SharedObject:Bt({objectId:an,initialSharedVersion:cn,mutable:Tt()}),Receiving:un}),bn=rn({Object:yn,Pure:Bt({bytes:on}),UnresolvedPure:Bt({value:Ft()}),UnresolvedObject:Bt({objectId:an,version:Nt(Ct(cn)),digest:Nt(Ct($t())),initialSharedVersion:Nt(Ct(cn)),mutable:Nt(Ct(Tt()))})}),wn=rn({Object:yn,Pure:Bt({bytes:on})}),vn=rn({None:At(!0),Epoch:cn}),En=Bt({version:At(2),sender:jt(sn),expiration:jt(vn),gasData:ln,inputs:xt(bn),commands:xt(mn)}),kn={MoveCall(e){const[t,n="",r=""]="target"in e?e.target.split("::"):[e.package,e.module,e.function];return{$kind:"MoveCall",MoveCall:{package:t,module:n,function:r,typeArguments:e.typeArguments??[],arguments:e.arguments??[]}}},TransferObjects:(e,t)=>({$kind:"TransferObjects",TransferObjects:{objects:e.map(e=>Lt(dn,e)),address:Lt(dn,t)}}),SplitCoins:(e,t)=>({$kind:"SplitCoins",SplitCoins:{coin:Lt(dn,e),amounts:t.map(e=>Lt(dn,e))}}),MergeCoins:(e,t)=>({$kind:"MergeCoins",MergeCoins:{destination:Lt(dn,e),sources:t.map(e=>Lt(dn,e))}}),Publish:({modules:e,dependencies:t})=>({$kind:"Publish",Publish:{modules:e.map(e=>"string"==typeof e?e:Ie(new Uint8Array(e))),dependencies:t.map(e=>nn(e))}}),Upgrade:({modules:e,dependencies:t,package:n,ticket:r})=>({$kind:"Upgrade",Upgrade:{modules:e.map(e=>"string"==typeof e?e:Ie(new Uint8Array(e))),dependencies:t.map(e=>nn(e)),package:n,ticket:Lt(dn,r)}}),MakeMoveVec:({type:e,elements:t})=>({$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(e=>Lt(dn,e))}}),Intent:({name:e,inputs:t={},data:n={}})=>({$kind:"$Intent",$Intent:{name:e,inputs:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.map(e=>Lt(dn,e)):Lt(dn,t)])),data:n}})},Sn=/^vector<(.+)>$/,On=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class xn{static parseFromStr(e,t=!1){if("address"===e)return{address:null};if("bool"===e)return{bool:null};if("u8"===e)return{u8:null};if("u16"===e)return{u16:null};if("u32"===e)return{u32:null};if("u64"===e)return{u64:null};if("u128"===e)return{u128:null};if("u256"===e)return{u256:null};if("signer"===e)return{signer:null};const n=e.match(Sn);if(n)return{vector:xn.parseFromStr(n[1],t)};const r=e.match(On);if(r){return{struct:{address:t?tn(r[1]):r[1],module:r[2],name:r[3],typeParams:void 0===r[5]?[]:xn.parseStructTypeArgs(r[5],t)}}}throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,t=!1){return Ue(e).map(e=>xn.parseFromStr(e,t))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${xn.tagToString(e.vector)}>`;if("struct"in e){const t=e.struct,n=t.typeParams.map(xn.tagToString).join(", ");return`${t.address}::${t.module}::${t.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}const In=at.bytes(Jt).transform({validate:e=>{const t="string"==typeof e?e:_e(e);if(!t||!Yt(tn(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>"string"==typeof e?Te(tn(e)):e,output:e=>tn(_e(e))}),Tn=at.byteVector().transform({name:"ObjectDigest",input:e=>Se(e),output:e=>ke(new Uint8Array(e)),validate:e=>{if(32!==Se(e).length)throw new Error("ObjectDigest must be 32 bytes")}}),_n=at.struct("SuiObjectRef",{objectId:In,version:at.u64(),digest:Tn}),An=at.struct("SharedObjectRef",{objectId:In,initialSharedVersion:at.u64(),mutable:at.bool()}),Cn=at.enum("ObjectArg",{ImmOrOwnedObject:_n,SharedObject:An,Receiving:_n}),jn=at.enum("Owner",{AddressOwner:In,ObjectOwner:In,Shared:at.struct("Shared",{initialSharedVersion:at.u64()}),Immutable:null,ConsensusAddressOwner:at.struct("ConsensusAddressOwner",{owner:In,startVersion:at.u64()})}),Pn=at.enum("CallArg",{Pure:at.struct("Pure",{bytes:at.byteVector().transform({input:e=>"string"==typeof e?Oe(e):e,output:e=>Ie(new Uint8Array(e))})}),Object:Cn}),Bn=at.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:at.lazy(()=>Bn),struct:at.lazy(()=>Kn),u16:null,u32:null,u256:null}),Nn=Bn.transform({input:e=>"string"==typeof e?xn.parseFromStr(e,!0):e,output:e=>xn.tagToString(e)}),Rn=at.enum("Argument",{GasCoin:null,Input:at.u16(),Result:at.u16(),NestedResult:at.tuple([at.u16(),at.u16()])}),$n=at.struct("ProgrammableMoveCall",{package:In,module:at.string(),function:at.string(),typeArguments:at.vector(Nn),arguments:at.vector(Rn)}),Mn=at.enum("Command",{MoveCall:$n,TransferObjects:at.struct("TransferObjects",{objects:at.vector(Rn),address:Rn}),SplitCoins:at.struct("SplitCoins",{coin:Rn,amounts:at.vector(Rn)}),MergeCoins:at.struct("MergeCoins",{destination:Rn,sources:at.vector(Rn)}),Publish:at.struct("Publish",{modules:at.vector(at.byteVector().transform({input:e=>"string"==typeof e?Oe(e):e,output:e=>Ie(new Uint8Array(e))})),dependencies:at.vector(In)}),MakeMoveVec:at.struct("MakeMoveVec",{type:(Un=Nn,at.enum("Option",{None:null,Some:Un})).transform({input:e=>null===e?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:at.vector(Rn)}),Upgrade:at.struct("Upgrade",{modules:at.vector(at.byteVector().transform({input:e=>"string"==typeof e?Oe(e):e,output:e=>Ie(new Uint8Array(e))})),dependencies:at.vector(In),package:In,ticket:Rn})});var Un;const Dn=at.struct("ProgrammableTransaction",{inputs:at.vector(Pn),commands:at.vector(Mn)}),Fn=at.enum("TransactionKind",{ProgrammableTransaction:Dn,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),Ln=at.enum("TransactionExpiration",{None:null,Epoch:at.u64({name:"unsafe_u64",...Vn}).transform({input:e=>e,output:e=>Number(e)})});var Vn;const Kn=at.struct("StructTag",{address:In,module:at.string(),name:at.string(),typeParams:at.vector(Bn)}),zn=at.struct("GasData",{payment:at.vector(_n),owner:In,price:at.u64(),budget:at.u64()}),qn=at.struct("TransactionDataV1",{kind:Fn,sender:In,gasData:zn,expiration:Ln}),Zn=at.enum("TransactionData",{V1:qn}),Wn=at.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Gn=at.enum("IntentVersion",{V0:null}),Hn=at.enum("AppId",{Sui:null}),Jn=at.struct("Intent",{scope:Wn,version:Gn,appId:Hn});function Yn(e){return at.struct(`IntentMessage<${e.name}>`,{intent:Jn,value:e})}const Xn=at.enum("CompressedSignature",{ED25519:at.bytes(64),Secp256k1:at.bytes(64),Secp256r1:at.bytes(64),ZkLogin:at.byteVector(),Passkey:at.byteVector()}),Qn=at.enum("PublicKey",{ED25519:at.bytes(32),Secp256k1:at.bytes(33),Secp256r1:at.bytes(33),ZkLogin:at.byteVector(),Passkey:at.bytes(33)}),er=at.struct("MultiSigPkMap",{pubKey:Qn,weight:at.u8()}),tr=at.struct("MultiSigPublicKey",{pk_map:at.vector(er),threshold:at.u16()}),nr=at.struct("MultiSig",{sigs:at.vector(Xn),bitmap:at.u16(),multisig_pk:tr}),rr=at.byteVector().transform({input:e=>"string"==typeof e?Oe(e):e,output:e=>Ie(new Uint8Array(e))}),sr=at.struct("SenderSignedTransaction",{intentMessage:Yn(Zn),txSignatures:at.vector(rr)}),ir=at.vector(sr,{name:"SenderSignedData"}),ar=at.struct("PasskeyAuthenticator",{authenticatorData:at.byteVector(),clientDataJson:at.string(),userSignature:at.byteVector()}),or=at.enum("PackageUpgradeError",{UnableToFetchPackage:at.struct("UnableToFetchPackage",{packageId:In}),NotAPackage:at.struct("NotAPackage",{objectId:In}),IncompatibleUpgrade:null,DigestDoesNotMatch:at.struct("DigestDoesNotMatch",{digest:at.byteVector()}),UnknownUpgradePolicy:at.struct("UnknownUpgradePolicy",{policy:at.u8()}),PackageIDDoesNotMatch:at.struct("PackageIDDoesNotMatch",{packageId:In,ticketId:In})}),cr=at.struct("ModuleId",{address:In,name:at.string()}),ur=at.struct("MoveLocation",{module:cr,function:at.u16(),instruction:at.u16(),functionName:at.option(at.string())}),dr=at.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:at.struct("IndexOutOfBounds",{idx:at.u16()}),SecondaryIndexOutOfBounds:at.struct("SecondaryIndexOutOfBounds",{resultIdx:at.u16(),secondaryIdx:at.u16()}),InvalidResultArity:at.struct("InvalidResultArity",{resultIdx:at.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),lr=at.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),hr=at.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:at.struct("MoveObjectTooBig",{objectSize:at.u64(),maxObjectSize:at.u64()}),MovePackageTooBig:at.struct("MovePackageTooBig",{objectSize:at.u64(),maxObjectSize:at.u64()}),CircularObjectOwnership:at.struct("CircularObjectOwnership",{object:In}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:at.option(ur),MoveAbort:at.tuple([ur,at.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:at.struct("CommandArgumentError",{argIdx:at.u16(),kind:dr}),TypeArgumentError:at.struct("TypeArgumentError",{argumentIdx:at.u16(),kind:lr}),UnusedValueWithoutDrop:at.struct("UnusedValueWithoutDrop",{resultIdx:at.u16(),secondaryIdx:at.u16()}),InvalidPublicFunctionReturnType:at.struct("InvalidPublicFunctionReturnType",{idx:at.u16()}),InvalidTransferObject:null,EffectsTooLarge:at.struct("EffectsTooLarge",{currentSize:at.u64(),maxSize:at.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:at.struct("PackageUpgradeError",{upgradeError:or}),WrittenObjectsTooLarge:at.struct("WrittenObjectsTooLarge",{currentSize:at.u64(),maxSize:at.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:at.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:at.vector(In)}),AddressDeniedForCoin:at.struct("AddressDeniedForCoin",{address:In,coinType:at.string()}),CoinTypeGlobalPause:at.struct("CoinTypeGlobalPause",{coinType:at.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),fr=at.enum("ExecutionStatus",{Success:null,Failed:at.struct("ExecutionFailed",{error:hr,command:at.option(at.u64())})}),pr=at.struct("GasCostSummary",{computationCost:at.u64(),storageCost:at.u64(),storageRebate:at.u64(),nonRefundableStorageFee:at.u64()}),gr=at.struct("TransactionEffectsV1",{status:fr,executedEpoch:at.u64(),gasUsed:pr,modifiedAtVersions:at.vector(at.tuple([In,at.u64()])),sharedObjects:at.vector(_n),transactionDigest:Tn,created:at.vector(at.tuple([_n,jn])),mutated:at.vector(at.tuple([_n,jn])),unwrapped:at.vector(at.tuple([_n,jn])),deleted:at.vector(_n),unwrappedThenDeleted:at.vector(_n),wrapped:at.vector(_n),gasObject:at.tuple([_n,jn]),eventsDigest:at.option(Tn),dependencies:at.vector(Tn)}),mr=at.tuple([at.u64(),Tn]),yr=at.enum("ObjectIn",{NotExist:null,Exist:at.tuple([mr,jn])}),br=at.enum("ObjectOut",{NotExist:null,ObjectWrite:at.tuple([Tn,jn]),PackageWrite:mr}),wr=at.enum("IDOperation",{None:null,Created:null,Deleted:null}),vr=at.struct("EffectsObjectChange",{inputState:yr,outputState:br,idOperation:wr}),Er=at.enum("UnchangedSharedKind",{ReadOnlyRoot:mr,MutateDeleted:at.u64(),ReadDeleted:at.u64(),Cancelled:at.u64(),PerEpochConfig:null}),kr=at.struct("TransactionEffectsV2",{status:fr,executedEpoch:at.u64(),gasUsed:pr,transactionDigest:Tn,gasObjectIndex:at.option(at.u32()),eventsDigest:at.option(Tn),dependencies:at.vector(Tn),lamportVersion:at.u64(),changedObjects:at.vector(at.tuple([In,vr])),unchangedSharedObjects:at.vector(at.tuple([In,Er])),auxDataDigest:at.option(Tn)}),Sr=at.enum("TransactionEffects",{V1:gr,V2:kr});function Or(e){switch(e){case"u8":return at.u8();case"u16":return at.u16();case"u32":return at.u32();case"u64":return at.u64();case"u128":return at.u128();case"u256":return at.u256();case"bool":return at.bool();case"string":return at.string();case"id":case"address":return In}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[e,n]=t.slice(1);return"vector"===e?at.vector(Or(n)):at.option(Or(n))}throw new Error(`Invalid Pure type name: ${e}`)}const xr={...at,U8:at.u8(),U16:at.u16(),U32:at.u32(),U64:at.u64(),U128:at.u128(),U256:at.u256(),ULEB128:at.uleb128(),Bool:at.bool(),String:at.string(),Address:In,AppId:Hn,Argument:Rn,CallArg:Pn,Command:Mn,CompressedSignature:Xn,GasData:zn,Intent:Jn,IntentMessage:Yn,IntentScope:Wn,IntentVersion:Gn,MultiSig:nr,MultiSigPkMap:er,MultiSigPublicKey:tr,ObjectArg:Cn,ObjectDigest:Tn,Owner:jn,PasskeyAuthenticator:ar,ProgrammableMoveCall:$n,ProgrammableTransaction:Dn,PublicKey:Qn,SenderSignedData:ir,SenderSignedTransaction:sr,SharedObjectRef:An,StructTag:Kn,SuiObjectRef:_n,TransactionData:Zn,TransactionDataV1:qn,TransactionEffects:Sr,TransactionExpiration:Ln,TransactionKind:Fn,TypeTag:Nn},Ir=Bt({digest:$t(),objectId:$t(),version:Dt([Vt(Pt(),Et()),$t(),It()])}),Tr=rn({ImmOrOwned:Ir,Shared:Bt({objectId:an,initialSharedVersion:cn,mutable:Tt()}),Receiving:Ir}),_r=rn({Object:Tr,Pure:xt(Vt(Pt(),Et()))}),Ar=Dt([Bt({kind:At("Input"),index:Vt(Pt(),Et()),value:Ft(),type:Nt(At("object"))}),Bt({kind:At("Input"),index:Vt(Pt(),Et()),value:Ft(),type:At("pure")})]),Cr=Dt([Bt({Epoch:Vt(Pt(),Et())}),Bt({None:Ct(At(!0))})]),jr=Vt(Dt([Pt(),$t(),It()]),vt(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),Pr=Dt([Bt({bool:Ct(At(!0))}),Bt({u8:Ct(At(!0))}),Bt({u64:Ct(At(!0))}),Bt({u128:Ct(At(!0))}),Bt({address:Ct(At(!0))}),Bt({signer:Ct(At(!0))}),Bt({vector:_t(()=>Pr)}),Bt({struct:_t(()=>Br)}),Bt({u16:Ct(At(!0))}),Bt({u32:Ct(At(!0))}),Bt({u256:Ct(At(!0))})]),Br=Bt({address:$t(),module:$t(),name:$t(),typeParams:xt(Pr)}),Nr=Bt({budget:Nt(jr),price:Nt(jr),payment:Nt(xt(Ir)),owner:Nt($t())}),Rr=Dt([...[Ar,Bt({kind:At("GasCoin")}),Bt({kind:At("Result"),index:Vt(Pt(),Et())}),Bt({kind:At("NestedResult"),index:Vt(Pt(),Et()),resultIndex:Vt(Pt(),Et())})]]),$r=Bt({kind:At("MoveCall"),target:Vt($t(),vt(e=>3===e.split("::").length)),typeArguments:xt($t()),arguments:xt(Rr)}),Mr=Bt({kind:At("TransferObjects"),objects:xt(Rr),address:Rr}),Ur=Bt({kind:At("SplitCoins"),coin:Rr,amounts:xt(Rr)}),Dr=Bt({kind:At("MergeCoins"),destination:Rr,sources:xt(Rr)}),Fr=Bt({kind:At("MakeMoveVec"),type:Dt([Bt({Some:Pr}),Bt({None:Ct(At(!0))})]),objects:xt(Rr)}),Lr=Dt([...[$r,Mr,Ur,Dr,Bt({kind:At("Publish"),modules:xt(xt(Vt(Pt(),Et()))),dependencies:xt($t())}),Bt({kind:At("Upgrade"),modules:xt(xt(Vt(Pt(),Et()))),dependencies:xt($t()),packageId:$t(),ticket:Rr}),Fr]]);function Vr(e){const t=e.inputs.map((e,t)=>{if(e.Object)return{kind:"Input",index:t,value:{Object:e.Object.ImmOrOwnedObject?{ImmOrOwned:e.Object.ImmOrOwnedObject}:e.Object.Receiving?{Receiving:{digest:e.Object.Receiving.digest,version:e.Object.Receiving.version,objectId:e.Object.Receiving.objectId}}:{Shared:{mutable:e.Object.SharedObject.mutable,initialSharedVersion:e.Object.SharedObject.initialSharedVersion,objectId:e.Object.SharedObject.objectId}}},type:"object"};if(e.Pure)return{kind:"Input",index:t,value:{Pure:Array.from(Oe(e.Pure.bytes))},type:"pure"};if(e.UnresolvedPure)return{kind:"Input",type:"pure",index:t,value:e.UnresolvedPure.value};if(e.UnresolvedObject)return{kind:"Input",type:"object",index:t,value:e.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:e.sender??void 0,expiration:"Epoch"===e.expiration?.$kind?{Epoch:Number(e.expiration.Epoch)}:e.expiration?{None:!0}:null,gasConfig:{owner:e.gasData.owner??void 0,budget:e.gasData.budget??void 0,price:e.gasData.price??void 0,payment:e.gasData.payment??void 0},inputs:t,transactions:e.commands.map(e=>{if(e.MakeMoveVec)return{kind:"MakeMoveVec",type:null===e.MakeMoveVec.type?{None:!0}:{Some:xn.parseFromStr(e.MakeMoveVec.type)},objects:e.MakeMoveVec.elements.map(e=>Kr(e,t))};if(e.MergeCoins)return{kind:"MergeCoins",destination:Kr(e.MergeCoins.destination,t),sources:e.MergeCoins.sources.map(e=>Kr(e,t))};if(e.MoveCall)return{kind:"MoveCall",target:`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`,typeArguments:e.MoveCall.typeArguments,arguments:e.MoveCall.arguments.map(e=>Kr(e,t))};if(e.Publish)return{kind:"Publish",modules:e.Publish.modules.map(e=>Array.from(Oe(e))),dependencies:e.Publish.dependencies};if(e.SplitCoins)return{kind:"SplitCoins",coin:Kr(e.SplitCoins.coin,t),amounts:e.SplitCoins.amounts.map(e=>Kr(e,t))};if(e.TransferObjects)return{kind:"TransferObjects",objects:e.TransferObjects.objects.map(e=>Kr(e,t)),address:Kr(e.TransferObjects.address,t)};if(e.Upgrade)return{kind:"Upgrade",modules:e.Upgrade.modules.map(e=>Array.from(Oe(e))),dependencies:e.Upgrade.dependencies,packageId:e.Upgrade.package,ticket:Kr(e.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(e)}`)})}}function Kr(e,t){if("GasCoin"===e.$kind)return{kind:"GasCoin"};if("Result"===e.$kind)return{kind:"Result",index:e.Result};if("NestedResult"===e.$kind)return{kind:"NestedResult",index:e.NestedResult[0],resultIndex:e.NestedResult[1]};if("Input"===e.$kind)return t[e.Input];throw new Error(`Invalid argument ${Object.keys(e)}`)}function zr(e){switch(e.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:e.index};case"NestedResult":return{NestedResult:[e.index,e.resultIndex]};case"Input":return{Input:e.index}}}function qr(e){return Dt(Object.entries(e).map(([e,t])=>Bt({[e]:t})))}Bt({version:At(1),sender:Nt($t()),expiration:jt(Cr),gasConfig:Nr,inputs:xt(Ar),transactions:xt(Lr)});const Zr=qr({GasCoin:At(!0),Input:Vt(Pt(),Et()),Result:Vt(Pt(),Et()),NestedResult:Mt([Vt(Pt(),Et()),Vt(Pt(),Et())])}),Wr=Bt({budget:Ct(cn),price:Ct(cn),owner:Ct(sn),payment:Ct(xt(un))}),Gr=Bt({package:an,module:$t(),function:$t(),typeArguments:xt($t()),arguments:xt(Zr)}),Hr=Bt({name:$t(),inputs:Rt($t(),Dt([Zr,xt(Zr)])),data:Rt($t(),Ft())}),Jr=qr({MoveCall:Gr,TransferObjects:Bt({objects:xt(Zr),address:Zr}),SplitCoins:Bt({coin:Zr,amounts:xt(Zr)}),MergeCoins:Bt({destination:Zr,sources:xt(Zr)}),Publish:Bt({modules:xt(on),dependencies:xt(an)}),MakeMoveVec:Bt({type:Ct($t()),elements:xt(Zr)}),Upgrade:Bt({modules:xt(on),dependencies:xt(an),package:an,ticket:Zr}),$Intent:Hr}),Yr=qr({ImmOrOwnedObject:un,SharedObject:Bt({objectId:an,initialSharedVersion:cn,mutable:Tt()}),Receiving:un}),Xr=qr({Object:Yr,Pure:Bt({bytes:on}),UnresolvedPure:Bt({value:Ft()}),UnresolvedObject:Bt({objectId:an,version:Nt(Ct(cn)),digest:Nt(Ct($t())),initialSharedVersion:Nt(Ct(cn)),mutable:Nt(Ct(Tt()))})}),Qr=qr({None:At(!0),Epoch:cn}),es=Bt({version:At(2),sender:jt(sn),expiration:jt(Qr),gasData:Wr,inputs:xt(Xr),commands:xt(Jr),digest:Nt(Ct($t()))});const ts={Pure:function(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?Ie(e):e.toBase64()}}},ObjectRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:t,version:n,objectId:tn(e)}}}),SharedObjectRef:({objectId:e,mutable:t,initialSharedVersion:n})=>({$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:t,initialSharedVersion:n,objectId:tn(e)}}}),ReceivingRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:t,version:n,objectId:tn(e)}}})};BigInt(1e9);const ns=nn("0x6"),rs="0x2::sui::SUI";nn("0x5"),nn("0x8");const ss="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function is(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function as(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function os(e,...t){if(!is(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function cs(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");as(e.outputLen),as(e.blockLen)}function us(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ds(e,t){os(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ls(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function hs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function fs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ps(e,t){return e<<32-t|e>>>t}function gs(e,t){return e<<t|e>>>32-t>>>0}const ms=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function ys(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const bs=ms?e=>e:e=>ys(e);const ws=ms?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=ys(e[t]);return e},vs=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Es=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ks(e){if(os(e),vs)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Es[e[n]];return t}const Ss=48,Os=57,xs=65,Is=70,Ts=97,_s=102;function As(e){return e>=Ss&&e<=Os?e-Ss:e>=xs&&e<=Is?e-(xs-10):e>=Ts&&e<=_s?e-(Ts-10):void 0}function Cs(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(vs)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=As(e.charCodeAt(s)),i=As(e.charCodeAt(s+1));if(void 0===n||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+i}return r}function js(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Ps(e){return"string"==typeof e&&(e=js(e)),os(e),e}function Bs(e){return"string"==typeof e&&(e=js(e)),os(e),e}function Ns(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];os(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}class Rs{}function $s(e){const t=t=>e().update(Ps(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ms(e){const t=(t,n)=>e(n).update(Ps(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}function Us(e=32){if(ss&&"function"==typeof ss.getRandomValues)return ss.getRandomValues(new Uint8Array(e));if(ss&&"function"==typeof ss.randomBytes)return Uint8Array.from(ss.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Ds=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]);function Fs(e,t,n){return e&t^~e&n}function Ls(e,t,n){return e&t^e&n^t&n}class Vs extends Rs{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=fs(this.buffer)}update(e){us(this),os(e=Ps(e));const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(r-this.pos,s-i);if(a===r){const t=fs(e);for(;r<=s-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){us(this),ds(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,hs(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const s=BigInt(32),i=BigInt(4294967295),a=Number(n>>s&i),o=Number(n&i),c=r?4:0,u=r?0:4;e.setUint32(t+c,a,r),e.setUint32(t+u,o,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const a=fs(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)a.setUint32(4*e,u[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=a,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ks=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zs=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),qs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Zs=BigInt(2**32-1),Ws=BigInt(32);function Gs(e,t=!1){return t?{h:Number(e&Zs),l:Number(e>>Ws&Zs)}:{h:0|Number(e>>Ws&Zs),l:0|Number(e&Zs)}}const Hs=(e,t,n)=>e>>>n,Js=(e,t,n)=>e<<32-n|t>>>n,Ys=(e,t,n)=>e>>>n|t<<32-n,Xs=(e,t,n)=>e<<32-n|t>>>n,Qs=(e,t,n)=>e<<64-n|t>>>n-32,ei=(e,t,n)=>e>>>n-32|t<<64-n,ti=(e,t)=>t;function ni(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const ri=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),si=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,ii=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ai=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,oi=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),ci=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,ui=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),di=new Uint32Array(32);function li(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=di[2*e],u=di[2*e+1],d=di[2*t],l=di[2*t+1],h=di[2*n],f=di[2*n+1],p=di[2*r],g=di[2*r+1],m=ri(c,d,a);var y;u=si(m,u,l,o),c=0|m,({Dh:g,Dl:p}={Dh:g^u,Dl:p^c}),({Dh:g,Dl:p}={Dh:ti(0,p),Dl:(y=g,y)}),({h:f,l:h}=ni(f,h,g,p)),({Bh:l,Bl:d}={Bh:l^f,Bl:d^h}),({Bh:l,Bl:d}={Bh:Ys(l,d,24),Bl:Xs(l,d,24)}),di[2*e]=c,di[2*e+1]=u,di[2*t]=d,di[2*t+1]=l,di[2*n]=h,di[2*n+1]=f,di[2*r]=p,di[2*r+1]=g}function hi(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=di[2*e],u=di[2*e+1],d=di[2*t],l=di[2*t+1],h=di[2*n],f=di[2*n+1],p=di[2*r],g=di[2*r+1],m=ri(c,d,a);u=si(m,u,l,o),c=0|m,({Dh:g,Dl:p}={Dh:g^u,Dl:p^c}),({Dh:g,Dl:p}={Dh:Ys(g,p,16),Dl:Xs(g,p,16)}),({h:f,l:h}=ni(f,h,g,p)),({Bh:l,Bl:d}={Bh:l^f,Bl:d^h}),({Bh:l,Bl:d}={Bh:Qs(l,d,63),Bl:ei(l,d,63)}),di[2*e]=c,di[2*e+1]=u,di[2*t]=d,di[2*t+1]=l,di[2*n]=h,di[2*n+1]=f,di[2*r]=p,di[2*r+1]=g}class fi extends Rs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,as(e),as(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ls(this.buffer)}update(e){us(this),os(e=Ps(e));const{blockLen:t,buffer:n,buffer32:r}=this,s=e.length,i=e.byteOffset,a=e.buffer;for(let o=0;o<s;){this.pos===t&&(ws(r),this.compress(r,0,!1),ws(r),this.pos=0);const c=Math.min(t-this.pos,s-o),u=i+o;if(c===t&&!(u%4)&&o+c<s){const e=new Uint32Array(a,u,Math.floor((s-o)/4));ws(e);for(let n=0;o+t<s;n+=r.length,o+=t)this.length+=t,this.compress(e,n,!1);ws(e);continue}n.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c}return this}digestInto(e){us(this),ds(e,this);const{pos:t,buffer32:n}=this;this.finished=!0,hs(this.buffer.subarray(t)),ws(n),this.compress(n,0,!0),ws(n);const r=ls(e);this.get().forEach((e,t)=>r[t]=bs(e))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){const{buffer:t,length:n,finished:r,destroyed:s,outputLen:i,pos:a}=this;return e||(e=new this.constructor({dkLen:i})),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=r,e.length=n,e.pos=a,e.outputLen=i,e}clone(){return this._cloneInto()}}class pi extends fi{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|ui[0],this.v0h=0|ui[1],this.v1l=0|ui[2],this.v1h=0|ui[3],this.v2l=0|ui[4],this.v2h=0|ui[5],this.v3l=0|ui[6],this.v3h=0|ui[7],this.v4l=0|ui[8],this.v4h=0|ui[9],this.v5l=0|ui[10],this.v5h=0|ui[11],this.v6l=0|ui[12],this.v6h=0|ui[13],this.v7l=0|ui[14],this.v7h=0|ui[15],function(e,t={},n,r,s){if(as(n),e<0||e>n)throw new Error("outputLen bigger than keyLen");const{key:i,salt:a,personalization:o}=t;if(void 0!==i&&(i.length<1||i.length>n))throw new Error("key length must be undefined or 1.."+n);if(void 0!==a&&a.length!==r)throw new Error("salt must be undefined or "+r);if(void 0!==o&&o.length!==s)throw new Error("personalization must be undefined or "+s)}(t,e,64,16,16);let{key:n,personalization:r,salt:s}=e,i=0;if(void 0!==n&&(n=Ps(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==s){s=Ps(s);const e=ls(s);this.v4l^=bs(e[0]),this.v4h^=bs(e[1]),this.v5l^=bs(e[2]),this.v5h^=bs(e[3])}if(void 0!==r){r=Ps(r);const e=ls(r);this.v6l^=bs(e[0]),this.v6h^=bs(e[1]),this.v7l^=bs(e[2]),this.v7h^=bs(e[3])}if(void 0!==n){const e=new Uint8Array(this.blockLen);e.set(n),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:n,v1h:r,v2l:s,v2h:i,v3l:a,v3h:o,v4l:c,v4h:u,v5l:d,v5h:l,v6l:h,v6h:f,v7l:p,v7h:g}=this;return[e,t,n,r,s,i,a,o,c,u,d,l,h,f,p,g]}set(e,t,n,r,s,i,a,o,c,u,d,l,h,f,p,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|n,this.v1h=0|r,this.v2l=0|s,this.v2h=0|i,this.v3l=0|a,this.v3h=0|o,this.v4l=0|c,this.v4h=0|u,this.v5l=0|d,this.v5h=0|l,this.v6l=0|h,this.v6h=0|f,this.v7l=0|p,this.v7h=0|g}compress(e,t,n){this.get().forEach((e,t)=>di[t]=e),di.set(ui,16);let{h:r,l:s}=Gs(BigInt(this.length));di[24]=ui[8]^s,di[25]=ui[9]^r,n&&(di[28]=~di[28],di[29]=~di[29]);let i=0;const a=Ds;for(let n=0;n<12;n++)li(0,4,8,12,e,t+2*a[i++]),hi(0,4,8,12,e,t+2*a[i++]),li(1,5,9,13,e,t+2*a[i++]),hi(1,5,9,13,e,t+2*a[i++]),li(2,6,10,14,e,t+2*a[i++]),hi(2,6,10,14,e,t+2*a[i++]),li(3,7,11,15,e,t+2*a[i++]),hi(3,7,11,15,e,t+2*a[i++]),li(0,5,10,15,e,t+2*a[i++]),hi(0,5,10,15,e,t+2*a[i++]),li(1,6,11,12,e,t+2*a[i++]),hi(1,6,11,12,e,t+2*a[i++]),li(2,7,8,13,e,t+2*a[i++]),hi(2,7,8,13,e,t+2*a[i++]),li(3,4,9,14,e,t+2*a[i++]),hi(3,4,9,14,e,t+2*a[i++]);this.v0l^=di[0]^di[16],this.v0h^=di[1]^di[17],this.v1l^=di[2]^di[18],this.v1h^=di[3]^di[19],this.v2l^=di[4]^di[20],this.v2h^=di[5]^di[21],this.v3l^=di[6]^di[22],this.v3h^=di[7]^di[23],this.v4l^=di[8]^di[24],this.v4h^=di[9]^di[25],this.v5l^=di[10]^di[26],this.v5h^=di[11]^di[27],this.v6l^=di[12]^di[28],this.v6h^=di[13]^di[29],this.v7l^=di[14]^di[30],this.v7h^=di[15]^di[31],hs(di)}destroy(){this.destroyed=!0,hs(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const gi=Ms(e=>new pi(e));function mi(e,t,n){const r=xr.Address.serialize(e).toBytes(),s=xr.TypeTag.serialize(t).toBytes(),i=xr.u64().serialize(n.length).toBytes(),a=gi.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(r),a.update(i),a.update(n),a.update(s),`0x${_e(a.digest().slice(0,32))}`}function yi(e){if("string"==typeof e)switch(e){case"address":return xr.Address;case"bool":return xr.Bool;case"u8":return xr.U8;case"u16":return xr.U16;case"u32":return xr.U32;case"u64":return xr.U64;case"u128":return xr.U128;case"u256":return xr.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if("u8"===e.vector)return xr.byteVector().transform({input:e=>"string"==typeof e?(new TextEncoder).encode(e):e,output:e=>e});const t=yi(e.vector);return t?xr.vector(t):null}if("datatype"in e){const t=tn(e.datatype.package);if(t===tn("0x1")){if("ascii"===e.datatype.module&&"String"===e.datatype.type)return xr.String;if("string"===e.datatype.module&&"String"===e.datatype.type)return xr.String;if("option"===e.datatype.module&&"Option"===e.datatype.type){const t=yi(e.datatype.typeParameters[0]);return t?xr.vector(t):null}}if(t===tn("0x2")&&"object"===e.datatype.module&&"ID"===e.datatype.type)return xr.Address}return null}function bi(e){if("string"==typeof e)switch(e){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${e}`)}if("Vector"in e)return{vector:bi(e.Vector)};if("Struct"in e)return{datatype:{package:e.Struct.address,module:e.Struct.module,type:e.Struct.name,typeParameters:e.Struct.typeArguments.map(bi)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const wi=5e10;function vi(e){return async function(t,n,r){return await async function(e,t){const{inputs:n,commands:r}=e,s=[],i=new Set;r.forEach(t=>{if(t.MoveCall){if(t.MoveCall._argumentTypes)return;if(t.MoveCall.arguments.map(t=>"Input"===t.$kind?e.inputs[t.Input]:null).some(e=>e?.UnresolvedPure||e?.UnresolvedObject&&"boolean"!=typeof e?.UnresolvedObject.mutable)){const e=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;i.add(e),s.push(t.MoveCall)}}});const a=new Map;i.size>0&&await Promise.all([...i].map(async e=>{const[n,r,s]=e.split("::"),i=await t.getNormalizedMoveFunction({package:n,module:r,function:s});a.set(e,i.parameters.map(e=>function(e){return"object"==typeof e&&"Reference"in e?{ref:"&",body:bi(e.Reference)}:"object"==typeof e&&"MutableReference"in e?{ref:"&mut",body:bi(e.MutableReference)}:{ref:null,body:bi(e)}}(e)))}));s.length&&await Promise.all(s.map(async e=>{const t=a.get(`${e.package}::${e.module}::${e.function}`);if(!t)return;const n=t.length>0&&function(e){const t="object"==typeof e.body&&"datatype"in e.body?e.body.datatype:null;return!!t&&tn(t.package)===tn("0x2")&&"tx_context"===t.module&&"TxContext"===t.type}(t.at(-1))?t.slice(0,t.length-1):t;e._argumentTypes=n}));r.forEach(e=>{if(!e.MoveCall)return;const t=e.MoveCall,r=`${t.package}::${t.module}::${t.function}`,s=t._argumentTypes;if(s){if(s.length!==e.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${r}`);s.forEach((e,r)=>{const s=t.arguments[r];if("Input"!==s.$kind)return;const i=n[s.Input];if(!i.UnresolvedPure&&!i.UnresolvedObject)return;const a=i.UnresolvedPure?.value??i.UnresolvedObject?.objectId,o=yi(e.body);if(o)return s.type="pure",void(n[n.indexOf(i)]=ts.Pure(o.serialize(a)));if("string"!=typeof a)throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(a,null,2)}`);s.type="object";const c=i.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:a}}:i;n[s.Input]=c})}})}(t,e),await async function(e,t){const n=e.inputs.filter(e=>e.UnresolvedObject&&!(e.UnresolvedObject.version||e.UnresolvedObject?.initialSharedVersion)),r=[...new Set(n.map(e=>nn(e.UnresolvedObject.objectId)))],s=r.length?Ae(r,50):[],i=(await Promise.all(s.map(e=>t.multiGetObjects({ids:e,options:{showOwner:!0}})))).flat(),a=new Map(r.map((e,t)=>[e,i[t]])),o=Array.from(a).filter(([e,t])=>t.error).map(([e,t])=>JSON.stringify(t.error));if(o.length)throw new Error(`The following input objects are invalid: ${o.join(", ")}`);const c=i.map(e=>{if(e.error||!e.data)throw new Error(`Failed to fetch object: ${e.error}`);const t=e.data.owner,n=t&&"object"==typeof t?"Shared"in t?t.Shared.initial_shared_version:"ConsensusAddressOwner"in t?t.ConsensusAddressOwner.start_version:null:null;return{objectId:e.data.objectId,digest:e.data.digest,version:e.data.version,initialSharedVersion:n}}),u=new Map(r.map((e,t)=>[e,c[t]]));for(const[t,n]of e.inputs.entries()){if(!n.UnresolvedObject)continue;let r;const s=tn(n.UnresolvedObject.objectId),i=u.get(s);n.UnresolvedObject.initialSharedVersion??i?.initialSharedVersion?r=ts.SharedObjectRef({objectId:s,initialSharedVersion:n.UnresolvedObject.initialSharedVersion||i?.initialSharedVersion,mutable:n.UnresolvedObject.mutable||Ei(e,t)}):ki(e,t)&&(r=ts.ReceivingRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})),e.inputs[e.inputs.indexOf(n)]=r??ts.ObjectRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})}}(t,e),n.onlyTransactionKind||(await async function(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}(t,e),await async function(e,t){if(e.gasConfig.budget)return;const n=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(wi),payment:[]}}})});if("success"!==n.effects.status.status)throw new Error(`Dry run failed, could not automatically determine a budget: ${n.effects.status.error}`,{cause:n});const r=1000n*BigInt(e.gasConfig.price||1n),s=BigInt(n.effects.gasUsed.computationCost)+r,i=s+BigInt(n.effects.gasUsed.storageCost)-BigInt(n.effects.gasUsed.storageRebate);e.gasConfig.budget=String(i>s?i:s)}(t,e),await async function(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:rs})).data.filter(t=>!e.inputs.find(e=>!!e.Object?.ImmOrOwnedObject&&t.coinObjectId===e.Object.ImmOrOwnedObject.objectId)).map(e=>({objectId:e.coinObjectId,digest:e.digest,version:e.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");e.gasConfig.payment=n.map(e=>Lt(un,e))}}(t,e)),await r()}}function Ei(e,t){let n=!1;return e.getInputUses(t,(e,t)=>{if(t.MoveCall&&t.MoveCall._argumentTypes){const r=t.MoveCall.arguments.indexOf(e);n="&"!==t.MoveCall._argumentTypes[r].ref||n}"MakeMoveVec"!==t.$kind&&"MergeCoins"!==t.$kind&&"SplitCoins"!==t.$kind&&"TransferObjects"!==t.$kind||(n=!0)}),n}function ki(e,t){let n=!1;return e.getInputUses(t,(e,t)=>{if(t.MoveCall&&t.MoveCall._argumentTypes){const r=t.MoveCall.arguments.indexOf(e);n=function(e){if("object"!=typeof e.body||!("datatype"in e.body))return!1;return"0x2"===e.body.datatype.package&&"transfer"===e.body.datatype.module&&"Receiving"===e.body.datatype.type}(t.MoveCall._argumentTypes[r])||n}}),n}function Si(e,t){return!!e.inputs.some(e=>e.UnresolvedObject||e.UnresolvedPure)||!(t.onlyTransactionKind||e.gasConfig.price&&e.gasConfig.budget&&e.gasConfig.payment)}async function Oi(e,t,n){if(function(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(t=>{Ii(t,xr.U64,e)});break;case"TransferObjects":Ii(t.TransferObjects.address,xr.Address,e)}}(e),!Si(e,t))return await xi(e),n();const r=function(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}(t);return(r.core?.resolveTransactionPlugin()??vi(r))(e,t,async()=>{await xi(e),await n()})}function xi(e){e.inputs.forEach((e,t)=>{if("Object"!==e.$kind&&"Pure"!==e.$kind)throw new Error(`Input at index ${t} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function Ii(e,t,n){if("Input"!==e.$kind)return;const r=n.inputs[e.Input];"UnresolvedPure"===r.$kind&&(n.inputs[e.Input]=ts.Pure(t.serialize(r.UnresolvedPure.value)))}function Ti(e){function t(t,n){if("string"==typeof t)return e(Or(t).serialize(n));if(t instanceof Uint8Array||Xe(t))return e(t);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return t.u8=t=>e(xr.U8.serialize(t)),t.u16=t=>e(xr.U16.serialize(t)),t.u32=t=>e(xr.U32.serialize(t)),t.u64=t=>e(xr.U64.serialize(t)),t.u128=t=>e(xr.U128.serialize(t)),t.u256=t=>e(xr.U256.serialize(t)),t.bool=t=>e(xr.Bool.serialize(t)),t.string=t=>e(xr.String.serialize(t)),t.address=t=>e(xr.Address.serialize(t)),t.id=t.address,t.vector=(t,n)=>e(xr.vector(Or(t)).serialize(n)),t.option=(t,n)=>e(xr.option(Or(t)).serialize(n)),t}function _i(e){return"string"==typeof e?tn(e):e.Object?e.Object.ImmOrOwnedObject?tn(e.Object.ImmOrOwnedObject.objectId):e.Object.Receiving?tn(e.Object.Receiving.objectId):tn(e.Object.SharedObject.objectId):e.UnresolvedObject?tn(e.UnresolvedObject.objectId):void 0}function Ai(e,t,n){const r=e=>{switch(e.$kind){case"Input":{const n=t.get(e.Input);if(void 0===n)throw new Error(`Input ${e.Input} not found in input mapping`);return{...e,Input:n}}case"Result":{const t=n.get(e.Result);return void 0!==t?{...e,Result:t}:e}case"NestedResult":{const t=n.get(e.NestedResult[0]);return void 0!==t?{...e,NestedResult:[t,e.NestedResult[1]]}:e}default:return e}};switch(e.$kind){case"MoveCall":e.MoveCall.arguments=e.MoveCall.arguments.map(r);break;case"TransferObjects":e.TransferObjects.objects=e.TransferObjects.objects.map(r),e.TransferObjects.address=r(e.TransferObjects.address);break;case"SplitCoins":e.SplitCoins.coin=r(e.SplitCoins.coin),e.SplitCoins.amounts=e.SplitCoins.amounts.map(r);break;case"MergeCoins":e.MergeCoins.destination=r(e.MergeCoins.destination),e.MergeCoins.sources=e.MergeCoins.sources.map(r);break;case"MakeMoveVec":e.MakeMoveVec.elements=e.MakeMoveVec.elements.map(r);break;case"Upgrade":e.Upgrade.ticket=r(e.Upgrade.ticket);break;case"$Intent":{const t=e.$Intent.inputs;e.$Intent.inputs={};for(const[n,s]of Object.entries(t))e.$Intent.inputs[n]=Array.isArray(s)?s.map(r):r(s);break}}}function Ci(e){return tn(e).replace("0x","")}class ji{constructor(e){this.version=2,this.sender=e?.sender??null,this.expiration=e?.expiration??null,this.inputs=e?.inputs??[],this.commands=e?.commands??[],this.gasData=e?.gasData??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const t=xr.TransactionKind.parse(e).ProgrammableTransaction;if(!t)throw new Error("Unable to deserialize from bytes.");return ji.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:t.inputs,commands:t.commands})}static fromBytes(e){const t=xr.TransactionData.parse(e),n=t?.V1,r=n.kind.ProgrammableTransaction;if(!n||!r)throw new Error("Unable to deserialize from bytes.");return ji.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:r.inputs,commands:r.commands})}static restore(e){return 2===e.version?new ji(Lt(En,e)):new ji(Lt(En,function(e){return Lt(En,{version:2,sender:e.sender??null,expiration:e.expiration?"Epoch"in e.expiration?{Epoch:e.expiration.Epoch}:{None:!0}:null,gasData:{owner:e.gasConfig.owner??null,budget:e.gasConfig.budget?.toString()??null,price:e.gasConfig.price?.toString()??null,payment:e.gasConfig.payment?.map(e=>({digest:e.digest,objectId:e.objectId,version:e.version.toString()}))??null},inputs:e.inputs.map(e=>{if("Input"===e.kind){if(Ot(_r,e.value)){const t=Lt(_r,e.value);if(t.Object){if(t.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:t.Object.ImmOrOwned.objectId,version:String(t.Object.ImmOrOwned.version),digest:t.Object.ImmOrOwned.digest}}};if(t.Object.Shared)return{Object:{SharedObject:{mutable:t.Object.Shared.mutable??null,initialSharedVersion:t.Object.Shared.initialSharedVersion,objectId:t.Object.Shared.objectId}}};if(t.Object.Receiving)return{Object:{Receiving:{digest:t.Object.Receiving.digest,version:String(t.Object.Receiving.version),objectId:t.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:Ie(new Uint8Array(t.Pure))}}}return"object"===e.type?{UnresolvedObject:{objectId:e.value}}:{UnresolvedPure:{value:e.value}}}throw new Error("Invalid input")}),commands:e.transactions.map(e=>{switch(e.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in e.type?xn.tagToString(e.type.Some):null,elements:e.objects.map(e=>zr(e))}};case"MergeCoins":return{MergeCoins:{destination:zr(e.destination),sources:e.sources.map(e=>zr(e))}};case"MoveCall":{const[t,n,r]=e.target.split("::");return{MoveCall:{package:t,module:n,function:r,typeArguments:e.typeArguments,arguments:e.arguments.map(e=>zr(e))}}}case"Publish":return{Publish:{modules:e.modules.map(e=>Ie(Uint8Array.from(e))),dependencies:e.dependencies}};case"SplitCoins":return{SplitCoins:{coin:zr(e.coin),amounts:e.amounts.map(e=>zr(e))}};case"TransferObjects":return{TransferObjects:{objects:e.objects.map(e=>zr(e)),address:zr(e.address)}};case"Upgrade":return{Upgrade:{modules:e.modules.map(e=>Ie(Uint8Array.from(e))),dependencies:e.dependencies,package:e.packageId,ticket:zr(e.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(e)}`)})})}(e)))}static getDigestFromBytes(e){const t=function(e,t){const n=Array.from(`${e}::`).map(e=>e.charCodeAt(0)),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),gi(r,{dkLen:32})}("TransactionData",e);return ke(t)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:t,onlyTransactionKind:n}={}){const r=this.inputs,s=this.commands,i={ProgrammableTransaction:{inputs:r,commands:s}};if(n)return xr.TransactionKind.serialize(i,{maxSize:e}).toBytes();const a=t?.expiration??this.expiration,o=t?.sender??this.sender,c={...this.gasData,...t?.gasConfig,...t?.gasData};if(!o)throw new Error("Missing transaction sender");if(!c.budget)throw new Error("Missing gas budget");if(!c.payment)throw new Error("Missing gas payment");if(!c.price)throw new Error("Missing gas price");const u={sender:Ci(o),expiration:a||{None:!0},gasData:{payment:c.payment,owner:Ci(this.gasData.owner??o),price:BigInt(c.price),budget:BigInt(c.budget)},kind:{ProgrammableTransaction:{inputs:r,commands:s}}};return xr.TransactionData.serialize({V1:u},{maxSize:e}).toBytes()}addInput(e,t){const n=this.inputs.length;return this.inputs.push(t),{Input:n,type:e,$kind:"Input"}}getInputUses(e,t){this.mapArguments((n,r)=>("Input"===n.$kind&&n.Input===e&&t(n,r),n))}mapCommandArguments(e,t){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(r=>t(r,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(r=>t(r,n,e)),n.TransferObjects.address=t(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=t(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(r=>t(r,n,e));break;case"MergeCoins":n.MergeCoins.destination=t(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(r=>t(r,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(r=>t(r,n,e));break;case"Upgrade":n.Upgrade.ticket=t(n.Upgrade.ticket,n,e);break;case"$Intent":const r=n.$Intent.inputs;n.$Intent.inputs={};for(const[s,i]of Object.entries(r))n.$Intent.inputs[s]=Array.isArray(i)?i.map(r=>t(r,n,e)):t(i,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const t of this.commands.keys())this.mapCommandArguments(t,e)}replaceCommand(e,t,n=e){if(!Array.isArray(t))return void(this.commands[e]=t);const r=t.length-1;this.commands.splice(e,1,...structuredClone(t)),this.mapArguments((s,i,a)=>{if(a<e+t.length)return s;if("number"!=typeof n&&("Result"===s.$kind&&s.Result===e||"NestedResult"===s.$kind&&s.NestedResult[0]===e)){if("NestedResult"in s&&0!==s.NestedResult[1])throw new Error(`Cannot replace command ${e} with a specific result type: NestedResult[${e}, ${s.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`);return Lt(dn,structuredClone(n))}switch(s.$kind){case"Result":s.Result===e&&"number"==typeof n&&(s.Result=n),s.Result>e&&(s.Result+=r);break;case"NestedResult":if(s.NestedResult[0]===e&&"number"==typeof n)return{$kind:"NestedResult",NestedResult:[n,s.NestedResult[1]]};s.NestedResult[0]>e&&(s.NestedResult[0]+=r)}return s})}replaceCommandWithTransaction(e,t,n){if("Result"!==n.$kind&&"NestedResult"!==n.$kind)throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(e,t),this.replaceCommand(e+t.commands.length,[],"Result"in n?{NestedResult:[n.Result+e,0]}:{NestedResult:[n.NestedResult[0]+e,n.NestedResult[1]]})}insertTransaction(e,t){const n=new Map,r=new Map;for(let e=0;e<t.inputs.length;e++){const r=t.inputs[e],s=_i(r);let i=-1;if(void 0!==s&&(i=this.inputs.findIndex(e=>_i(e)===s),-1!==i&&this.inputs[i].Object?.SharedObject&&r.Object?.SharedObject&&(this.inputs[i].Object.SharedObject.mutable=this.inputs[i].Object.SharedObject.mutable||r.Object.SharedObject.mutable)),-1!==i)n.set(e,i);else{const t=this.inputs.length;this.inputs.push(r),n.set(e,t)}}for(let n=0;n<t.commands.length;n++)r.set(n,e+n);const s=[];for(let e=0;e<t.commands.length;e++){const i=structuredClone(t.commands[e]);Ai(i,n,r),s.push(i)}this.commands.splice(e,0,...s);const i=s.length;i>0&&this.mapArguments((t,n,r)=>{if(r>=e&&r<e+s.length)return t;switch(t.$kind){case"Result":t.Result>=e&&(t.Result+=i);break;case"NestedResult":t.NestedResult[0]>=e&&(t.NestedResult[0]+=i)}return t})}getDigest(){const e=this.build({onlyTransactionKind:!1});return ji.getDigestFromBytes(e)}snapshot(){return Lt(En,this)}shallowClone(){return new ji({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(e){this.sender||(this.sender=e.sender??null),this.expiration||(this.expiration=e.expiration??null),this.gasData.budget||(this.gasData.budget=e.gasData.budget),this.gasData.owner||(this.gasData.owner=e.gasData.owner??null),this.gasData.payment||(this.gasData.payment=e.gasData.payment),this.gasData.price||(this.gasData.price=e.gasData.price);for(let t=0;t<this.inputs.length;t++){const n=this.inputs[t],r=e.inputs[t];switch(n.$kind){case"UnresolvedPure":if("Pure"!==r.$kind)throw new Error(`Expected input at index ${t} to resolve to a Pure argument, but got ${JSON.stringify(r)}`);this.inputs[t]=r;break;case"UnresolvedObject":if("Object"!==r.$kind)throw new Error(`Expected input at index ${t} to resolve to an Object argument, but got ${JSON.stringify(r)}`);if("ImmOrOwnedObject"===r.Object.$kind||"Receiving"===r.Object.$kind){const e=n.UnresolvedObject,s=r.Object.ImmOrOwnedObject??r.Object.Receiving;if(tn(e.objectId)!==tn(s.objectId)||null!=e.version&&e.version!==s.version||null!=e.digest&&e.digest!==s.digest||null!=e.mutable||null!=e.initialSharedVersion)throw new Error(`Input at index ${t} did not match unresolved object. ${JSON.stringify(e)} is not compatible with ${JSON.stringify(s)}`)}else{if("SharedObject"!==r.Object.$kind)throw new Error(`Input at index ${t} resolved to an unexpected Object kind: ${JSON.stringify(r.Object)}`);{const e=n.UnresolvedObject,s=r.Object.SharedObject;if(tn(e.objectId)!==tn(s.objectId)||null!=e.initialSharedVersion&&e.initialSharedVersion!==s.initialSharedVersion||null!=e.mutable&&e.mutable!==s.mutable||null!=e.version||null!=e.digest)throw new Error(`Input at index ${t} did not match unresolved object. ${JSON.stringify(e)} is not compatible with ${JSON.stringify(s)}`)}}this.inputs[t]=r}}}}var Pi,Bi,Ni,Ri,$i,Mi,Ui,Di,Fi,Li,Vi=e=>{throw TypeError(e)},Ki=(e,t,n)=>t.has(e)||Vi("Cannot "+n),zi=(e,t,n)=>(Ki(e,t,"read from private field"),n?n.call(e):t.get(e)),qi=(e,t,n)=>t.has(e)?Vi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Zi=(e,t,n,r)=>(Ki(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Wi=(e,t,n)=>(Ki(e,t,"access private method"),n);const Gi={"Mvr-Source":`@mysten/sui@${f}`};class Hi{constructor({cache:e,url:t,pageSize:n=50,overrides:r}){qi(this,$i),qi(this,Pi),qi(this,Bi),qi(this,Ni),qi(this,Ri),Zi(this,Pi,e),Zi(this,Bi,t),Zi(this,Ni,n),Zi(this,Ri,{packages:r?.packages,types:r?.types}),function(e){if(e?.packages)for(const[t,n]of Object.entries(e.packages)){if(!Wt(t))throw new Error(`Invalid package name: ${t}`);if(!Yt(tn(n)))throw new Error(`Invalid package ID: ${n}`)}if(e?.types)for(const[t,n]of Object.entries(e.types)){if(Qt(t).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");if(!Yt(Qt(n).address))throw new Error(`Invalid type: ${n}`)}}(zi(this,Ri))}async resolvePackage({package:e}){if(!Xi(e))return{package:e};return{package:await zi(this,$i,Mi).load(e)}}async resolveType({type:e}){if(!Xi(e))return{type:e};const t=[...Ji(e)],n=await zi(this,$i,Ui).loadMany(t),r={};for(let e=0;e<t.length;e++){const s=n[e];if(s instanceof Error)throw s;r[t[e]]=s}return{type:Yi(e,r)}}async resolve({types:e=[],packages:t=[]}){const n=new Set;for(const t of e??[])Ji(t,n);const r=[...n],[s,i]=await Promise.all([r.length>0?zi(this,$i,Ui).loadMany(r):[],t.length>0?zi(this,$i,Mi).loadMany(t):[]]),a={...zi(this,Ri)?.types};for(const[e,t]of r.entries()){const n=s[e];if(n instanceof Error)throw n;a[t]=n}const o={};for(const t of e??[]){const e=Yi(t,a);o[t]={type:e}}const c={};for(const[e,n]of(t??[]).entries()){const t=zi(this,Ri)?.packages?.[n]??i[e];if(t instanceof Error)throw t;c[n]={package:t}}return{types:o,packages:c}}}function Ji(e,t=new Set){if("string"==typeof e&&!Xi(e))return t;const n=Qi(e)?e:Qt(e);Xi(n.address)&&t.add(`${n.address}::${n.module}::${n.name}`);for(const e of n.typeParams)Ji(e,t);return t}function Yi(e,t){const n=Qi(e)?e:Qt(e),r=`${n.address}::${n.module}::${n.name}`,s=t[r];return en({...n,address:s?s.split("::")[0]:n.address,typeParams:n.typeParams.map(e=>Yi(e,t))})}function Xi(e){return e.includes("/")||e.includes("@")||e.includes(".sui")}function Qi(e){return"object"==typeof e&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function ea(e){const t=new Set;for(const n of e)if(Xi(n)){if(!Gt(n))throw new Error(`Invalid type with names: ${n}`);t.add(n)}return t}Pi=new WeakMap,Bi=new WeakMap,Ni=new WeakMap,Ri=new WeakMap,$i=new WeakSet,Mi=function(){return zi(this,Pi).readSync(["#mvrPackageDataLoader",zi(this,Bi)??""],()=>{const e=new Ce(async e=>{if(!zi(this,Bi))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Wi(this,$i,Di).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve package: ${e}`))}),t=zi(this,Ri)?.packages;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Ui=function(){return zi(this,Pi).readSync(["#mvrTypeDataLoader",zi(this,Bi)??""],()=>{const e=new Ce(async e=>{if(!zi(this,Bi))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Wi(this,$i,Fi).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve type: ${e}`))}),t=zi(this,Ri)?.types;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Di=async function(e){if(0===e.length)return{};const t=Ae(e,zi(this,Ni)),n={};return await Promise.all(t.map(async e=>{const t=await Wi(this,$i,Li).call(this,"/v1/resolution/bulk",{names:e});if(t?.resolution)for(const e of Object.keys(t?.resolution)){const r=t.resolution[e]?.package_id;r&&(n[e]=r)}})),n},Fi=async function(e){if(0===e.length)return{};const t=Ae(e,zi(this,Ni)),n={};return await Promise.all(t.map(async e=>{const t=await Wi(this,$i,Li).call(this,"/v1/struct-definition/bulk",{types:e});if(t?.resolution)for(const e of Object.keys(t?.resolution)){const r=t.resolution[e]?.type_tag;r&&(n[e]=r)}})),n},Li=async function(e,t){if(!zi(this,Bi))throw new Error("MVR Api URL is not set for the current client");const n=await fetch(`${zi(this,Bi)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...Gi},body:JSON.stringify(t)});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${e?.message}`)}return n.json()};const ta=new WeakMap,na=e=>{let t;if(e){const n=e.overrides??{packages:{},types:{}};ta.has(n)||ta.set(n,new pt),t=new Hi({cache:ta.get(n),url:e.url,pageSize:e.pageSize,overrides:n})}return async(e,n,r)=>{const s=function(e){const t=new Set,n=new Set;for(const r of e.commands)switch(r.$kind){case"MakeMoveVec":r.MakeMoveVec.type&&ea([r.MakeMoveVec.type]).forEach(e=>{n.add(e)});break;case"MoveCall":const e=r.MoveCall,s=e.package.split("::")[0];if(Xi(s)){if(!Wt(s))throw new Error(`Invalid package name: ${s}`);t.add(s)}ea(e.typeArguments??[]).forEach(e=>{n.add(e)})}return{packages:[...t],types:[...n]}}(e);if(0===s.types.length&&0===s.packages.length)return r();const i=await(t||function(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}(n).core.mvr).resolve({types:s.types,packages:s.packages});!function(e,t){for(const n of e.commands){if(n.MakeMoveVec?.type){if(!Xi(n.MakeMoveVec.type))continue;if(!t.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=t.types[n.MakeMoveVec.type].type}const e=n.MoveCall;if(!e)continue;const r=e.package.split("::"),s=r[0];if(Xi(s)&&!t.packages[s])throw new Error(`No address found for package: ${s}`);Xi(s)&&(r[0]=t.packages[s].package,e.package=r.join("::"));const i=e.typeArguments;if(i){for(let e=0;e<i.length;e++)if(Xi(i[e])){if(!t.types[i[e]])throw new Error(`No resolution found for type: ${i[e]}`);i[e]=t.types[i[e]].type}e.typeArguments=i}}}(e,i),await r()}};var ra,sa,ia,aa,oa,ca,ua,da,la,ha,fa,pa,ga,ma,ya,ba,wa,va,Ea,ka=e=>{throw TypeError(e)},Sa=(e,t,n)=>t.has(e)||ka("Cannot "+n),Oa=(e,t,n)=>(Sa(e,t,"read from private field"),n?n.call(e):t.get(e)),xa=(e,t,n)=>t.has(e)?ka("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Ia=(e,t,n,r)=>(Sa(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Ta=(e,t,n)=>(Sa(e,t,"access private method"),n);function _a(e,t=1/0){const n=[],r=t=>n[t]??(n[t]={$kind:"NestedResult",get NestedResult(){return["function"==typeof e?e():e,t]}});return new Proxy({$kind:"Result",get Result(){return"function"==typeof e?e():e}},{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);if(n===Symbol.iterator)return function*(){let e=0;for(;e<t;)yield r(e),e++};if("symbol"==typeof n)return;const s=parseInt(n,10);return Number.isNaN(s)||s<0?void 0:r(s)}})}const Aa=Symbol.for("@mysten/transaction");function Ca(e){return!!e&&"object"==typeof e&&!0===e[Aa]}const ja={buildPlugins:new Map,serializationPlugins:new Map},Pa=Symbol.for("@mysten/transaction/registry");function Ba(){try{const e=globalThis;return e[Pa]||(e[Pa]=ja),e[Pa]}catch{return ja}}const Na=class e{constructor(){xa(this,ha),xa(this,ra),xa(this,sa),xa(this,ia,new Map),xa(this,aa,[]),xa(this,oa,[]),xa(this,ca,new Set),xa(this,ua,new Set),xa(this,da,new Map),xa(this,la),this.object=function(e){function t(t){return e(t)}return t.system=e=>{const n=e?.mutable;return t(void 0!==n?ts.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},t.clock=()=>t(ts.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),t.random=()=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),t.denyList=e=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:e?.mutable}}),t.option=({type:e,value:t})=>n=>n.moveCall({typeArguments:[e],target:"0x1::option::"+(null===t?"none":"some"),arguments:null===t?[]:[n.object(t)]}),t}(e=>{if("function"==typeof e)return this.object(this.add(e));if("object"==typeof e&&Ot(dn,e))return e;const t=_i(e),n=Oa(this,la).inputs.find(e=>t===_i(e));return n?.Object?.SharedObject&&"object"==typeof e&&e.Object?.SharedObject&&(n.Object.SharedObject.mutable=n.Object.SharedObject.mutable||e.Object.SharedObject.mutable),n?{$kind:"Input",Input:Oa(this,la).inputs.indexOf(n),type:"object"}:Ta(this,ha,ga).call(this,"object","string"==typeof e?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:tn(e)}}:e)});const e=Ba();Ia(this,la,new ji),Ia(this,sa,[...e.buildPlugins.values()]),Ia(this,ra,[...e.serializationPlugins.values()])}static fromKind(t){const n=new e;return Ia(n,la,ji.fromKindBytes("string"==typeof t?Oe(t):t)),Ia(n,aa,Oa(n,la).inputs.slice()),Ia(n,oa,Oa(n,la).commands.slice()),Ia(n,ca,new Set(Oa(n,oa).map((e,t)=>t))),n}static from(t){const n=new e;return Ca(t)?Ia(n,la,ji.restore(t.getData())):"string"==typeof t&&t.startsWith("{")?Ia(n,la,ji.restore(JSON.parse(t))):Ia(n,la,ji.fromBytes("string"==typeof t?Oe(t):t)),Ia(n,aa,Oa(n,la).inputs.slice()),Ia(n,oa,Oa(n,la).commands.slice()),Ia(n,ca,new Set(Oa(n,oa).map((e,t)=>t))),n}static registerGlobalSerializationPlugin(e,t){Ba().serializationPlugins.set(e,t??e)}static unregisterGlobalSerializationPlugin(e){Ba().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,t){Ba().buildPlugins.set(e,t??e)}static unregisterGlobalBuildPlugin(e){Ba().buildPlugins.delete(e)}addSerializationPlugin(e){Oa(this,ra).push(e)}addBuildPlugin(e){Oa(this,sa).push(e)}addIntentResolver(e,t){if(Oa(this,ia).has(e)&&Oa(this,ia).get(e)!==t)throw new Error(`Intent resolver for ${e} already exists`);Oa(this,ia).set(e,t)}setSender(e){Oa(this,la).sender=e}setSenderIfNotSet(e){Oa(this,la).sender||(Oa(this,la).sender=e)}setExpiration(e){Oa(this,la).expiration=e?Lt(vn,e):null}setGasPrice(e){Oa(this,la).gasConfig.price=String(e)}setGasBudget(e){Oa(this,la).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){null==Oa(this,la).gasData.budget&&(Oa(this,la).gasConfig.budget=String(e))}setGasOwner(e){Oa(this,la).gasConfig.owner=e}setGasPayment(e){Oa(this,la).gasConfig.payment=e.map(e=>Lt(un,e))}get blockData(){return Vr(Oa(this,la).snapshot())}getData(){return Oa(this,la).snapshot()}get[Aa](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:Ti(e=>Xe(e)?Ta(this,ha,ga).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):Ta(this,ha,ga).call(this,"pure",Ot(wn,e)?Lt(wn,e):e instanceof Uint8Array?ts.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(ts.ObjectRef(...e))}receivingRef(...e){return this.object(ts.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(ts.SharedObjectRef(...e))}add(e){if("function"==typeof e){if(Oa(this,da).has(e))return Oa(this,da).get(e);const t=Ta(this,ha,fa).call(this),n=e(t);if(!n||"object"!=typeof n||!("then"in n))return Ia(this,ca,Oa(t,ca)),Oa(this,da).set(e,n),n;const r=Ta(this,ha,pa).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Oa(this,la).commands.length,result:null}}});Oa(this,ua).add(Promise.resolve(n).then(e=>{r.$Intent.data.result=e}));const s=_a(()=>r.$Intent.data.resultIndex);return Oa(this,da).set(e,s),s}return Ta(this,ha,pa).call(this,e),_a(Oa(this,la).commands.length-1)}splitCoins(e,t){const n=kn.SplitCoins("string"==typeof e?this.object(e):Ta(this,ha,ya).call(this,e),t.map(e=>"number"==typeof e||"bigint"==typeof e||"string"==typeof e?this.pure.u64(e):Ta(this,ha,ma).call(this,e)));return Ta(this,ha,pa).call(this,n),_a(Oa(this,la).commands.length-1,t.length)}mergeCoins(e,t){return this.add(kn.MergeCoins(this.object(e),t.map(e=>this.object(e))))}publish({modules:e,dependencies:t}){return this.add(kn.Publish({modules:e,dependencies:t}))}upgrade({modules:e,dependencies:t,package:n,ticket:r}){return this.add(kn.Upgrade({modules:e,dependencies:t,package:n,ticket:this.object(r)}))}moveCall({arguments:e,...t}){return this.add(kn.MoveCall({...t,arguments:e?.map(e=>Ta(this,ha,ma).call(this,e))}))}transferObjects(e,t){return this.add(kn.TransferObjects(e.map(e=>this.object(e)),"string"==typeof t?this.pure.address(t):Ta(this,ha,ma).call(this,t)))}makeMoveVec({type:e,elements:t}){return this.add(kn.MakeMoveVec({type:e,elements:t.map(e=>this.object(e))}))}serialize(){return JSON.stringify(Vr(Oa(this,la).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const t=this.isFullyResolved();return JSON.stringify(Lt(es,t?{...Oa(this,la).snapshot(),digest:Oa(this,la).getDigest()}:Oa(this,la).snapshot()),(e,t)=>"bigint"==typeof t?t.toString():t,2)}async sign(e){const{signer:t,...n}=e,r=await this.build(n);return t.signTransaction(r)}isFullyResolved(){return!!Oa(this,la).sender&&(!(Oa(this,ua).size>0)&&(!Oa(this,la).commands.some(e=>e.$Intent)&&!Si(Oa(this,la),{})))}async build(e={}){return await this.prepareForSerialization(e),await Ta(this,ha,ba).call(this,e),Oa(this,la).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await Ta(this,ha,ba).call(this,e),Oa(this,la).getDigest()}async prepareForSerialization(e){await Ta(this,ha,va).call(this),Ta(this,ha,Ea).call(this);const t=new Set;for(const e of Oa(this,la).commands)e.$Intent&&t.add(e.$Intent.name);const n=[...Oa(this,ra)];for(const r of t)if(!e.supportedIntents?.includes(r)){if(!Oa(this,ia).has(r))throw new Error(`Missing intent resolver for ${r}`);n.push(Oa(this,ia).get(r))}n.push(na()),await Ta(this,ha,wa).call(this,n,e)}};ra=new WeakMap,sa=new WeakMap,ia=new WeakMap,aa=new WeakMap,oa=new WeakMap,ca=new WeakMap,ua=new WeakMap,da=new WeakMap,la=new WeakMap,ha=new WeakSet,fa=function(){const e=new Na;return Ia(e,la,Oa(this,la)),Ia(e,ra,Oa(this,ra)),Ia(e,sa,Oa(this,sa)),Ia(e,ia,Oa(this,ia)),Ia(e,ua,Oa(this,ua)),Ia(e,ca,new Set(Oa(this,ca))),Ia(e,da,Oa(this,da)),Oa(this,aa).push(Oa(e,aa)),Oa(this,oa).push(Oa(e,oa)),e},pa=function(e){const t=Oa(this,la).commands.length;return Oa(this,oa).push(e),Oa(this,ca).add(t),Oa(this,la).commands.push(e),Oa(this,la).mapCommandArguments(t,e=>{if("Result"===e.$kind&&!Oa(this,ca).has(e.Result))throw new Error(`Result { Result: ${e.Result} } is not available to use in the current transaction`);if("NestedResult"===e.$kind&&!Oa(this,ca).has(e.NestedResult[0]))throw new Error(`Result { NestedResult: [${e.NestedResult[0]}, ${e.NestedResult[1]}] } is not available to use in the current transaction`);if("Input"===e.$kind&&e.Input>=Oa(this,la).inputs.length)throw new Error(`Input { Input: ${e.Input} } references an input that does not exist in the current transaction`);return e}),e},ga=function(e,t){return Oa(this,aa).push(t),Oa(this,la).addInput(e,t)},ma=function(e){return Xe(e)?this.pure(e):Ta(this,ha,ya).call(this,e)},ya=function(e){if("function"==typeof e){const t=this.add(e);return"function"==typeof t?Ta(this,ha,ya).call(this,t):Lt(dn,t)}return Lt(dn,e)},ba=async function(e){if(!e.onlyTransactionKind&&!Oa(this,la).sender)throw new Error("Missing transaction sender");await Ta(this,ha,wa).call(this,[...Oa(this,sa),Oi],e)},wa=async function(e,t){try{const n=r=>{if(r>=e.length)return()=>{};const s=e[r];return async()=>{const e=n(r+1);let i=!1,a=!1;if(await s(Oa(this,la),t,async()=>{if(i)throw new Error(`next() was call multiple times in TransactionPlugin ${r}`);i=!0,await e(),a=!0}),!i)throw new Error(`next() was not called in TransactionPlugin ${r}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${r}`)}};await n(0)()}finally{Ia(this,aa,Oa(this,la).inputs.slice()),Ia(this,oa,Oa(this,la).commands.slice())}},va=async function(){for(;Oa(this,ua).size>0;){const e=Promise.all(Oa(this,ua));Oa(this,ua).clear(),Oa(this,ua).add(e),await e,Oa(this,ua).delete(e)}},Ea=function(){const e=Oa(this,la).commands,t=Oa(this,la).inputs,n=Oa(this,oa).flat(1/0),r=Oa(this,aa).flat(1/0);if(n.length!==e.length)throw new Error("Unexpected number of commands found in transaction data");if(r.length!==t.length)throw new Error("Unexpected number of inputs found in transaction data");const s=n.filter(e=>"AsyncTransactionThunk"!==e.$Intent?.name);function i(t){const n=e[t];if("AsyncTransactionThunk"===n.$Intent?.name){const e=n.$Intent.data.result;if(null==e)throw new Error("AsyncTransactionThunk has not been resolved");return i(e.Result)}const r=s.indexOf(n);if(-1===r)throw new Error("Unable to find original index for command");return r}Oa(this,la).commands=s,Oa(this,la).inputs=r,Ia(this,oa,s),Ia(this,aa,r),Ia(this,ca,new Set(s.map((e,t)=>t))),Oa(this,la).mapArguments(e=>{if("Input"===e.$kind){const n=r.indexOf(t[e.Input]);if(-1===n)throw new Error("Input has not been resolved");return{...e,Input:n}}if("Result"===e.$kind){const t=i(e.Result);return{...e,Result:t}}if("NestedResult"===e.$kind){const t=i(e.NestedResult[0]);return{...e,NestedResult:[t,e.NestedResult[1]]}}return e});for(const[t,n]of e.entries())if("AsyncTransactionThunk"===n.$Intent?.name)try{n.$Intent.data.resultIndex=i(t)}catch{}};let Ra=Na;const $a={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class Ma extends gt{constructor(e){super(e),this.core=this,this.mvr=new Hi({cache:this.cache.scope("core.mvr"),url:e.mvr?.url??$a[this.network],pageSize:e.mvr?.pageSize,overrides:e.mvr?.overrides})}async getObject(e){const{objectId:t}=e,{objects:[n]}=await this.getObjects({objectIds:[t],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const t=xn.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=mi(e.parentId,t,e.name.bcs),{objects:[r]}=await this.getObjects({objectIds:[n],signal:e.signal});if(r instanceof Error)throw r;const s=Qt(r.type),i=await r.content;return{dynamicField:{id:r.id,digest:r.digest,version:r.version,type:r.type,previousTransaction:r.previousTransaction,name:{type:"string"==typeof s.typeParams[0]?s.typeParams[0]:en(s.typeParams[0]),bcs:e.name.bcs},value:{type:"string"==typeof s.typeParams[1]?s.typeParams[1]:en(s.typeParams[1]),bcs:i.slice(Jt+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:t=6e4,...n}){const r=e?AbortSignal.any([AbortSignal.timeout(t),e]):AbortSignal.timeout(t),s=new Promise((e,t)=>{r.addEventListener("abort",()=>t(r.reason))});for(s.catch(()=>{});;){r.throwIfAborted();try{return await this.getTransaction({...n,signal:r})}catch{await Promise.race([new Promise(e=>setTimeout(e,2e3)),s])}}}}class Ua extends Error{}class Da extends Ua{constructor(e,t){super(t),this.code=e}static fromResponse(e,t){switch(e.code){case"notExists":return new Da(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Da(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Da(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Da(e.code,`Display error: ${e.error}`);default:return new Da(e.code,"Unknown error while loading object"+(t?` ${t}`:""))}}}function Fa(e){return{...ji.fromBytes(e).snapshot(),bcs:e}}function La(e){const t=xr.TransactionEffects.parse(e);switch(t.$kind){case"V1":return function(){throw new Error("V1 effects are not supported yet")}(t.V1);case"V2":return function({bytes:e,effects:t}){const n=t.changedObjects.map(([e,n])=>({id:e,inputState:"Exist"===n.inputState.$kind?"Exists":"DoesNotExist",inputVersion:n.inputState.Exist?.[0][0]??null,inputDigest:n.inputState.Exist?.[0][1]??null,inputOwner:n.inputState.Exist?.[1]??null,outputState:"NotExist"===n.outputState.$kind?"DoesNotExist":n.outputState.$kind,outputVersion:"PackageWrite"===n.outputState.$kind?n.outputState.PackageWrite?.[0]:n.outputState.ObjectWrite?t.lamportVersion:null,outputDigest:"PackageWrite"===n.outputState.$kind?n.outputState.PackageWrite?.[1]:n.outputState.ObjectWrite?.[0]??null,outputOwner:n.outputState.ObjectWrite?n.outputState.ObjectWrite[1]:null,idOperation:n.idOperation.$kind}));return{bcs:e,digest:t.transactionDigest,version:2,status:"Success"===t.status.$kind?{success:!0,error:null}:{success:!1,error:t.status.Failed.error.$kind},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:null===t.gasObjectIndex?null:n[t.gasObjectIndex]??null,eventsDigest:t.eventsDigest,dependencies:t.dependencies,lamportVersion:t.lamportVersion,changedObjects:n,unchangedConsensusObjects:t.unchangedSharedObjects.map(([e,t])=>({kind:"MutateDeleted"===t.$kind?"MutateConsensusStreamEnded":"ReadDeleted"===t.$kind?"ReadConsensusStreamEnded":t.$kind,objectId:e,version:"ReadOnlyRoot"===t.$kind?t.ReadOnlyRoot[0]:t[t.$kind],digest:"ReadOnlyRoot"===t.$kind?t.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:t.auxDataDigest}}({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}var Va,Ka=e=>{throw TypeError(e)},za=(e,t,n)=>t.has(e)||Ka("Cannot "+n),qa=(e,t,n)=>(za(e,t,"read from private field"),n?n.call(e):t.get(e));class Za extends Ma{constructor({jsonRpcClient:e,mvr:t}){var n,r,s;super({network:e.network,base:e,mvr:t}),n=this,(r=Va).has(n)?Ka("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(n):r.set(n,s),((e,t,n,r)=>{za(e,t,"write to private field"),r?r.call(e,n):t.set(e,n)})(this,Va,e)}async getObjects(e){const t=Ae(e.objectIds,50),n=[];for(const r of t){const t=await qa(this,Va).multiGetObjects({ids:r,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:e.signal});for(const[e,s]of t.entries())s.error?n.push(Da.fromResponse(s.error,r[e])):n.push(Wa(s.data))}return{objects:n}}async getOwnedObjects(e){const t=await qa(this,Va).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:t.data.map(e=>{if(e.error)throw Da.fromResponse(e.error);return Wa(e.data)}),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getCoins(e){const t=await qa(this,Va).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:t.data.map(t=>({id:t.coinObjectId,version:t.version,digest:t.digest,balance:t.balance,type:`0x2::coin::Coin<${t.coinType}>`,content:Promise.resolve(Xa.serialize({id:t.coinObjectId,balance:{value:t.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address},previousTransaction:t.previousTransaction})),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getBalance(e){const t=await qa(this,Va).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:t.coinType,balance:t.totalBalance}}}async getAllBalances(e){return{balances:(await qa(this,Va).getAllBalances({owner:e.address,signal:e.signal})).map(e=>({coinType:e.coinType,balance:e.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){return{transaction:Ja(await qa(this,Va).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal}))}}async executeTransaction(e){return{transaction:Ja(await qa(this,Va).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal}))}}async dryRunTransaction(e){const t=Ra.from(e.transaction),n=await qa(this,Va).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:r,objectTypes:s}=function({bytes:e,effects:t,objectChanges:n}){const r=[],s=[],i={};return n?.forEach(e=>{switch(e.type){case"published":r.push({id:e.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:e.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:e.sender},outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Ga(e.recipient),idOperation:"None"}),i[e.objectId]=e.objectType;break;case"mutated":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.previousVersion,inputDigest:null,inputOwner:Ga(e.owner),outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Ga(e.owner),idOperation:"None"}),i[e.objectId]=e.objectType;break;case"deleted":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:t.deleted?.find(t=>t.objectId===e.objectId)?.digest??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[e.objectId]=e.objectType;break;case"wrapped":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:e.sender},outputState:"ObjectWrite",outputVersion:e.version,outputDigest:t.wrapped?.find(t=>t.objectId===e.objectId)?.digest??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:e.sender},idOperation:"None"}),i[e.objectId]=e.objectType;break;case"created":r.push({id:e.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Ga(e.owner),idOperation:"Created"}),i[e.objectId]=e.objectType}}),{objectTypes:i,effects:{bcs:e??null,digest:t.transactionDigest,version:2,status:"success"===t.status.status?{success:!0,error:null}:{success:!1,error:t.status.error},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:{id:t.gasObject?.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:t.gasObject.reference.version,outputDigest:t.gasObject.reference.digest,outputOwner:Ga(t.gasObject.owner),idOperation:"None"},eventsDigest:t.eventsDigest??null,dependencies:t.dependencies??[],lamportVersion:t.gasObject.reference.version,changedObjects:r,unchangedConsensusObjects:s,auxiliaryDataDigest:null}}}({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await t.getDigest(),epoch:null,effects:r,objectTypes:Promise.resolve(s),signatures:[],transaction:Fa(e.transaction),balanceChanges:n.balanceChanges.map(e=>({coinType:e.coinType,address:Ha(e.owner),amount:e.amount}))}}}async getReferenceGasPrice(e){const t=await qa(this,Va).getReferenceGasPrice({signal:e?.signal});return{referenceGasPrice:String(t)}}async getDynamicFields(e){const t=await qa(this,Va).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:t.data.map(e=>({id:e.objectId,type:e.objectType,name:{type:e.name.type,bcs:Oe(e.bcsName)}})),hasNextPage:t.hasNextPage,cursor:t.nextCursor}}async verifyZkLoginSignature(e){const t=await qa(this,Va).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:t.success,errors:t.errors}}async defaultNameServiceName(e){return{data:{name:(await qa(this,Va).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return vi(qa(this,Va))}async getMoveFunction(e){const t=await qa(this,Va).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:tn(e.packageId),moduleName:e.moduleName,name:e.name,visibility:to(t.visibility),isEntry:t.isEntry,typeParameters:t.typeParameters.map(e=>{return{isPhantom:!1,constraints:(t=e,t.abilities.map(e=>{switch(e){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}}))};var t}),parameters:t.parameters.map(e=>Qa(e)),returns:t.return.map(e=>Qa(e))}}}}function Wa(e){return{id:e.objectId,version:e.version,digest:e.digest,type:e.type,content:Promise.resolve("moveObject"===e.bcs?.dataType?Oe(e.bcs.bcsBytes):new Uint8Array),owner:Ga(e.owner),previousTransaction:e.previousTransaction??null}}function Ga(e){if("Immutable"===e)return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in e)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:e.ConsensusAddressOwner.owner,startVersion:e.ConsensusAddressOwner.start_version}};if("AddressOwner"in e)return{$kind:"AddressOwner",AddressOwner:e.AddressOwner};if("ObjectOwner"in e)return{$kind:"ObjectOwner",ObjectOwner:e.ObjectOwner};if("Shared"in e)return{$kind:"Shared",Shared:{initialSharedVersion:e.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function Ha(e){if("Immutable"===e)return null;if("ConsensusAddressOwner"in e)return e.ConsensusAddressOwner.owner;if("AddressOwner"in e)return e.AddressOwner;if("ObjectOwner"in e)return e.ObjectOwner;if("Shared"in e)return null;throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function Ja(e){const t=xr.SenderSignedData.parse(Oe(e.rawTransaction))[0],n={};e.objectChanges?.forEach(e=>{"published"!==e.type&&(n[e.objectId]=e.objectType)});const r=xr.TransactionData.serialize(t.intentMessage.value).toBytes(),s=ji.restore({version:2,sender:t.intentMessage.value.V1.sender,expiration:t.intentMessage.value.V1.expiration,gasData:t.intentMessage.value.V1.gasData,inputs:t.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:t.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:e.digest,epoch:e.effects?.executedEpoch??null,effects:La(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(n),transaction:{...s,bcs:r},signatures:t.txSignatures,balanceChanges:e.balanceChanges?.map(e=>({coinType:e.coinType,address:Ha(e.owner),amount:e.amount}))??[]}}Va=new WeakMap;const Ya=xr.struct("Balance",{value:xr.u64()}),Xa=xr.struct("Coin",{id:xr.Address,balance:Ya});function Qa(e){if("string"!=typeof e){if("Reference"in e)return{reference:"immutable",body:eo(e.Reference)};if("MutableReference"in e)return{reference:"mutable",body:eo(e.MutableReference)}}return{reference:null,body:eo(e)}}function eo(e){switch(e){case"Address":return{$kind:"address"};case"Bool":return{$kind:"bool"};case"U8":return{$kind:"u8"};case"U16":return{$kind:"u16"};case"U32":return{$kind:"u32"};case"U64":return{$kind:"u64"};case"U128":return{$kind:"u128"};case"U256":return{$kind:"u256"}}if("string"==typeof e)throw new Error(`Unknown type: ${e}`);if("Vector"in e)return{$kind:"vector",vector:eo(e.Vector)};if("Struct"in e)return{$kind:"datatype",datatype:{typeName:`${tn(e.Struct.address)}::${e.Struct.module}::${e.Struct.name}`,typeParameters:e.Struct.typeArguments.map(e=>eo(e))}};if("TypeParameter"in e)return{$kind:"typeParameter",index:e.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}function to(e){switch(e){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const no=Symbol.for("@mysten/SuiClient");class ro extends gt{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new Z({url:e.url}),this.core=new Za({jsonRpcClient:this,mvr:e.mvr})}get[no](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:t,cursor:n,limit:r,signal:s}){if(!t||!Yt(tn(t)))throw new Error("Invalid Sui address");return e&&Xi(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[t,e,n,r],signal:s})}async getAllCoins(e){if(!e.owner||!Yt(tn(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:t,signal:n}){if(!e||!Yt(tn(e)))throw new Error("Invalid Sui address");return t&&Xi(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getBalance",params:[e,t],signal:n})}async getAllBalances(e){if(!e.owner||!Yt(tn(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:t}){return e&&Xi(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:t})}async getTotalSupply({coinType:e,signal:t}){return e&&Xi(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:t})}async call(e,t,{signal:n}={}){return await this.transport.request({method:e,params:t,signal:n})}async getMoveFunctionArgTypes({package:e,module:t,function:n,signal:r}){return e&&Wt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,t,n],signal:r})}async getNormalizedMoveModulesByPackage({package:e,signal:t}){return e&&Wt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:t})}async getNormalizedMoveModule({package:e,module:t,signal:n}){return e&&Wt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,t],signal:n})}async getNormalizedMoveFunction({package:e,module:t,function:n,signal:r}){return e&&Wt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,t,n],signal:r})}async getNormalizedMoveStruct({package:e,module:t,struct:n,signal:r}){return e&&Wt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,t,n],signal:r})}async getOwnedObjects(e){if(!e.owner||!Yt(tn(e.owner)))throw new Error("Invalid Sui address");const t=e.filter?{...e.filter}:void 0;return t&&"MoveModule"in t&&Wt(t.MoveModule.package)?t.MoveModule={module:t.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveModule.package})).package}:t&&"StructType"in t&&Xi(t.StructType)&&(t.StructType=(await this.core.mvr.resolveType({type:t.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:t,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!Xt(nn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){e.ids.forEach(e=>{if(!e||!Xt(nn(e)))throw new Error(`Invalid Sui Object id ${e}`)});if(e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:t,cursor:n,limit:r,order:s,signal:i}){return e&&"MoveFunction"in e&&Wt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:t},n,r,"descending"===(s||"descending")],signal:i})}async getTransactionBlock(e){if(!Ht(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){e.digests.forEach(e=>{if(!Ht(e))throw new Error(`Invalid Transaction digest ${e}`)});if(e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:t,options:n,requestType:r,signal:s}){const i=await this.transport.request({method:"sui_executeTransactionBlock",params:["string"==typeof e?e:Ie(e),Array.isArray(t)?t:[t],n],signal:s});if("WaitForLocalExecution"===r)try{await this.waitForTransaction({digest:i.digest})}catch{}return i}async signAndExecuteTransaction({transaction:e,signer:t,...n}){let r;e instanceof Uint8Array?r=e:(e.setSenderIfNotSet(t.toSuiAddress()),r=await e.build({client:this}));const{signature:s,bytes:i}=await t.signTransaction(r);return this.executeTransactionBlock({transactionBlock:i,signature:s,...n})}async getTotalTransactionBlocks({signal:e}={}){const t=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(t)}async getReferenceGasPrice({signal:e}={}){const t=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(t)}async getStakes(e){if(!e.owner||!Yt(tn(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(e=>{if(!e||!Xt(nn(e)))throw new Error(`Invalid Sui Stake id ${e}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:t,limit:n,order:r,signal:s}){return e&&"MoveEventType"in e&&Xi(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Wt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Wt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,t,n,"descending"===(r||"descending")],signal:s})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){let t;if(Ca(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),t=Ie(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if("string"==typeof e.transactionBlock)t=e.transactionBlock;else{if(!(e.transactionBlock instanceof Uint8Array))throw new Error("Unknown transaction block format.");t=Ie(e.transactionBlock)}return e.signal?.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,t,e.gasPrice?.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:["string"==typeof e.transactionBlock?e.transactionBlock:Ie(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!Xt(nn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const t=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(t)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e?.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e?.epoch],signal:e?.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e?.cursor,e?.limit,e?.descendingOrder],signal:e?.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e?.descendingOrder],signal:e?.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e?.cursor,e?.limit,e?.descendingOrder],signal:e?.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const t=await this.getCheckpoint({id:"0",signal:e});return _e(Se(t.digest).slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...t}){const{nextCursor:n,hasNextPage:r,data:s}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[t.address,t.cursor,t.limit],signal:t.signal});return{hasNextPage:r,nextCursor:n,data:s.map(t=>function(e,t="at"){const n=e.toLowerCase();let r;if(n.includes("@")){if(!Kt.test(n))throw new Error(`Invalid SuiNS name ${e}`);const[t,s]=n.split("@");r=[...t?t.split("."):[],s]}else{if(!zt.test(n))throw new Error(`Invalid SuiNS name ${e}`);r=n.split(".").slice(0,-1)}return"dot"===t?`${r.join(".")}.sui`:`${r.slice(0,-1).join(".")}@${r[r.length-1]}`}(t,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e?.version],signal:e?.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:t=6e4,pollInterval:n=2e3,...r}){const s=AbortSignal.timeout(t),i=new Promise((e,t)=>{s.addEventListener("abort",()=>t(s.reason))});for(i.catch(()=>{});!s.aborted;){e?.throwIfAborted();try{return await this.getTransactionBlock(r)}catch{await Promise.race([new Promise(e=>setTimeout(e,n)),i])}}throw s.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class so extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function io(e){}function ao(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=io,onError:n=io,onRetry:r=io,onComment:s}=e;let i,a="",o=!0,c="",u="";function d(e){if(""===e)return c.length>0&&t({id:i,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),i=void 0,c="",void(u="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1!==n){const t=e.slice(0,n),r=" "===e[n+1]?2:1;return void l(t,e.slice(n+r),e)}l(e,"",e)}function l(e,t,s){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new so(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:n(new so(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:s}))}}return{feed:function(e){const t=o?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const s=e.indexOf("\r",r),i=e.indexOf("\n",r);let a=-1;if(-1!==s&&-1!==i?a=Math.min(s,i):-1!==s?a=s===e.length-1?-1:s:-1!==i&&(a=i),-1===a){n=e.slice(r);break}{const n=e.slice(r,a);t.push(n),r=a+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${a}${t}`);for(const e of n)d(e);a=r,o=!1},reset:function(e={}){a&&e.consume&&d(a),o=!0,i=void 0,c="",u="",a=""}}}class oo extends Event{constructor(e,t){var n,r;super(e),this.code=null!=(n=null==t?void 0:t.code)?n:void 0,this.message=null!=(r=null==t?void 0:t.message)?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return n(uo(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(uo(this),t)}}function co(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(co).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${co(e.cause)}`:e.message:`${e}`}function uo(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var lo,ho,fo,po,go,mo,yo,bo,wo,vo,Eo,ko,So,Oo,xo,Io,To,_o,Ao,Co,jo,Po,Bo,No,Ro,$o=e=>{throw TypeError(e)},Mo=(e,t,n)=>t.has(e)||$o("Cannot "+n),Uo=(e,t,n)=>(Mo(e,t,"read from private field"),n?n.call(e):t.get(e)),Do=(e,t,n)=>t.has(e)?$o("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Fo=(e,t,n,r)=>(Mo(e,t,"write to private field"),t.set(e,n),n),Lo=(e,t,n)=>(Mo(e,t,"access private method"),n);class Vo extends EventTarget{constructor(e,t){var n,r;super(),Do(this,Oo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Do(this,lo),Do(this,ho),Do(this,fo),Do(this,po),Do(this,go),Do(this,mo),Do(this,yo),Do(this,bo,null),Do(this,wo),Do(this,vo),Do(this,Eo,null),Do(this,ko,null),Do(this,So,null),Do(this,Io,async e=>{var t;Uo(this,vo).reset();const{body:n,redirected:r,status:s,headers:i}=e;if(204===s)return Lo(this,Oo,jo).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(Fo(this,fo,r?new URL(e.url):void 0),200!==s)return void Lo(this,Oo,jo).call(this,`Non-200 status code (${s})`,s);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void Lo(this,Oo,jo).call(this,'Invalid content type, expected "text/event-stream"',s);if(Uo(this,lo)===this.CLOSED)return;Fo(this,lo,this.OPEN);const a=new Event("open");if(null==(t=Uo(this,So))||t.call(this,a),this.dispatchEvent(a),"object"!=typeof n||!n||!("getReader"in n))return Lo(this,Oo,jo).call(this,"Invalid response body, expected a web ReadableStream",s),void this.close();const o=new TextDecoder,c=n.getReader();let u=!0;do{const{done:e,value:t}=await c.read();t&&Uo(this,vo).feed(o.decode(t,{stream:!e})),e&&(u=!1,Uo(this,vo).reset(),Lo(this,Oo,Po).call(this))}while(u)}),Do(this,To,e=>{Fo(this,wo,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&Lo(this,Oo,Po).call(this,co(e))}),Do(this,Ao,e=>{"string"==typeof e.id&&Fo(this,bo,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Uo(this,fo)?Uo(this,fo).origin:Uo(this,ho).origin,lastEventId:e.id||""});Uo(this,ko)&&(!e.event||"message"===e.event)&&Uo(this,ko).call(this,t),this.dispatchEvent(t)}),Do(this,Co,e=>{Fo(this,mo,e)}),Do(this,Bo,()=>{Fo(this,yo,void 0),Uo(this,lo)===this.CONNECTING&&Lo(this,Oo,xo).call(this)});try{if(e instanceof URL)Fo(this,ho,e);else{if("string"!=typeof e)throw new Error("Invalid URL");Fo(this,ho,new URL(e,function(){const e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()))}}catch{throw function(e){const t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):new SyntaxError(e)}("An invalid or illegal string was specified")}Fo(this,vo,ao({onEvent:Uo(this,Ao),onRetry:Uo(this,Co)})),Fo(this,lo,this.CONNECTING),Fo(this,mo,3e3),Fo(this,go,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),Fo(this,po,null!=(r=null==t?void 0:t.withCredentials)&&r),Lo(this,Oo,xo).call(this)}get readyState(){return Uo(this,lo)}get url(){return Uo(this,ho).href}get withCredentials(){return Uo(this,po)}get onerror(){return Uo(this,Eo)}set onerror(e){Fo(this,Eo,e)}get onmessage(){return Uo(this,ko)}set onmessage(e){Fo(this,ko,e)}get onopen(){return Uo(this,So)}set onopen(e){Fo(this,So,e)}addEventListener(e,t,n){const r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){const r=t;super.removeEventListener(e,r,n)}close(){Uo(this,yo)&&clearTimeout(Uo(this,yo)),Uo(this,lo)!==this.CLOSED&&(Uo(this,wo)&&Uo(this,wo).abort(),Fo(this,lo,this.CLOSED),Fo(this,wo,void 0))}}function Ko(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function zo(e){const t={};for(const n of Object.keys(e)){const r=Ko(n),s=e[n];t[r]=s}return t}lo=new WeakMap,ho=new WeakMap,fo=new WeakMap,po=new WeakMap,go=new WeakMap,mo=new WeakMap,yo=new WeakMap,bo=new WeakMap,wo=new WeakMap,vo=new WeakMap,Eo=new WeakMap,ko=new WeakMap,So=new WeakMap,Oo=new WeakSet,xo=function(){Fo(this,lo,this.CONNECTING),Fo(this,wo,new AbortController),Uo(this,go)(Uo(this,ho),Lo(this,Oo,_o).call(this)).then(Uo(this,Io)).catch(Uo(this,To))},Io=new WeakMap,To=new WeakMap,_o=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Uo(this,bo)?{"Last-Event-ID":Uo(this,bo)}:void 0},cache:"no-store",signal:null==(e=Uo(this,wo))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ao=new WeakMap,Co=new WeakMap,jo=function(e,t){var n;Uo(this,lo)!==this.CLOSED&&Fo(this,lo,this.CLOSED);const r=new oo("error",{code:t,message:e});null==(n=Uo(this,Eo))||n.call(this,r),this.dispatchEvent(r)},Po=function(e,t){var n;if(Uo(this,lo)===this.CLOSED)return;Fo(this,lo,this.CONNECTING);const r=new oo("error",{code:t,message:e});null==(n=Uo(this,Eo))||n.call(this,r),this.dispatchEvent(r),Fo(this,yo,setTimeout(Uo(this,Bo),Uo(this,mo)))},Bo=new WeakMap,Vo.CONNECTING=0,Vo.OPEN=1,Vo.CLOSED=2,function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(No||(No={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Ro||(Ro={}));const qo=No.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Zo=e=>{switch(typeof e){case"undefined":return qo.undefined;case"string":return qo.string;case"number":return Number.isNaN(e)?qo.nan:qo.number;case"boolean":return qo.boolean;case"function":return qo.function;case"bigint":return qo.bigint;case"symbol":return qo.symbol;case"object":return Array.isArray(e)?qo.array:null===e?qo.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?qo.promise:"undefined"!=typeof Map&&e instanceof Map?qo.map:"undefined"!=typeof Set&&e instanceof Set?qo.set:"undefined"!=typeof Date&&e instanceof Date?qo.date:qo.object;default:return qo.unknown}},Wo=No.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Go extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof Go))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,No.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);var Ho=(e,t)=>{let n;switch(e.code){case Wo.invalid_type:n=e.received===qo.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Wo.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,No.jsonStringifyReplacer)}`;break;case Wo.unrecognized_keys:n=`Unrecognized key(s) in object: ${No.joinValues(e.keys,", ")}`;break;case Wo.invalid_union:n="Invalid input";break;case Wo.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${No.joinValues(e.options)}`;break;case Wo.invalid_enum_value:n=`Invalid enum value. Expected ${No.joinValues(e.options)}, received '${e.received}'`;break;case Wo.invalid_arguments:n="Invalid function arguments";break;case Wo.invalid_return_type:n="Invalid function return type";break;case Wo.invalid_date:n="Invalid date";break;case Wo.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:No.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Wo.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Wo.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Wo.custom:n="Invalid input";break;case Wo.invalid_intersection_types:n="Intersection results could not be merged";break;case Wo.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Wo.not_finite:n="Number must be finite";break;default:n=t.defaultError,No.assertNever(e)}return{message:n}};let Jo=Ho;function Yo(e,t){const n=Jo,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ho?void 0:Ho].filter(e=>!!e)});e.common.issues.push(r)}class Xo{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return Qo;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return Xo.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return Qo;if("aborted"===s.status)return Qo;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const Qo=Object.freeze({status:"aborted"}),ec=e=>({status:"dirty",value:e}),tc=e=>({status:"valid",value:e}),nc=e=>"aborted"===e.status,rc=e=>"dirty"===e.status,sc=e=>"valid"===e.status,ic=e=>"undefined"!=typeof Promise&&e instanceof Promise;var ac;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(ac||(ac={}));class oc{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const cc=(e,t)=>{if(sc(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Go(e.common.issues);return this._error=t,this._error}}};function uc(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??n??s.defaultError}},description:s}}class dc{get description(){return this._def.description}_getType(e){return Zo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Zo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Xo,ctx:{common:e.parent.common,data:e.data,parsedType:Zo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ic(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zo(e)},r=this._parseSync({data:e,path:n.path,parent:n});return cc(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zo(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return sc(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>sc(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zo(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(ic(r)?r:Promise.resolve(r));return cc(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),i=()=>r.addIssue({code:Wo.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new uu({schema:this,typeName:bu.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return du.create(this,this._def)}nullable(){return lu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wc.create(this)}promise(){return cu.create(this,this._def)}or(e){return Jc.create([this,e],this._def)}and(e){return Xc.create(this,e,this._def)}transform(e){return new uu({...uc(this._def),schema:this,typeName:bu.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new hu({...uc(this._def),innerType:this,defaultValue:t,typeName:bu.ZodDefault})}brand(){return new gu({typeName:bu.ZodBranded,type:this,...uc(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new fu({...uc(this._def),innerType:this,catchValue:t,typeName:bu.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return mu.create(this,e)}readonly(){return yu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const lc=/^c[^\s-]{8,}$/i,hc=/^[0-9a-z]+$/,fc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gc=/^[a-z0-9_-]{21}$/i,mc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yc=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let wc;const vc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ec=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,kc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Sc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Oc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ic="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Tc=new RegExp(`^${Ic}$`);function _c(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Ac(e){return new RegExp(`^${_c(e)}$`)}function Cc(e){let t=`${Ic}T${_c(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function jc(e,t){return!("v4"!==t&&t||!vc.test(e))||!("v6"!==t&&t||!kc.test(e))}function Pc(e,t){if(!mc.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function Bc(e,t){return!("v4"!==t&&t||!Ec.test(e))||!("v6"!==t&&t||!Sc.test(e))}class Nc extends dc{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==qo.string){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.string,received:t.parsedType}),Qo}const t=new Xo;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,i=e.data.length<r.value;(s||i)&&(n=this._getOrReturnCtx(e,n),s?Yo(n,{code:Wo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):i&&Yo(n,{code:Wo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)bc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"email",code:Wo.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)wc||(wc=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"emoji",code:Wo.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)pc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"uuid",code:Wo.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)gc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"nanoid",code:Wo.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)lc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"cuid",code:Wo.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)hc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"cuid2",code:Wo.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)fc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"ulid",code:Wo.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),Yo(n,{validation:"url",code:Wo.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"regex",code:Wo.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){Cc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Tc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Ac(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?yc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"duration",code:Wo.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?jc(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"ip",code:Wo.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Pc(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"jwt",code:Wo.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Bc(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"cidr",code:Wo.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Oc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"base64",code:Wo.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?xc.test(e.data)||(n=this._getOrReturnCtx(e,n),Yo(n,{validation:"base64url",code:Wo.invalid_string,message:r.message}),t.dirty()):No.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Wo.invalid_string,...ac.errToObj(n)})}_addCheck(e){return new Nc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ac.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ac.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ac.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ac.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ac.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ac.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ac.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ac.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ac.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ac.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ac.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ac.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ac.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ac.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...ac.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ac.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ac.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ac.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ac.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ac.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ac.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ac.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ac.errToObj(t)})}nonempty(e){return this.min(1,ac.errToObj(e))}trim(){return new Nc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Nc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Nc({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Rc(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Nc.create=e=>new Nc({checks:[],typeName:bu.ZodString,coerce:e?.coerce??!1,...uc(e)});class $c extends dc{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==qo.number){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.number,received:t.parsedType}),Qo}let t;const n=new Xo;for(const r of this._def.checks)if("int"===r.kind)No.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==Rc(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.not_finite,message:r.message}),n.dirty()):No.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ac.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ac.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ac.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ac.toString(t))}setLimit(e,t,n,r){return new $c({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ac.toString(r)}]})}_addCheck(e){return new $c({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ac.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ac.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ac.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ac.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ac.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ac.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ac.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ac.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ac.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&No.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}$c.create=e=>new $c({checks:[],typeName:bu.ZodNumber,coerce:e?.coerce||!1,...uc(e)});class Mc extends dc{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==qo.bigint)return this._getInvalidInput(e);let t;const n=new Xo;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Yo(t,{code:Wo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):No.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.bigint,received:t.parsedType}),Qo}gte(e,t){return this.setLimit("min",e,!0,ac.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ac.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ac.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ac.toString(t))}setLimit(e,t,n,r){return new Mc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ac.toString(r)}]})}_addCheck(e){return new Mc({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ac.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ac.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ac.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ac.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ac.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Mc.create=e=>new Mc({checks:[],typeName:bu.ZodBigInt,coerce:e?.coerce??!1,...uc(e)});class Uc extends dc{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==qo.boolean){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.boolean,received:t.parsedType}),Qo}return tc(e.data)}}Uc.create=e=>new Uc({typeName:bu.ZodBoolean,coerce:e?.coerce||!1,...uc(e)});class Dc extends dc{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==qo.date){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.date,received:t.parsedType}),Qo}if(Number.isNaN(e.data.getTime())){return Yo(this._getOrReturnCtx(e),{code:Wo.invalid_date}),Qo}const t=new Xo;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),Yo(n,{code:Wo.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):No.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Dc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ac.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ac.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Dc.create=e=>new Dc({checks:[],coerce:e?.coerce||!1,typeName:bu.ZodDate,...uc(e)});class Fc extends dc{_parse(e){if(this._getType(e)!==qo.symbol){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.symbol,received:t.parsedType}),Qo}return tc(e.data)}}Fc.create=e=>new Fc({typeName:bu.ZodSymbol,...uc(e)});class Lc extends dc{_parse(e){if(this._getType(e)!==qo.undefined){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.undefined,received:t.parsedType}),Qo}return tc(e.data)}}Lc.create=e=>new Lc({typeName:bu.ZodUndefined,...uc(e)});class Vc extends dc{_parse(e){if(this._getType(e)!==qo.null){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.null,received:t.parsedType}),Qo}return tc(e.data)}}Vc.create=e=>new Vc({typeName:bu.ZodNull,...uc(e)});class Kc extends dc{constructor(){super(...arguments),this._any=!0}_parse(e){return tc(e.data)}}Kc.create=e=>new Kc({typeName:bu.ZodAny,...uc(e)});class zc extends dc{constructor(){super(...arguments),this._unknown=!0}_parse(e){return tc(e.data)}}zc.create=e=>new zc({typeName:bu.ZodUnknown,...uc(e)});class qc extends dc{_parse(e){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.never,received:t.parsedType}),Qo}}qc.create=e=>new qc({typeName:bu.ZodNever,...uc(e)});class Zc extends dc{_parse(e){if(this._getType(e)!==qo.undefined){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.void,received:t.parsedType}),Qo}return tc(e.data)}}Zc.create=e=>new Zc({typeName:bu.ZodVoid,...uc(e)});class Wc extends dc{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==qo.array)return Yo(t,{code:Wo.invalid_type,expected:qo.array,received:t.parsedType}),Qo;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(Yo(t,{code:e?Wo.too_big:Wo.too_small,minimum:s?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(Yo(t,{code:Wo.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(Yo(t,{code:Wo.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new oc(t,e,t.path,n)))).then(e=>Xo.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new oc(t,e,t.path,n)));return Xo.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new Wc({...this._def,minLength:{value:e,message:ac.toString(t)}})}max(e,t){return new Wc({...this._def,maxLength:{value:e,message:ac.toString(t)}})}length(e,t){return new Wc({...this._def,exactLength:{value:e,message:ac.toString(t)}})}nonempty(e){return this.min(1,e)}}function Gc(e){if(e instanceof Hc){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=du.create(Gc(r))}return new Hc({...e._def,shape:()=>t})}return e instanceof Wc?new Wc({...e._def,type:Gc(e.element)}):e instanceof du?du.create(Gc(e.unwrap())):e instanceof lu?lu.create(Gc(e.unwrap())):e instanceof Qc?Qc.create(e.items.map(e=>Gc(e))):e}Wc.create=(e,t)=>new Wc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:bu.ZodArray,...uc(t)});class Hc extends dc{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=No.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==qo.object){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.object,received:t.parsedType}),Qo}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof qc&&"strip"===this._def.unknownKeys))for(const e in n.data)s.includes(e)||i.push(e);const a=[];for(const e of s){const t=r[e],s=n.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new oc(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof qc){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)i.length>0&&(Yo(n,{code:Wo.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const r=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new oc(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Xo.mergeObjectSync(t,e)):Xo.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return ac.errToObj,new Hc({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:ac.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new Hc({...this._def,unknownKeys:"strip"})}passthrough(){return new Hc({...this._def,unknownKeys:"passthrough"})}extend(e){return new Hc({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Hc({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:bu.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Hc({...this._def,catchall:e})}pick(e){const t={};for(const n of No.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Hc({...this._def,shape:()=>t})}omit(e){const t={};for(const n of No.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Hc({...this._def,shape:()=>t})}deepPartial(){return Gc(this)}partial(e){const t={};for(const n of No.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new Hc({...this._def,shape:()=>t})}required(e){const t={};for(const n of No.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof du;)e=e._def.innerType;t[n]=e}return new Hc({...this._def,shape:()=>t})}keyof(){return iu(No.objectKeys(this.shape))}}Hc.create=(e,t)=>new Hc({shape:()=>e,unknownKeys:"strip",catchall:qc.create(),typeName:bu.ZodObject,...uc(t)}),Hc.strictCreate=(e,t)=>new Hc({shape:()=>e,unknownKeys:"strict",catchall:qc.create(),typeName:bu.ZodObject,...uc(t)}),Hc.lazycreate=(e,t)=>new Hc({shape:e,unknownKeys:"strip",catchall:qc.create(),typeName:bu.ZodObject,...uc(t)});class Jc extends dc{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new Go(e.ctx.common.issues));return Yo(t,{code:Wo.invalid_union,unionErrors:n}),Qo});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new Go(e));return Yo(t,{code:Wo.invalid_union,unionErrors:s}),Qo}}get options(){return this._def.options}}function Yc(e,t){const n=Zo(e),r=Zo(t);if(e===t)return{valid:!0,data:e};if(n===qo.object&&r===qo.object){const n=No.objectKeys(t),r=No.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Yc(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===qo.array&&r===qo.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=Yc(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===qo.date&&r===qo.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Jc.create=(e,t)=>new Jc({options:e,typeName:bu.ZodUnion,...uc(t)});class Xc extends dc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(nc(e)||nc(r))return Qo;const s=Yc(e.value,r.value);return s.valid?((rc(e)||rc(r))&&t.dirty(),{status:t.value,value:s.data}):(Yo(n,{code:Wo.invalid_intersection_types}),Qo)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Xc.create=(e,t,n)=>new Xc({left:e,right:t,typeName:bu.ZodIntersection,...uc(n)});class Qc extends dc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==qo.array)return Yo(n,{code:Wo.invalid_type,expected:qo.array,received:n.parsedType}),Qo;if(n.data.length<this._def.items.length)return Yo(n,{code:Wo.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Qo;!this._def.rest&&n.data.length>this._def.items.length&&(Yo(n,{code:Wo.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new oc(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Xo.mergeArray(t,e)):Xo.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Qc({...this._def,rest:e})}}Qc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qc({items:e,typeName:bu.ZodTuple,rest:null,...uc(t)})};class eu extends dc{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==qo.object)return Yo(n,{code:Wo.invalid_type,expected:qo.object,received:n.parsedType}),Qo;const r=[],s=this._def.keyType,i=this._def.valueType;for(const e in n.data)r.push({key:s._parse(new oc(n,e,n.path,e)),value:i._parse(new oc(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Xo.mergeObjectAsync(t,r):Xo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new eu(t instanceof dc?{keyType:e,valueType:t,typeName:bu.ZodRecord,...uc(n)}:{keyType:Nc.create(),valueType:e,typeName:bu.ZodRecord,...uc(t)})}}class tu extends dc{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==qo.map)return Yo(n,{code:Wo.invalid_type,expected:qo.map,received:n.parsedType}),Qo;const r=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([e,t],i)=>({key:r._parse(new oc(n,e,n.path,[i,"key"])),value:s._parse(new oc(n,t,n.path,[i,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of i){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return Qo;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of i){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return Qo;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}tu.create=(e,t,n)=>new tu({valueType:t,keyType:e,typeName:bu.ZodMap,...uc(n)});class nu extends dc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==qo.set)return Yo(n,{code:Wo.invalid_type,expected:qo.set,received:n.parsedType}),Qo;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(Yo(n,{code:Wo.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(Yo(n,{code:Wo.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const n=new Set;for(const r of e){if("aborted"===r.status)return Qo;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>s._parse(new oc(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new nu({...this._def,minSize:{value:e,message:ac.toString(t)}})}max(e,t){return new nu({...this._def,maxSize:{value:e,message:ac.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}nu.create=(e,t)=>new nu({valueType:e,minSize:null,maxSize:null,typeName:bu.ZodSet,...uc(t)});class ru extends dc{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ru.create=(e,t)=>new ru({getter:e,typeName:bu.ZodLazy,...uc(t)});class su extends dc{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Yo(t,{received:t.data,code:Wo.invalid_literal,expected:this._def.value}),Qo}return{status:"valid",value:e.data}}get value(){return this._def.value}}function iu(e,t){return new au({values:e,typeName:bu.ZodEnum,...uc(t)})}su.create=(e,t)=>new su({value:e,typeName:bu.ZodLiteral,...uc(t)});class au extends dc{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return Yo(t,{expected:No.joinValues(n),received:t.parsedType,code:Wo.invalid_type}),Qo}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return Yo(t,{received:t.data,code:Wo.invalid_enum_value,options:n}),Qo}return tc(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return au.create(e,{...this._def,...t})}exclude(e,t=this._def){return au.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}au.create=iu;class ou extends dc{_parse(e){const t=No.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==qo.string&&n.parsedType!==qo.number){const e=No.objectValues(t);return Yo(n,{expected:No.joinValues(e),received:n.parsedType,code:Wo.invalid_type}),Qo}if(this._cache||(this._cache=new Set(No.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=No.objectValues(t);return Yo(n,{received:n.data,code:Wo.invalid_enum_value,options:e}),Qo}return tc(e.data)}get enum(){return this._def.values}}ou.create=(e,t)=>new ou({values:e,typeName:bu.ZodNativeEnum,...uc(t)});class cu extends dc{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==qo.promise&&!1===t.common.async)return Yo(t,{code:Wo.invalid_type,expected:qo.promise,received:t.parsedType}),Qo;const n=t.parsedType===qo.promise?t.data:Promise.resolve(t.data);return tc(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}cu.create=(e,t)=>new cu({type:e,typeName:bu.ZodPromise,...uc(t)});class uu extends dc{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===bu.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:e=>{Yo(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===r.type){const e=r.transform(n.data,s);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Qo;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?Qo:"dirty"===r.status||"dirty"===t.value?ec(r.value):r});{if("aborted"===t.value)return Qo;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?Qo:"dirty"===r.status||"dirty"===t.value?ec(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,s);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?Qo:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Qo:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!sc(e))return Qo;const i=r.transform(e.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>sc(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):Qo)}No.assertNever(r)}}uu.create=(e,t,n)=>new uu({schema:e,typeName:bu.ZodEffects,effect:t,...uc(n)}),uu.createWithPreprocess=(e,t,n)=>new uu({schema:t,effect:{type:"preprocess",transform:e},typeName:bu.ZodEffects,...uc(n)});class du extends dc{_parse(e){return this._getType(e)===qo.undefined?tc(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}du.create=(e,t)=>new du({innerType:e,typeName:bu.ZodOptional,...uc(t)});class lu extends dc{_parse(e){return this._getType(e)===qo.null?tc(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}lu.create=(e,t)=>new lu({innerType:e,typeName:bu.ZodNullable,...uc(t)});class hu extends dc{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===qo.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}hu.create=(e,t)=>new hu({innerType:e,typeName:bu.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...uc(t)});class fu extends dc{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ic(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Go(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Go(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}fu.create=(e,t)=>new fu({innerType:e,typeName:bu.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...uc(t)});class pu extends dc{_parse(e){if(this._getType(e)!==qo.nan){const t=this._getOrReturnCtx(e);return Yo(t,{code:Wo.invalid_type,expected:qo.nan,received:t.parsedType}),Qo}return{status:"valid",value:e.data}}}pu.create=e=>new pu({typeName:bu.ZodNaN,...uc(e)});class gu extends dc{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class mu extends dc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Qo:"dirty"===e.status?(t.dirty(),ec(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Qo:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new mu({in:e,out:t,typeName:bu.ZodPipeline})}}class yu extends dc{_parse(e){const t=this._def.innerType._parse(e),n=e=>(sc(e)&&(e.value=Object.freeze(e.value)),e);return ic(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var bu;yu.create=(e,t)=>new yu({innerType:e,typeName:bu.ZodReadonly,...uc(t)}),Hc.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(bu||(bu={}));const wu=Nc.create,vu=$c.create;pu.create,Mc.create;const Eu=Uc.create;Dc.create,Fc.create,Lc.create,Vc.create,Kc.create,zc.create,qc.create;const ku=Zc.create,Su=Wc.create,Ou=Hc.create;Hc.strictCreate,Jc.create,Xc.create,Qc.create;const xu=eu.create;tu.create,nu.create,ru.create,su.create;const Iu=au.create;function Tu(e,t){let n={...e};for(let e of t)delete n[e];return n}ou.create,cu.create,uu.create,du.create,lu.create,uu.createWithPreprocess;var _u=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;function Au(e){let t=e.url,n=e.params;return n&&(t=t.replace(_u,(e,t)=>t in n?`${n[t]}`:e)),t}function Cu(e,t,n){return e.find(e=>e.method===t&&e.path===n)}var ju=class extends Error{constructor(e,t,n,r){super(e),this.config=t,this.data=n,this.cause=r}},Pu={name:"form-data",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new ju("Zodios: multipart/form-data body must be an object",t);let n=function(e){let t=new FormData;for(let n in e)t.append(n,e[n]);return{data:t}}(t.data);return{...t,data:n.data,headers:{...t.headers,...n.headers}}}};var Bu={name:"form-url",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new ju("Zodios: application/x-www-form-urlencoded body must be an object",t);return{...t,data:new URLSearchParams(t.data).toString(),headers:{...t.headers,"Content-Type":"application/x-www-form-urlencoded"}}}};function Nu(e,t){return{request:async(n,r)=>({...r,headers:{...r.headers,[e]:t}})}}function Ru(e){return[!0,"response","all"].includes(e)}function $u(e){return[!0,"request","all"].includes(e)}var Mu=class{constructor(e,t){this.plugins=[],this.key=`${e}-${t}`}indexOf(e){return this.plugins.findIndex(t=>(null==t?void 0:t.name)===e)}use(e){if(e.name){let t=this.indexOf(e.name);if(-1!==t)return this.plugins[t]=e,{key:this.key,value:t}}return this.plugins.push(e),{key:this.key,value:this.plugins.length-1}}eject(e){if("string"==typeof e){let t=this.indexOf(e);if(-1===t)throw new Error(`Plugin with name '${e}' not found`);this.plugins[t]=void 0}else{if(e.key!==this.key)throw new Error(`Plugin with key '${e.key}' is not registered for endpoint '${this.key}'`);this.plugins[e.value]=void 0}}async interceptRequest(e,t){let n=t;for(let t of this.plugins)null!=t&&t.request&&(n=await t.request(e,n));return n}async interceptResponse(e,t,n){let r=n;for(let n=this.plugins.length-1;n>=0;n--){let s=this.plugins[n];s&&(r=r.then(null!=s&&s.response?n=>s.response(e,t,n):void 0,null!=s&&s.error?n=>s.error(e,t,n):void 0))}return r}count(){return this.plugins.reduce((e,t)=>t?e+1:e,0)}};function Uu(e){let t=new Set;for(let n of e){let e=`${n.method} ${n.path}`;if(t.has(e))throw new Error(`Zodios: Duplicate path '${e}'`);t.add(e)}let n=new Set;for(let t of e)if(t.alias){if(n.has(t.alias))throw new Error(`Zodios: Duplicate alias '${t.alias}'`);n.add(t.alias)}for(let t of e)if(t.parameters&&t.parameters.filter(e=>"Body"===e.type).length>1)throw new Error(`Zodios: Multiple body parameters in endpoint '${t.path}'`)}var Du=class{constructor(e,t,n){let r,s;if(this.endpointPlugins=new Map,!e)throw Array.isArray(t)?new Error("Zodios: missing base url"):new Error("Zodios: missing api description");if("string"==typeof e&&Array.isArray(t))s=e,this.api=t,r=n||{};else{if(!Array.isArray(e)||Array.isArray(t))throw new Error("Zodios: api must be an array");this.api=e,r=t||{}}Uu(this.api),this.options={validate:!0,transform:!0,sendDefaults:!1,...r},this.options.axiosInstance?this.axiosInstance=this.options.axiosInstance:this.axiosInstance=i.create({...this.options.axiosConfig}),s&&(this.axiosInstance.defaults.baseURL=s),this.injectAliasEndpoints(),this.initPlugins(),[!0,"all","request","response"].includes(this.options.validate)&&this.use(function({validate:e,transform:t,sendDefaults:n}){return{name:"zod-validation",request:$u(e)?async(e,r)=>{let s=Cu(e,r.method,r.url);if(!s)throw new Error(`No endpoint found for ${r.method} ${r.url}`);let{parameters:i}=s;if(!i)return r;let a={...r,queries:{...r.queries},headers:{...r.headers},params:{...r.params}},o={Query:e=>{var t;return null==(t=a.queries)?void 0:t[e]},Body:e=>a.data,Header:e=>{var t;return null==(t=a.headers)?void 0:t[e]},Path:e=>{var t;return null==(t=a.params)?void 0:t[e]}},c={Query:(e,t)=>a.queries[e]=t,Body:(e,t)=>a.data=t,Header:(e,t)=>a.headers[e]=t,Path:(e,t)=>a.params[e]=t},u=$u(t);for(let e of i){let{name:t,schema:s,type:i}=e,a=o[i](t);if(n||void 0!==a){let e=await s.safeParseAsync(a);if(!e.success)throw new ju(`Zodios: Invalid ${i} parameter '${t}'`,r,a,e.error);u&&c[i](t,e.data)}}return a}:void 0,response:Ru(e)?async(e,n,r)=>{var s,i,a,o;let c=Cu(e,n.method,n.url);if(!c)throw new Error(`No endpoint found for ${n.method} ${n.url}`);if((null==(i=null==(s=r.headers)?void 0:s["content-type"])?void 0:i.includes("application/json"))||(null==(o=null==(a=r.headers)?void 0:a["content-type"])?void 0:o.includes("application/vnd.api+json"))){let e=await c.response.safeParseAsync(r.data);if(!e.success)throw new ju(`Zodios: Invalid response from endpoint '${c.method} ${c.path}'\nstatus: ${r.status} ${r.statusText}\ncause:\n${e.error.message}\nreceived:\n${JSON.stringify(r.data,null,2)}`,n,r.data,e.error);Ru(t)&&(r.data=e.data)}return r}:void 0}}(this.options))}initPlugins(){this.endpointPlugins.set("any-any",new Mu("any","any")),this.api.forEach(e=>{let t=new Mu(e.method,e.path);switch(e.requestFormat){case"binary":t.use(Nu("Content-Type","application/octet-stream"));break;case"form-data":t.use(Pu);break;case"form-url":t.use(Bu);break;case"text":t.use(Nu("Content-Type","text/plain"))}this.endpointPlugins.set(`${e.method}-${e.path}`,t)})}getAnyEndpointPlugins(){return this.endpointPlugins.get("any-any")}findAliasEndpointPlugins(e){let t=this.api.find(t=>t.alias===e);if(t)return this.endpointPlugins.get(`${t.method}-${t.path}`)}findEnpointPlugins(e,t){return this.endpointPlugins.get(`${e}-${t}`)}get baseURL(){return this.axiosInstance.defaults.baseURL}get axios(){return this.axiosInstance}use(...e){if("object"==typeof e[0])return this.getAnyEndpointPlugins().use(e[0]);if("string"==typeof e[0]&&"object"==typeof e[1]){let t=this.findAliasEndpointPlugins(e[0]);if(!t)throw new Error(`Zodios: no alias '${e[0]}' found to register plugin`);return t.use(e[1])}if("string"==typeof e[0]&&"string"==typeof e[1]&&"object"==typeof e[2]){let t=this.findEnpointPlugins(e[0],e[1]);if(!t)throw new Error(`Zodios: no endpoint '${e[0]} ${e[1]}' found to register plugin`);return t.use(e[2])}throw new Error("Zodios: invalid plugin registration")}eject(e){var t;"string"!=typeof e?null==(t=this.endpointPlugins.get(e.key))||t.eject(e):this.getAnyEndpointPlugins().eject(e)}injectAliasEndpoints(){this.api.forEach(e=>{e.alias&&(["post","put","patch","delete"].includes(e.method)?this[e.alias]=(t,n)=>this.request({...n,method:e.method,url:e.path,data:t}):this[e.alias]=t=>this.request({...t,method:e.method,url:e.path}))})}async request(e){let t=e,n=this.getAnyEndpointPlugins(),r=this.findEnpointPlugins(t.method,t.url);t=await n.interceptRequest(this.api,t),r&&(t=await r.interceptRequest(this.api,t));let s=this.axiosInstance.request({...Tu(t,["params","queries"]),url:Au(t),params:t.queries});return r&&(s=r.interceptResponse(this.api,t,s)),s=n.interceptResponse(this.api,t,s),(await s).data}async get(e,...[t]){return this.request({...t,method:"get",url:e})}async post(e,t,...[n]){return this.request({...n,method:"post",url:e,data:t})}async put(e,t,...[n]){return this.request({...n,method:"put",url:e,data:t})}async patch(e,t,...[n]){return this.request({...n,method:"patch",url:e,data:t})}async delete(e,t,...[n]){return this.request({...n,method:"delete",url:e,data:t})}};const Fu=Iu(["crypto","fx","equity","metal","rates","crypto_redemption_rate","commodities","crypto_index","crypto_nav"]),Lu=Fu.nullish(),Vu=wu(),Ku=Ou({attributes:xu(wu()),id:Vu}).passthrough(),zu=wu(),qu=Iu(["hex","base64"]),Zu=Ou({data:Su(wu()),encoding:qu}).passthrough(),Wu=Ou({conf:wu(),expo:vu().int(),price:wu(),publish_time:vu().int()}).passthrough(),Gu=Ou({prev_publish_time:vu().int().nullable(),proof_available_time:vu().int().nullable(),slot:vu().int().gte(0).nullable()}).partial().passthrough(),Hu=Ou({ema_price:Wu,id:Vu,metadata:Gu,price:Wu}).passthrough(),Ju=Ou({binary:Zu,parsed:Su(Hu).nullish()}).passthrough(),Yu=Ou({cap:vu().int().gte(0),publisher:wu()}).passthrough(),Xu=Ou({publisher_stake_caps:Su(Yu)}).passthrough(),Qu=Ou({binary:Zu,parsed:Su(Xu).nullish()}).passthrough(),ed=Ou({down_slots_ratio:wu(),end_timestamp:vu().int(),id:Vu,start_timestamp:vu().int(),twap:Wu}).passthrough(),td=Ou({binary:Zu,parsed:Su(ed).nullish()}).passthrough(),nd={AssetType:Fu,asset_type:Lu,RpcPriceIdentifier:Vu,PriceFeedMetadata:Ku,PriceIdInput:zu,EncodingType:qu,BinaryUpdate:Zu,RpcPrice:Wu,RpcPriceFeedMetadataV2:Gu,ParsedPriceUpdate:Hu,PriceUpdate:Ju,ParsedPublisherStakeCap:Yu,ParsedPublisherStakeCapsUpdate:Xu,LatestPublisherStakeCapsUpdateDataResponse:Qu,ParsedPriceFeedTwap:ed,TwapsResponse:td};var rd;new Du((Uu(rd=[{method:"get",path:"/v2/price_feeds",alias:"price_feeds_metadata",description:"Get the set of price feeds.\n\nThis endpoint fetches all price feeds from the Pyth network. It can be filtered by asset type\nand query string.",requestFormat:"json",parameters:[{name:"query",type:"Query",schema:wu().nullish()},{name:"asset_type",type:"Query",schema:Lu}],response:Su(Ku)},{method:"get",path:"/v2/updates/price/:publish_time",alias:"timestamp_price_updates",description:"Get the latest price updates by price feed id.\n\nGiven a collection of price feed ids, retrieve the latest Pyth price for each price feed.",requestFormat:"json",parameters:[{name:"publish_time",type:"Path",schema:vu().int()},{name:"ids[]",type:"Query",schema:Su(zu)},{name:"encoding",type:"Query",schema:Iu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Eu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Eu().optional()}],response:Ju,errors:[{status:404,description:"Price ids not found",schema:ku()}]},{method:"get",path:"/v2/updates/price/latest",alias:"latest_price_updates",description:"Get the latest price updates by price feed id.\n\nGiven a collection of price feed ids, retrieve the latest Pyth price for each price feed.",requestFormat:"json",parameters:[{name:"ids[]",type:"Query",schema:Su(zu)},{name:"encoding",type:"Query",schema:Iu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Eu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Eu().optional()}],response:Ju,errors:[{status:404,description:"Price ids not found",schema:ku()}]},{method:"get",path:"/v2/updates/price/stream",alias:"price_stream_sse_handler",description:"SSE route handler for streaming price updates.\n\nThe connection will automatically close after 24 hours to prevent resource leaks.\nClients should implement reconnection logic to maintain continuous price updates.",requestFormat:"json",parameters:[{name:"ids[]",type:"Query",schema:Su(zu)},{name:"encoding",type:"Query",schema:Iu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Eu().optional()},{name:"allow_unordered",type:"Query",schema:Eu().optional()},{name:"benchmarks_only",type:"Query",schema:Eu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Eu().optional()}],response:Ju,errors:[{status:404,description:"Price ids not found",schema:ku()}]},{method:"get",path:"/v2/updates/publisher_stake_caps/latest",alias:"latest_publisher_stake_caps",description:"Get the most recent publisher stake caps update data.",requestFormat:"json",parameters:[{name:"encoding",type:"Query",schema:Iu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Eu().optional()}],response:Qu},{method:"get",path:"/v2/updates/twap/:window_seconds/latest",alias:"latest_twaps",description:"Get the latest TWAP by price feed id with a custom time window.\n\nGiven a collection of price feed ids, retrieve the latest Pyth TWAP price for each price feed.",requestFormat:"json",parameters:[{name:"window_seconds",type:"Path",schema:vu().int().gte(0)},{name:"ids[]",type:"Query",schema:Su(zu)},{name:"encoding",type:"Query",schema:Iu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Eu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Eu().optional()}],response:td,errors:[{status:404,description:"Price ids not found",schema:ku()}]}]),rd));class sd{baseURL;timeout;httpRetries;headers;constructor(e,t){this.baseURL=e,this.timeout=t?.timeout??5e3,this.httpRetries=t?.httpRetries??3,this.headers=t?.headers??{}}async httpRequest(e,t,n,r=this.httpRetries,s=100+Math.floor(100*Math.random())){try{const r=await fetch(e,{...n,signal:AbortSignal.any([...n?.signal?[n.signal]:[],AbortSignal.timeout(this.timeout)]),headers:{...this.headers,...n?.headers}});if(!r.ok){const e=await r.text();throw new Error(`HTTP error! status: ${r.status.toString()}${e?`, body: ${e}`:""}`)}const s=await r.json();return t.parse(s)}catch(i){if(r>0&&!(i instanceof Error&&"AbortError"===i.name))return await new Promise(e=>setTimeout(e,s)),this.httpRequest(e,t,n,r-1,2*s);throw i}}async getPriceFeeds({fetchOptions:e,...t}={}){const n=this.buildURL("price_feeds");if(t){const e=zo(t);this.appendUrlSearchParams(n,e)}return await this.httpRequest(n.toString(),nd.PriceFeedMetadata.array(),e)}async getLatestPublisherCaps({fetchOptions:e,...t}={}){const n=this.buildURL("updates/publisher_stake_caps/latest");return t&&this.appendUrlSearchParams(n,t),await this.httpRequest(n.toString(),nd.LatestPublisherStakeCapsUpdateDataResponse,e)}async getLatestPriceUpdates(e,t,n){const r=this.buildURL("updates/price/latest");for(const t of e)r.searchParams.append("ids[]",t);if(t){const e=zo(t);this.appendUrlSearchParams(r,e)}return this.httpRequest(r.toString(),nd.PriceUpdate,n)}async getPriceUpdatesAtTimestamp(e,t,n,r){const s=this.buildURL(`updates/price/${e.toString()}`);for(const e of t)s.searchParams.append("ids[]",e);if(n){const e=zo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),nd.PriceUpdate,r)}async getPriceUpdatesStream(e,t){const n=this.buildURL("updates/price/stream");for(const t of e)n.searchParams.append("ids[]",t);if(t){const e=zo(t);this.appendUrlSearchParams(n,e)}return new Vo(n.toString(),{fetch:(e,t)=>fetch(e,{...t,headers:{...t?.headers,...this.headers}})})}async getLatestTwaps(e,t,n,r){const s=this.buildURL(`updates/twap/${t.toString()}/latest`);for(const t of e)s.searchParams.append("ids[]",t);if(n){const e=zo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),nd.TwapsResponse,r)}appendUrlSearchParams(e,t){for(const[n,r]of Object.entries(t))void 0!==r&&e.searchParams.append(n,String(r))}buildURL(e){return new URL(`./v2/${e}`,`${this.baseURL}${this.baseURL.endsWith("/")?"":"/"}`)}}class id extends sd{async getPriceFeedsUpdateData(e){return(await this.getLatestPriceUpdates(e,{encoding:"base64",parsed:!1})).binary.data.map(e=>s.from(e,"base64"))}}const ad=16384;class od{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(e,t,n){this.provider=e,this.pythStateId=t,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(void 0===this.baseUpdateFee){const e=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!e.data?.content||"moveObject"!==e.data.content.dataType)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=e.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(e){const t=await this.provider.getObject({id:e,options:{showContent:!0}}).then(t=>{if("moveObject"==t.data?.content?.dataType)return t.data.content.fields;throw new Error(`Cannot fetch package id for object ${e}`)});if("upgrade_cap"in t)return t.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(e,t){const n=await this.getWormholePackageId(),r=[];for(const s of e){const[e]=t.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[t.object(this.wormholeStateId),t.pure(xr.vector(xr.U8).serialize([...s],{maxSize:ad}).toBytes()),t.object(ns)]});r.push(e)}return r}async verifyVaasAndGetHotPotato(e,t,n){if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");const r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e),[i]=e.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[e.object(this.pythStateId),e.pure(xr.vector(xr.U8).serialize([...t[0]],{maxSize:ad}).toBytes()),s[0],e.object(ns)]});return i}async executePriceFeedUpdates(e,t,n,r,s){const i=[];let a=0;for(const o of n){const n=await this.getPriceFeedObjectId(o);if(!n)throw new Error(`Price feed ${o} not found, please create it first`);i.push(n),[r]=e.moveCall({target:`${t}::pyth::update_single_price_feed`,arguments:[e.object(this.pythStateId),r,e.object(n),s[a],e.object(ns)]}),a++}return e.moveCall({target:`${t}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${t}::price_info::PriceInfo`]}),i}async updatePriceFeeds(e,t,n){const r=await this.getPythPackageId(),s=await this.verifyVaasAndGetHotPotato(e,t,r),i=await this.getBaseUpdateFee(),a=e.splitCoins(e.gas,n.map(()=>e.pure.u64(i)));return await this.executePriceFeedUpdates(e,r,n,s,a)}async updatePriceFeedsWithCoins(e,t,n,r){const s=await this.getPythPackageId(),i=await this.verifyVaasAndGetHotPotato(e,t,s);return await this.executePriceFeedUpdates(e,s,n,i,r)}async createPriceFeed(e,t){const n=await this.getPythPackageId();if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");const r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e);e.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[e.object(this.pythStateId),e.pure(xr.vector(xr.U8).serialize([...t[0]],{maxSize:ad}).toBytes()),s[0],e.object(ns)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(e){const t=e.replace("0x","");if(!this.priceFeedObjectIdCache.has(t)){const{id:e,fieldType:n}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:e,name:{type:`${n}::price_identifier::PriceIdentifier`,value:{bytes:[...s.from(t,"hex")]}}});if(!r.data?.content)return;if("moveObject"!==r.data.content.dataType)throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(t,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(t)}async getPriceTableInfo(){if(void 0===this.priceTableInfo){const e=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!e.data?.type)throw new Error("Price Table not found, contract may not be initialized");let t=e.data.type.replace("0x2::table::Table<","");t=t.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:e.data.objectId,fieldType:t}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(e){const t=7+e.readUint8(6)+1,n=e.readUint16BE(t),r=t+2;return e.subarray(r,r+n)}}const cd=.05,ud={AUTHORIZE:"/api/authorize",PLACE_ORDER:"/api/perp-trade-api/trade/placeorder",CANCEL_ORDER:"/api/perp-trade-api/trade/cancelorder",PLAN_CLOSE_ORDER:"/api/perp-trade-api/plan/batch/plancloseorder",CANCEL_PLAN_ORDER:"/api/perp-trade-api/plan/cancelplanorder",ADJUST_LEVERAGE:"/api/perp-trade-api/user-config/adjust-leverage",GET_USER_CONFIG:"/api/perp-trade-api/user-config/config",GET_ACCOUNT_INFO:"/api/perp-trade-api/curr-info/account",GET_POSITIONS:"/api/perp-trade-api/curr-info/positions",GET_OPEN_ORDERS:"/api/perp-trade-api/curr-info/orders",GET_TRADING_PAIRS:"/api/perp-market-api/list",GET_ORDER_BOOK:"/api/perp-market-api/orderBook",GET_TICKER:"/api/perp-market-api/ticker",GET_POSITION_TPSL:"/api/perp-trade-api/plan/position/tpsl",HISTORY_ORDERS:"/api/perp-trade-api/history/orders",FUNDING_SETTLEMENTS:"/api/perp-trade-api/history/funding-settlements",BALANCE_CHANGES:"/api/perp-trade-api/history/balance-changes",ORACLE:"/api/perp-market-api/oracle"},dd='{"onboardingUrl":"dipcoin.io"}',ld={USDC:6,SUI:9,DEFAULT:18},hd={mainnet:{wormholeStateId:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pythStateId:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",priceServiceUrl:"https://hermes.pyth.network/"},testnet:{wormholeStateId:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",pythStateId:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",priceServiceUrl:"https://hermes-beta.pyth.network"}};class fd{baseURL;walletAddress;authToken;timeout=30;constructor(e){this.baseURL=e}isPerpTradeApiUrl(e){return e?.startsWith("/api/perp-trade-api")??!1}isPublicEndpoint(e){return e?.includes("/public/")??!1}buildHeaders(e,t="application/json"){const n={"Content-Type":t};return this.isPerpTradeApiUrl(e)&&(this.walletAddress&&(n["X-Wallet-Address"]=this.walletAddress),this.authToken&&!this.isPublicEndpoint(e)&&(n.Authorization=`Bearer ${this.authToken}`)),n}curlRequest(e,t,n,r){return new Promise((s,i)=>{const o=`${this.baseURL}${t}`,c=["-s","-X",e,o,"--max-time",String(this.timeout)];for(const[e,t]of Object.entries(n))c.push("-H",`${e}: ${t}`);r&&c.push("-d",r);const u=a("curl",c);let d="",l="";u.stdout.on("data",e=>{d+=e}),u.stderr.on("data",e=>{l+=e}),u.on("close",e=>{if(!d)return i(new Error(l||`curl exited with code ${e}`));try{s(JSON.parse(d))}catch{i(new Error(`Invalid JSON response: ${d.slice(0,200)}`))}}),u.on("error",e=>i(e))})}setWalletAddress(e){this.walletAddress=e}setAuthToken(e){this.authToken=e}async get(e,t){let n=e;if(t?.params){const e=new URLSearchParams;for(const[n,r]of Object.entries(t.params))null!=r&&e.append(n,String(r));const r=e.toString();r&&(n+=`?${r}`)}return this.curlRequest("GET",n,this.buildHeaders(e))}async post(e,t){const n=t?JSON.stringify(t):void 0;return this.curlRequest("POST",e,this.buildHeaders(e),n)}async postForm(e,t){const n=new URLSearchParams;for(const[e,r]of Object.entries(t))null!=r&&n.append(e,"object"==typeof r?JSON.stringify(r):String(r));return this.curlRequest("POST",e,this.buildHeaders(e,"application/x-www-form-urlencoded"),n.toString())}}var pd,gd;!function(e){e.BUY="BUY",e.SELL="SELL"}(pd||(pd={})),function(e){e.MARKET="MARKET",e.LIMIT="LIMIT"}(gd||(gd={}));const md=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yd=new Uint32Array(64);class bd extends Vs{constructor(e=32){super(64,e,8,!1),this.A=0|Ks[0],this.B=0|Ks[1],this.C=0|Ks[2],this.D=0|Ks[3],this.E=0|Ks[4],this.F=0|Ks[5],this.G=0|Ks[6],this.H=0|Ks[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:a,H:o}=this;return[e,t,n,r,s,i,a,o]}set(e,t,n,r,s,i,a,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)yd[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=yd[e-15],n=yd[e-2],r=ps(t,7)^ps(t,18)^t>>>3,s=ps(n,17)^ps(n,19)^n>>>10;yd[e]=s+yd[e-7]+r+yd[e-16]|0}let{A:n,B:r,C:s,D:i,E:a,F:o,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(ps(a,6)^ps(a,11)^ps(a,25))+Fs(a,o,c)+md[e]+yd[e]|0,d=(ps(n,2)^ps(n,13)^ps(n,22))+Ls(n,r,s)|0;u=c,c=o,o=a,a=i+t|0,i=s,s=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,s,i,a,o,c,u)}roundClean(){hs(yd)}destroy(){this.set(0,0,0,0,0,0,0,0),hs(this.buffer)}}const wd=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:a}=Gs(e[i],t);[r[i],s[i]]=[n,a]}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),vd=(()=>wd[0])(),Ed=(()=>wd[1])(),kd=new Uint32Array(80),Sd=new Uint32Array(80);class Od extends Vs{constructor(e=64){super(128,e,16,!1),this.Ah=0|qs[0],this.Al=0|qs[1],this.Bh=0|qs[2],this.Bl=0|qs[3],this.Ch=0|qs[4],this.Cl=0|qs[5],this.Dh=0|qs[6],this.Dl=0|qs[7],this.Eh=0|qs[8],this.El=0|qs[9],this.Fh=0|qs[10],this.Fl=0|qs[11],this.Gh=0|qs[12],this.Gl=0|qs[13],this.Hh=0|qs[14],this.Hl=0|qs[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:i,Dh:a,Dl:o,Eh:c,El:u,Fh:d,Fl:l,Gh:h,Gl:f,Hh:p,Hl:g}=this;return[e,t,n,r,s,i,a,o,c,u,d,l,h,f,p,g]}set(e,t,n,r,s,i,a,o,c,u,d,l,h,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|d,this.Fl=0|l,this.Gh=0|h,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)kd[n]=e.getUint32(t),Sd[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|kd[e-15],n=0|Sd[e-15],r=Ys(t,n,1)^Ys(t,n,8)^Hs(t,0,7),s=Xs(t,n,1)^Xs(t,n,8)^Js(t,n,7),i=0|kd[e-2],a=0|Sd[e-2],o=Ys(i,a,19)^Qs(i,a,61)^Hs(i,0,6),c=Xs(i,a,19)^ei(i,a,61)^Js(i,a,6),u=ii(s,c,Sd[e-7],Sd[e-16]),d=ai(u,r,o,kd[e-7],kd[e-16]);kd[e]=0|d,Sd[e]=0|u}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:a,Cl:o,Dh:c,Dl:u,Eh:d,El:l,Fh:h,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Ys(d,l,14)^Ys(d,l,18)^Qs(d,l,41),b=Xs(d,l,14)^Xs(d,l,18)^ei(d,l,41),w=d&h^~d&p,v=oi(y,b,l&f^~l&g,Ed[e],Sd[e]),E=ci(v,m,t,w,vd[e],kd[e]),k=0|v,S=Ys(n,r,28)^Qs(n,r,34)^Qs(n,r,39),O=Xs(n,r,28)^ei(n,r,34)^ei(n,r,39),x=n&s^n&a^s&a,I=r&i^r&o^i&o;m=0|p,y=0|g,p=0|h,g=0|f,h=0|d,f=0|l,({h:d,l:l}=ni(0|c,0|u,0|E,0|k)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|n,i=0|r;const T=ri(k,O,I);n=si(T,E,S,x),r=0|T}({h:n,l:r}=ni(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=ni(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=ni(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=ni(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l:l}=ni(0|this.Eh,0|this.El,0|d,0|l)),({h:h,l:f}=ni(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:g}=ni(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=ni(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,a,o,c,u,d,l,h,f,p,g,m,y)}roundClean(){hs(kd,Sd)}destroy(){hs(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class xd extends Od{constructor(){super(48),this.Ah=0|zs[0],this.Al=0|zs[1],this.Bh=0|zs[2],this.Bl=0|zs[3],this.Ch=0|zs[4],this.Cl=0|zs[5],this.Dh=0|zs[6],this.Dl=0|zs[7],this.Eh=0|zs[8],this.El=0|zs[9],this.Fh=0|zs[10],this.Fl=0|zs[11],this.Gh=0|zs[12],this.Gl=0|zs[13],this.Hh=0|zs[14],this.Hl=0|zs[15]}}const Id=$s(()=>new bd),Td=$s(()=>new Od),_d=$s(()=>new xd),Ad=BigInt(0),Cd=BigInt(1);function jd(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Pd(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Bd(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ad:BigInt("0x"+e)}function Nd(e){return Bd(ks(e))}function Rd(e){return os(e),Bd(ks(Uint8Array.from(e).reverse()))}function $d(e,t){return Cs(e.toString(16).padStart(2*t,"0"))}function Md(e,t){return $d(e,t).reverse()}function Ud(e,t,n){let r;if("string"==typeof t)try{r=Cs(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!is(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}const Dd=e=>"bigint"==typeof e&&Ad<=e;function Fd(e,t,n,r){if(!function(e,t,n){return Dd(e)&&Dd(t)&&Dd(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Ld(e){let t;for(t=0;e>Ad;e>>=Cd,t+=1);return t}const Vd=e=>(Cd<<BigInt(e))-Cd;function Kd(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const s=e[t];if(r&&void 0===s)return;const i=typeof s;if(i!==n||null===s)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function zd(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(void 0!==s)return s;const i=e(n,...r);return t.set(n,i),i}}const qd=BigInt(0),Zd=BigInt(1),Wd=BigInt(2),Gd=BigInt(3),Hd=BigInt(4),Jd=BigInt(5),Yd=BigInt(7),Xd=BigInt(8),Qd=BigInt(9),el=BigInt(16);function tl(e,t){const n=e%t;return n>=qd?n:t+n}function nl(e,t,n){let r=e;for(;t-- >qd;)r*=r,r%=n;return r}function rl(e,t){if(e===qd)throw new Error("invert: expected non-zero number");if(t<=qd)throw new Error("invert: expected positive modulus, got "+t);let n=tl(e,t),r=t,s=qd,i=Zd;for(;n!==qd;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==Zd)throw new Error("invert: does not exist");return tl(s,t)}function sl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function il(e,t){const n=(e.ORDER+Zd)/Hd,r=e.pow(t,n);return sl(e,r,t),r}function al(e,t){const n=(e.ORDER-Jd)/Xd,r=e.mul(t,Wd),s=e.pow(r,n),i=e.mul(t,s),a=e.mul(e.mul(i,Wd),s),o=e.mul(i,e.sub(a,e.ONE));return sl(e,o,t),o}function ol(e){if(e<Gd)throw new Error("sqrt is not defined for small field");let t=e-Zd,n=0;for(;t%Wd===qd;)t/=Wd,n++;let r=Wd;const s=fl(e);for(;1===hl(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return il;let i=s.pow(r,t);const a=(t+Zd)/Wd;return function(e,r){if(e.is0(r))return r;if(1!==hl(e,r))throw new Error("Cannot find square root");let s=n,o=e.mul(e.ONE,i),c=e.pow(r,t),u=e.pow(r,a);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===s)throw new Error("Cannot find square root");const r=Zd<<BigInt(s-t-1),i=e.pow(o,r);s=t,o=e.sqr(i),c=e.mul(c,o),u=e.mul(u,i)}return u}}function cl(e){return e%Hd===Gd?il:e%Xd===Jd?al:e%el===Qd?function(e){const t=fl(e),n=ol(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),a=(e+Yd)/el;return(e,t)=>{let n=e.pow(t,a),o=e.mul(n,r);const c=e.mul(n,s),u=e.mul(n,i),d=e.eql(e.sqr(o),t),l=e.eql(e.sqr(c),t);n=e.cmov(n,o,d),o=e.cmov(u,c,l);const h=e.eql(e.sqr(o),t),f=e.cmov(n,o,h);return sl(e,f,t),f}}(e):ol(e)}const ul=(e,t)=>(tl(e,t)&Zd)===Zd,dl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ll(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n)),e.ONE),i=e.inv(s);return t.reduceRight((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n)),i),r}function hl(e,t){const n=(e.ORDER-Zd)/Wd,r=e.pow(t,n),s=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),a=e.eql(r,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function fl(e,t,n=!1,r={}){if(e<=qd)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,a,o=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modOnDecode&&(o=e.modOnDecode),a=e.allowedLengths}else"number"==typeof t&&(s=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:u}=function(e,t){void 0!==t&&as(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const l=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:Vd(c),ZERO:qd,ONE:Zd,allowedLengths:a,create:t=>tl(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return qd<=t&&t<e},is0:e=>e===qd,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Zd)===Zd,neg:t=>tl(-t,e),eql:(e,t)=>e===t,sqr:t=>tl(t*t,e),add:(t,n)=>tl(t+n,e),sub:(t,n)=>tl(t-n,e),mul:(t,n)=>tl(t*n,e),pow:(e,t)=>function(e,t,n){if(n<qd)throw new Error("invalid exponent, negatives unsupported");if(n===qd)return e.ONE;if(n===Zd)return t;let r=e.ONE,s=t;for(;n>qd;)n&Zd&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Zd;return r}(l,e,t),div:(t,n)=>tl(t*rl(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>rl(t,e),sqrt:i||(t=>(d||(d=cl(e)),d(l,t))),toBytes:e=>n?Md(e,u):$d(e,u),fromBytes:(t,r=!0)=>{if(a){if(!a.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let s=n?Rd(t):Nd(t);if(o&&(s=tl(s,e)),!r&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>ll(l,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(l)}function pl(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function gl(e){const t=pl(e);return t+Math.ceil(t/2)}const ml=BigInt(0),yl=BigInt(1);function bl(e,t){const n=t.negate();return e?n:t}function wl(e,t){const n=ll(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function vl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function El(e,t){vl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Vd(e),maxNumber:n,shiftBy:BigInt(e)}}function kl(e,t,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:a}=n;let o=Number(e&s),c=e>>a;o>r&&(o-=i,c+=yl);const u=t*r;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:u}}const Sl=new WeakMap,Ol=new WeakMap;function xl(e){return Ol.get(e)||1}function Il(e){if(e!==ml)throw new Error("invalid wNAF")}class Tl{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>ml;)t&yl&&(n=n.add(r)),r=r.double(),t>>=yl;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=El(t,this.bits),s=[];let i=e,a=i;for(let e=0;e<n;e++){a=i,s.push(a);for(let e=1;e<r;e++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const i=El(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=kl(n,e,i);n=a,c?s=s.add(bl(d,t[l])):r=r.add(bl(u,t[o]))}return Il(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=El(e,this.bits);for(let e=0;e<s.windows&&n!==ml;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=kl(n,e,s);if(n=i,!o){const e=t[a];r=r.add(c?e.negate():e)}}return Il(n),r}getPrecomputes(e,t,n){let r=Sl.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Sl.set(t,r))),r}cached(e,t,n){const r=xl(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=xl(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){vl(t,this.bits),Ol.set(e,t),Sl.delete(e)}hasCache(e){return 1!==xl(e)}}function _l(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,o=Ld(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=Vd(c),d=new Array(Number(u)+1).fill(a);let l=a;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(a);for(let t=0;t<i;t++){const s=r[t],i=Number(s>>BigInt(e)&u);d[i]=d[i].add(n[t])}let t=a;for(let e=d.length-1,n=a;e>0;e--)n=n.add(d[e]),t=t.add(n);if(l=l.add(t),0!==e)for(let e=0;e<c;e++)l=l.double()}return l}function Al(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=dl.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Kd(e,t)}(t),t}return fl(e)}function Cl(e,t,n={}){if(!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>ml))throw new Error(`CURVE.${e} must be positive bigint`)}const r=Al(t.p,n.Fp),s=Al(t.n,n.Fn),i=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of i)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}const jl=BigInt(0),Pl=BigInt(1),Bl=BigInt(2),Nl=BigInt(8);class Rl{constructor(e){this.ep=e}static fromBytes(e){throw new Error("fromBytes must be implemented by subclass")}static fromHex(e){throw new Error("fromHex must be implemented by subclass")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toRawBytes(){return this.toBytes()}toHex(){return ks(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}}function $l(e,t,n){if("function"!=typeof t)throw new Error('"hash" function param is required');Kd(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:i,Fn:a}=e,o=a.ORDER,c=n.randomBytes||Us,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(jd("phflag",n),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return a.create(e)}function h(e){return l(Rd(e))}function f(e){const{head:n,prefix:r,scalar:a}=function(e){const n=i.BYTES;e=Ud("private key",e,n);const r=Ud("hashed private key",t(e),2*n),s=u(r.slice(0,n));return{head:s,prefix:r.slice(n,2*n),scalar:h(s)}}(e),o=s.multiply(a),c=o.toBytes();return{head:n,prefix:r,scalar:a,point:o,pointBytes:c}}function p(e){return f(e).pointBytes}function g(e=Uint8Array.of(),...n){const s=Ns(...n);return h(t(d(s,Ud("context",e),!!r)))}const m={zip215:!0};s.precompute(8);const y=i.BYTES,b={secret:y,public:y,signature:2*y,seed:y};function w(e=c(b.seed)){return e}const v={getExtendedPublicKey:f,randomSecretKey:w,isValidSecretKey:function(e){try{return!!a.fromBytes(e,!1)}catch(e){return!1}},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},randomPrivateKey:w,toMontgomery(t){const{y:n}=e.fromBytes(t),r=32===y;if(!r&&57!==y)throw new Error("only defined for 25519 and 448");const s=r?i.div(Pl+n,Pl-n):i.div(n-Pl,n+Pl);return i.toBytes(s)},toMontgomeryPriv(e){os(e,y);const n=t(e.subarray(0,y));return u(n).subarray(0,y)},precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:p(t)}},getPublicKey:p,sign:function(e,t,n={}){e=Ud("message",e),r&&(e=r(e));const{prefix:a,scalar:c,pointBytes:u}=f(t),d=g(n.context,a,e),h=s.multiply(d).toBytes(),p=l(d+g(n.context,h,u,e)*c);Fd("signature.s",p,jl,o);const m=i.BYTES;return Ud("result",Ns(h,Md(p,m)),2*m)},verify:function(t,n,a,o=m){const{context:c,zip215:u}=o,d=i.BYTES;t=Ud("signature",t,2*d),n=Ud("message",n),a=Ud("publicKey",a,d),void 0!==u&&jd("zip215",u),r&&(n=r(n));const l=Rd(t.slice(d,2*d));let h,f,p;try{h=e.fromHex(a,u),f=e.fromHex(t.slice(0,d),u),p=s.multiplyUnsafe(l)}catch(e){return!1}if(!u&&h.isSmallOrder())return!1;const y=g(c,f.toBytes(),h.toBytes(),n);return f.add(h.multiplyUnsafe(y)).subtract(p).clearCofactor().is0()},utils:v,Point:e,info:{type:"edwards",lengths:b}})}function Ml(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:fl(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const{Fp:n,Fn:r}=Cl("edwards",e,t),{h:s,n:i}=e;Kd(t,{},{uvRatio:"function"});const a=Bl<<BigInt(8*r.BYTES)-Pl,o=e=>n.create(e),c=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:jl}}});if(!function(e,t,n,r){const s=e.sqr(n),i=e.sqr(r),a=e.add(e.mul(t.a,s),i),o=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(a,o)}(n,e,e.Gx,e.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return Fd("coordinate "+e,t,n?Pl:jl,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const l=zd((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?Nl:n.inv(i));const c=o(r*t),u=o(s*t),d=n.mul(i,t);if(a)return{x:jl,y:Pl};if(d!==Pl)throw new Error("invZ was invalid");return{x:c,y:u}}),h=zd(t=>{const{a:n,d:r}=e;if(t.is0())throw new Error("bad point: ZERO");const{X:s,Y:i,Z:a,T:c}=t,u=o(s*s),d=o(i*i),l=o(a*a),h=o(l*l),f=o(u*n);if(o(l*o(f+d))!==o(h+o(r*o(u*d))))throw new Error("bad point: equation left != right (1)");if(o(s*i)!==o(a*c))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return wl(f,e)}static msm(e,t){return _l(f,r,e,t)}_setWindowSize(e){this.precompute(e)}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new f(t,n,Pl,o(t*n))}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(Bl),this}assertValidity(){h(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:s,Y:i,Z:a}=e,c=o(t*a),u=o(s*r),l=o(n*a),h=o(i*r);return c===u&&l===h}is0(){return this.equals(f.ZERO)}negate(){return new f(o(-this.X),this.Y,this.Z,o(-this.T))}double(){const{a:t}=e,{X:n,Y:r,Z:s}=this,i=o(n*n),a=o(r*r),c=o(Bl*o(s*s)),u=o(t*i),d=n+r,l=o(o(d*d)-i-a),h=u+a,p=h-c,g=u-a,m=o(l*p),y=o(h*g),b=o(l*g),w=o(p*h);return new f(m,y,w,b)}add(t){d(t);const{a:n,d:r}=e,{X:s,Y:i,Z:a,T:c}=this,{X:u,Y:l,Z:h,T:p}=t,g=o(s*u),m=o(i*l),y=o(c*r*p),b=o(a*h),w=o((s+i)*(u+l)-g-m),v=b-y,E=b+y,k=o(m-n*g),S=o(w*v),O=o(E*k),x=o(w*k),I=o(v*E);return new f(S,O,I,x)}subtract(e){return this.add(e.negate())}multiply(e){const t=e;Fd("scalar",t,Pl,i);const{p:n,f:r}=p.cached(this,t,e=>wl(f,e));return wl(f,[n,r])[0]}multiplyUnsafe(e,t=f.ZERO){const n=e;return Fd("scalar",n,jl,i),n===jl?f.ZERO:this.is0()||n===Pl?this:p.unsafe(this,n,e=>wl(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,i).is0()}toAffine(e){return l(this,e)}clearCofactor(){return s===Pl?this:this.multiplyUnsafe(s)}static fromBytes(e,t=!1){return os(e),f.fromHex(e,t)}static fromHex(t,r=!1){const{d:s,a:i}=e,u=n.BYTES;t=Ud("pointHex",t,u),jd("zip215",r);const d=t.slice(),l=t[u-1];d[u-1]=-129&l;const h=Rd(d),p=r?a:n.ORDER;Fd("pointHex.y",h,jl,p);const g=o(h*h),m=o(g-Pl),y=o(s*g-i);let{isValid:b,value:w}=c(m,y);if(!b)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&Pl)===Pl,E=!!(128&l);if(!r&&w===jl&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=o(-w)),f.fromAffine({x:w,y:h})}toBytes(){const{x:e,y:t}=this.toAffine(),r=Md(t,n.BYTES);return r[r.length-1]|=e&Pl?128:0,r}toRawBytes(){return this.toBytes()}toHex(){return ks(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}f.BASE=new f(e.Gx,e.Gy,Pl,o(e.Gx*e.Gy)),f.ZERO=new f(jl,Pl,Pl,jl),f.Fp=n,f.Fn=r;const p=new Tl(f,8*r.BYTES);return f}(t,n);return function(e,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:e})}(e,$l(i,r,s))}const Ul=BigInt(0),Dl=BigInt(1),Fl=BigInt(2);BigInt(3);const Ll=BigInt(5),Vl=BigInt(8),Kl={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Vl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function zl(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ql=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Zl(e,t){const n=Kl.p,r=tl(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Kl.p,a=e*e%i*e%i,o=nl(a,Fl,i)*a%i,c=nl(o,Dl,i)*e%i,u=nl(c,Ll,i)*c%i,d=nl(u,t,i)*u%i,l=nl(d,n,i)*d%i,h=nl(l,r,i)*l%i,f=nl(h,s,i)*h%i,p=nl(f,s,i)*h%i,g=nl(p,t,i)*u%i;return{pow_p_5_8:nl(g,Fl,i)*e%i,b2:a}}(e*tl(r*r*t,n)).pow_p_5_8;let i=tl(e*r*s,n);const a=tl(t*i*i,n),o=i,c=tl(i*ql,n),u=a===e,d=a===tl(-e,n),l=a===tl(-e*ql,n);return u&&(i=o),(d||l)&&(i=c),ul(i,n)&&(i=tl(-i,n)),{isValid:u||d,value:i}}const Wl=(()=>fl(Kl.p,{isLE:!0}))(),Gl=(()=>fl(Kl.n,{isLE:!0}))(),Hl=(()=>({...Kl,Fp:Wl,hash:Td,adjustScalarBytes:zl,uvRatio:Zl}))(),Jl=(()=>Ml(Hl))(),Yl=ql,Xl=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ql=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),th=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),nh=e=>Zl(Dl,e),rh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),sh=e=>Jl.CURVE.Fp.create(Rd(e)&rh);function ih(e){const{d:t}=Jl.CURVE,n=Jl.CURVE.Fp.ORDER,r=Jl.CURVE.Fp.create,s=r(Yl*e*e),i=r((s+Dl)*eh);let a=BigInt(-1);const o=r((a-t*s)*r(s+t));let{isValid:c,value:u}=Zl(i,o),d=r(u*e);ul(d,n)||(d=r(-d)),c||(u=d),c||(a=s);const l=r(a*(s-Dl)*th-o),h=u*u,f=r((u+u)*o),p=r(l*Xl),g=r(Dl-h),m=r(Dl+h);return new Jl.Point(r(f*m),r(g*p),r(p*m),r(f*g))}class ah extends Rl{constructor(e){super(e)}static fromAffine(e){return new ah(Jl.Point.fromAffine(e))}assertSame(e){if(!(e instanceof ah))throw new Error("RistrettoPoint expected")}init(e){return new ah(e)}static hashToCurve(e){return function(e){os(e,64);const t=ih(sh(e.subarray(0,32))),n=ih(sh(e.subarray(32,64)));return new ah(t.add(n))}(Ud("ristrettoHash",e,64))}static fromBytes(e){os(e,32);const{a:t,d:n}=Jl.CURVE,r=Wl.ORDER,s=Wl.create,i=sh(e);if(!function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(Md(i,32),e)||ul(i,r))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Dl+t*a),c=s(Dl-t*a),u=s(o*o),d=s(c*c),l=s(t*n*u-d),{isValid:h,value:f}=nh(s(l*d)),p=s(f*c),g=s(f*p*l);let m=s((i+i)*p);ul(m,r)&&(m=s(-m));const y=s(o*g),b=s(m*y);if(!h||ul(b,r)||y===Ul)throw new Error("invalid ristretto255 encoding 2");return new ah(new Jl.Point(m,y,Dl,b))}static fromHex(e){return ah.fromBytes(Ud("ristrettoHex",e,32))}static msm(e,t){return _l(ah,Jl.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep;const s=Wl.ORDER,i=Wl.create,a=i(i(n+t)*i(n-t)),o=i(e*t),c=i(o*o),{value:u}=nh(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*r);let f;if(ul(r*h,s)){let n=i(t*Yl),r=i(e*Yl);e=n,t=r,f=i(d*Ql)}else f=l;ul(e*h,s)&&(t=i(-t));let p=i((n-t)*f);return ul(p,s)&&(p=i(-p)),Md(p,32)}equals(e){this.assertSame(e);const{X:t,Y:n}=this.ep,{X:r,Y:s}=e.ep,i=Wl.create,a=i(t*s)===i(n*r),o=i(n*s)===i(t*r);return a||o}is0(){return this.equals(ah.ZERO)}}function oh(e,t){return xr.IntentMessage(xr.bytes(t.length)).serialize({intent:{scope:{[e]:!0},version:{V0:!0},appId:{Sui:!0}},value:t}).toBytes()}ah.BASE=(()=>new ah(Jl.Point.BASE))(),ah.ZERO=(()=>new ah(Jl.Point.ZERO))(),ah.Fp=Wl,ah.Fn=Gl;const ch={ED25519:0,Secp256k1:1,Secp256r1:2,MultiSig:3,ZkLogin:5,Passkey:6},uh={ED25519:32,Secp256k1:33,Secp256r1:33,Passkey:33},dh={0:"ED25519",1:"Secp256k1",2:"Secp256r1",3:"MultiSig",5:"ZkLogin",6:"Passkey"};class lh extends Rs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,cs(e);const n=Ps(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),hs(s)}update(e){return us(this),this.iHash.update(e),this}digestInto(e){us(this),os(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:a}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hh=(e,t,n)=>new lh(e,t).update(n).digest();hh.create=(e,t)=>new lh(e,t);const fh=(e,t)=>(e+(e>=0?t:-t)/wh)/t;function ph(e){void 0!==e.lowS&&jd("lowS",e.lowS),void 0!==e.prehash&&jd("prehash",e.prehash)}class gh extends Error{constructor(e=""){super(e)}}const mh={Err:gh,_tlv:{encode:(e,t)=>{const{Err:n}=mh;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=Pd(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Pd(s.length/2|128):"";return Pd(e)+i+s+t},decode(e,t){const{Err:n}=mh;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++];let i=0;if(!!(128&s)){const e=127&s;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const a=t.subarray(r,r+e);if(a.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===a[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of a)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=s;const a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=mh;if(e<yh)throw new t("integer: negative integers are not allowed");let n=Pd(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=mh;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Nd(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=mh,s=Ud("signature",e),{v:i,l:a}=r.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=r.decode(2,i),{v:u,l:d}=r.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(o),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=mh,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},yh=BigInt(0),bh=BigInt(1),wh=BigInt(2),vh=BigInt(3),Eh=BigInt(4);function kh(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=Ud("private key",t);try{r=e.fromBytes(s)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Sh(e,t={}){const{Fp:n,Fn:r}=Cl("weierstrass",e,t),{h:s,n:i}=e;Kd(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:a}=t;if(a&&(!n.is0(e.a)||"bigint"!=typeof a.beta||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function o(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const c=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),a=n.toBytes(s);if(jd("isCompressed",r),r){o();return Ns(Oh(!n.isOdd(i)),a)}return Ns(Uint8Array.of(4),a,n.toBytes(i))},u=t.fromBytes||function(e){os(e);const t=n.BYTES,r=t+1,s=2*t+1,i=e.length,a=e[0],c=e.subarray(1);if(i!==r||2!==a&&3!==a){if(i===s&&4===a){const e=n.fromBytes(c.subarray(0*t,1*t)),r=n.fromBytes(c.subarray(1*t,2*t));if(!l(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${r} or uncompressed=${s}`)}{const e=n.fromBytes(c);if(!n.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=d(e);let r;try{r=n.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}o();return!(1&~a)!==n.isOdd(r)&&(r=n.neg(r)),{x:e,y:r}}},d=function(e,t,n){return function(r){const s=e.sqr(r),i=e.mul(s,r);return e.add(e.add(i,e.mul(r,t)),n)}}(n,e.a,e.b);function l(e,t){const r=n.sqr(t),s=d(e);return n.eql(r,s)}if(!l(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const h=n.mul(n.pow(e.a,vh),Eh),f=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(h,f)))throw new Error("bad curve params: a or b");function p(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof v))throw new Error("ProjectivePoint expected")}function m(e){if(!a||!a.basises)throw new Error("no endo");return function(e,t,n){const[[r,s],[i,a]]=t,o=fh(a*e,n),c=fh(-s*e,n);let u=e-o*r-c*i,d=-o*s-c*a;const l=u<yh,h=d<yh;l&&(u=-u),h&&(d=-d);const f=Vd(Math.ceil(Ld(n)/2))+bh;if(u<yh||u>=f||d<yh||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:h,k2:d}}(e,a.basises,r.ORDER)}const y=zd((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const a=e.is0();null==t&&(t=a?n.ONE:n.inv(i));const o=n.mul(r,t),c=n.mul(s,t),u=n.mul(i,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:o,y:c}}),b=zd(e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw new Error("bad point: x or y not field elements");if(!l(r,s))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function w(e,t,r,s,i){return r=new v(n.mul(r.X,e),r.Y,r.Z),t=bl(s,t),r=bl(i,r),t.add(r)}class v{constructor(e,t,n){this.X=p("x",e),this.Y=p("y",t,!0),this.Z=p("z",n),Object.freeze(this)}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof v)throw new Error("projective point not allowed");return n.is0(t)&&n.is0(r)?v.ZERO:new v(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ(e){return wl(v,e)}static fromBytes(e){return os(e),v.fromHex(e)}static fromHex(e){const t=v.fromAffine(u(Ud("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(kh(r,e))}static msm(e,t){return _l(v,r,e,t)}_setWindowSize(e){this.precompute(e)}precompute(e=8,t=!0){return k.createCache(this,e),t||this.multiply(vh),this}assertValidity(){b(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){g(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:a,Z:o}=e,c=n.eql(n.mul(t,o),n.mul(i,s)),u=n.eql(n.mul(r,o),n.mul(a,s));return c&&u}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:r}=e,s=n.mul(r,vh),{X:i,Y:a,Z:o}=this;let c=n.ZERO,u=n.ZERO,d=n.ZERO,l=n.mul(i,i),h=n.mul(a,a),f=n.mul(o,o),p=n.mul(i,a);return p=n.add(p,p),d=n.mul(i,o),d=n.add(d,d),c=n.mul(t,d),u=n.mul(s,f),u=n.add(c,u),c=n.sub(h,u),u=n.add(h,u),u=n.mul(c,u),c=n.mul(p,c),d=n.mul(s,d),f=n.mul(t,f),p=n.sub(l,f),p=n.mul(t,p),p=n.add(p,d),d=n.add(l,l),l=n.add(d,l),l=n.add(l,f),l=n.mul(l,p),u=n.add(u,l),f=n.mul(a,o),f=n.add(f,f),l=n.mul(f,p),c=n.sub(c,l),d=n.mul(f,h),d=n.add(d,d),d=n.add(d,d),new v(c,u,d)}add(t){g(t);const{X:r,Y:s,Z:i}=this,{X:a,Y:o,Z:c}=t;let u=n.ZERO,d=n.ZERO,l=n.ZERO;const h=e.a,f=n.mul(e.b,vh);let p=n.mul(r,a),m=n.mul(s,o),y=n.mul(i,c),b=n.add(r,s),w=n.add(a,o);b=n.mul(b,w),w=n.add(p,m),b=n.sub(b,w),w=n.add(r,i);let E=n.add(a,c);return w=n.mul(w,E),E=n.add(p,y),w=n.sub(w,E),E=n.add(s,i),u=n.add(o,c),E=n.mul(E,u),u=n.add(m,y),E=n.sub(E,u),l=n.mul(h,w),u=n.mul(f,y),l=n.add(u,l),u=n.sub(m,l),l=n.add(m,l),d=n.mul(u,l),m=n.add(p,p),m=n.add(m,p),y=n.mul(h,y),w=n.mul(f,w),m=n.add(m,y),y=n.sub(p,y),y=n.mul(h,y),w=n.add(w,y),p=n.mul(m,w),d=n.add(d,p),p=n.mul(E,w),u=n.mul(b,u),u=n.sub(u,p),p=n.mul(b,m),l=n.mul(E,l),l=n.add(l,p),new v(u,d,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(v.ZERO)}multiply(e){const{endo:n}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,i;const a=e=>k.cached(this,e,e=>wl(v,e));if(n){const{k1neg:t,k1:r,k2neg:o,k2:c}=m(e),{p:u,f:d}=a(r),{p:l,f:h}=a(c);i=d.add(h),s=w(n.beta,u,l,t,o)}else{const{p:t,f:n}=a(e);s=t,i=n}return wl(v,[s,i])[0]}multiplyUnsafe(e){const{endo:n}=t,s=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===yh||s.is0())return v.ZERO;if(e===bh)return s;if(k.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:r,k2neg:i,k2:a}=m(e),{p1:o,p2:c}=function(e,t,n,r){let s=t,i=e.ZERO,a=e.ZERO;for(;n>ml||r>ml;)n&yl&&(i=i.add(s)),r&yl&&(a=a.add(s)),s=s.double(),n>>=yl,r>>=yl;return{p1:i,p2:a}}(v,s,r,a);return w(n.beta,o,c,t,i)}return k.unsafe(s,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return y(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===bh||(e?e(v,this):k.unsafe(this,i).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===bh?this:e?e(v,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return jd("isCompressed",e),this.assertValidity(),c(v,this,e)}toRawBytes(e=!0){return this.toBytes(e)}toHex(e=!0){return ks(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}v.BASE=new v(e.Gx,e.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=r;const E=r.BITS,k=new Tl(v,t.endo?Math.ceil(E/2):E);return v}function Oh(e){return Uint8Array.of(e?2:3)}function xh(e,t,n={}){cs(t),Kd(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Us,s=n.hmac||((e,...n)=>hh(t,e,Ns(...n))),{Fp:i,Fn:a}=e,{ORDER:o,BITS:c}=a,u=gl(o),d={secret:a.BYTES,public:1+i.BYTES,publicUncompressed:1+2*i.BYTES,signature:2*a.BYTES,seed:u};function l(e){return e>o>>bh}function h(e,t){if(!a.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..CURVE.n`)}class f{constructor(e,t,n){h("r",e),h("s",t),this.r=e,this.s=t,null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t="compact"){if("compact"===t){const t=a.BYTES;os(e,2*t);const n=e.subarray(0,t),r=e.subarray(t,2*t);return new f(a.fromBytes(n),a.fromBytes(r))}if("der"===t){os(e);const{r:t,s:n}=mh.toSig(e);return new f(t,n)}throw new Error("invalid format")}static fromHex(e,t){return this.fromBytes(Cs(e),t)}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(o*wh<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+o:r;if(!i.isValid(u))throw new Error("recovery id 2 or 3 invalid");const d=i.toBytes(u),l=e.fromHex(Ns(Oh(!(1&c)),d)),h=a.inv(u),f=v(Ud("msgHash",t)),p=a.create(-f*h),g=a.create(s*h),m=e.BASE.multiplyUnsafe(p).add(l.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,a.neg(this.s),this.recovery):this}toBytes(e="compact"){if("compact"===e)return Ns(a.toBytes(this.r),a.toBytes(this.s));if("der"===e)return Cs(mh.hexFromSig(this));throw new Error("invalid format")}toHex(e){return ks(this.toBytes(e))}assertValidity(){}static fromCompact(e){return f.fromBytes(Ud("sig",e),"compact")}static fromDER(e){return f.fromBytes(Ud("sig",e),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ks(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ks(this.toBytes("compact"))}}function p(e){try{return!!kh(a,e)}catch(e){return!1}}function g(e=r(u)){return function(e,t,n=!1){const r=e.length,s=pl(t),i=gl(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=tl(n?Rd(e):Nd(e),t-Zd)+Zd;return n?Md(a,s):$d(a,s)}(e,o)}const m={isValidSecretKey:p,isValidPublicKey:function(t,n){try{const r=t.length;return(!0!==n||r===d.public)&&((!1!==n||r===d.publicUncompressed)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:g,isValidPrivateKey:p,randomPrivateKey:g,normPrivateKeyToScalar:e=>kh(a,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};function y(t,n=!0){return e.BASE.multiply(kh(a,t)).toBytes(n)}function b(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;if(a.allowedLengths||d.secret===d.public)return;const n=Ud("key",t).length;return n===d.public||n===d.publicUncompressed}const w=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Nd(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},v=n.bits2int_modN||function(e){return a.create(w(e))},E=Vd(c);function k(e){return Fd("num < 2^"+c,e,yh,E),a.toBytes(e)}function S(n,s,i=O){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");let{lowS:o,prehash:c,extraEntropy:u}=i;null==o&&(o=!0),n=Ud("msgHash",n),ph(i),c&&(n=Ud("prehashed msgHash",t(n)));const h=v(n),p=kh(a,s),g=[k(p),k(h)];if(null!=u&&!1!==u){const e=!0===u?r(d.secret):u;g.push(Ud("extraEntropy",e))}const m=Ns(...g),y=h;return{seed:m,k2sig:function(t){const n=w(t);if(!a.isValidNot0(n))return;const r=a.inv(n),s=e.BASE.multiply(n).toAffine(),i=a.create(s.x);if(i===yh)return;const c=a.create(r*a.create(y+i*p));if(c===yh)return;let u=(s.x===i?0:2)|Number(s.y&bh),d=c;return o&&l(c)&&(d=function(e){return l(e)?a.neg(e):e}(c),u^=1),new f(i,d,u)}}}const O={lowS:n.lowS,prehash:!1},x={lowS:n.lowS,prehash:!1};return e.BASE.precompute(8),Object.freeze({keygen:function(e){const t=m.randomSecretKey(e);return{secretKey:t,publicKey:y(t)}},getPublicKey:y,sign:function(e,n,r=O){const{seed:i,k2sig:o}=S(e,n,r);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=r(e),a=r(e),o=0;const c=()=>{i.fill(1),a.fill(0),o=0},u=(...e)=>n(a,i,...e),d=(e=r(0))=>{a=u(s(0),e),i=u(),0!==e.length&&(a=u(s(1),e),i=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=u();const t=i.slice();n.push(t),e+=i.length}return Ns(...n)};return(e,t)=>{let n;for(c(),d(e);!(n=t(l()));)d();return c(),n}}(t.outputLen,a.BYTES,s)(i,o)},verify:function(n,r,s,i=x){const o=n;r=Ud("msgHash",r),s=Ud("publicKey",s),ph(i);const{lowS:c,prehash:u,format:d}=i;if("strict"in i)throw new Error("options.strict was renamed to lowS");let l,h;if(void 0===d){const e="string"==typeof o||is(o),t=!e&&null!==o&&"object"==typeof o&&"bigint"==typeof o.r&&"bigint"==typeof o.s;if(!e&&!t)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(t)l=new f(o.r,o.s);else if(e){try{l=f.fromDER(o)}catch(e){if(!(e instanceof mh.Err))throw e}if(!l)try{l=f.fromCompact(o)}catch(e){return!1}}}else if("compact"===d||"der"===d){if("string"!=typeof o&&!is(o))throw new Error('"der" / "compact" format expects Uint8Array signature');l=f.fromBytes(Ud("sig",o),d)}else{if("js"!==d)throw new Error('format must be "compact", "der" or "js"');if(!(o instanceof f))throw new Error('"js" format expects Signature instance');l=o}if(!l)return!1;try{if(h=e.fromHex(s),c&&l.hasHighS())return!1;u&&(r=t(r));const{r:n,s:i}=l,o=v(r),d=a.inv(i),f=a.create(o*d),p=a.create(n*d),g=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(p));if(g.is0())return!1;return a.create(g.x)===n}catch(e){return!1}},getSharedSecret:function(t,n,r=!0){if(!0===b(t))throw new Error("first arg must be private key");if(!1===b(n))throw new Error("second arg must be public key");const s=kh(a,t);return e.fromHex(n).multiply(s).toBytes(r)},utils:m,Point:e,Signature:f,info:{type:"weierstrass",lengths:d,publicKeyHasPrefix:!0}})}function Ih(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:fl(t.n,{BITS:e.nBitLength,allowedLengths:r,modOnDecode:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function Th(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=Ih(e);return function(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}(e,xh(Sh(t,n),r,s))}function _h(e,t){const n=t=>Th({...e,hash:t});return{...n(t),create:n}}const Ah={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Ch={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},jh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Ph=fl(Ah.p),Bh=fl(Ch.p),Nh=fl(jh.p),Rh=_h({...Ah,Fp:Ph,lowS:!1},Id);_h({...Ch,Fp:Bh,lowS:!1},_d),_h({...jh,Fp:Nh,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Td);const $h=Rh,Mh=Id;function Uh(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}class Dh{equals(e){return Uh(this.toRawBytes(),e.toRawBytes())}toBase64(){return Ie(this.toRawBytes())}toString(){throw new Error("`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.")}toSuiPublicKey(){return Ie(this.toSuiBytes())}verifyWithIntent(e,t,n){const r=oh(n,e),s=gi(r,{dkLen:32});return this.verify(s,t)}verifyPersonalMessage(e,t){return this.verifyWithIntent(xr.byteVector().serialize(e).toBytes(),t,"PersonalMessage")}verifyTransaction(e,t){return this.verifyWithIntent(e,t,"TransactionData")}verifyAddress(e){return this.toSuiAddress()===e}toSuiBytes(){const e=this.toRawBytes(),t=new Uint8Array(e.length+1);return t.set([this.flag()]),t.set(e,1),t}toSuiAddress(){return tn(ks(gi(this.toSuiBytes(),{dkLen:32})).slice(0,64))}}function Fh(e){const t=Oe(e),n=dh[t[0]];switch(n){case"ED25519":case"Secp256k1":case"Secp256r1":const r=uh[n],s=t.slice(1,t.length-r);return{serializedSignature:e,signatureScheme:n,signature:s,publicKey:t.slice(1+s.length),bytes:t};default:throw new Error("Unsupported signature scheme")}}function Lh(e){const t="string"==typeof e?Oe(e):e;if(t[0]!==ch.Passkey)throw new Error("Invalid signature scheme");const n=ar.parse(t.slice(1));return{signatureScheme:"Passkey",serializedSignature:Ie(t),signature:t,authenticatorData:n.authenticatorData,clientDataJson:n.clientDataJson,userSignature:new Uint8Array(n.userSignature),publicKey:new Uint8Array(n.userSignature.slice(65))}}function Vh(e,t){if(!Boolean(e))throw new Error(t)}(class extends Dh{constructor(e){if(super(),"string"==typeof e?this.data=Oe(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return ch.Passkey}async verify(e,t){const n=Lh(t),r=JSON.parse(n.clientDataJson);if("webauthn.get"!==r.type)return!1;if(!Uh(e,Oe(r.challenge.replace(/-/g,"+").replace(/_/g,"/"))))return!1;const s=n.userSignature.slice(65);if(!Uh(this.toRawBytes(),s))return!1;const i=new Uint8Array([...n.authenticatorData,...Mh(n.clientDataJson)]),a=n.userSignature.slice(1,65);return $h.verify(a,Mh(i),s)}}).SIZE=33;const Kh={Name:[],Document:["definitions"],OperationDefinition:["description","name","variableDefinitions","directives","selectionSet"],VariableDefinition:["description","variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["description","name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"],TypeCoordinate:["name"],MemberCoordinate:["name","memberName"],ArgumentCoordinate:["name","fieldName","argumentName"],DirectiveCoordinate:["name"],DirectiveArgumentCoordinate:["name","argumentName"]},zh=new Set(Object.keys(Kh));function qh(e){const t=null==e?void 0:e.kind;return"string"==typeof t&&zh.has(t)}var Zh,Wh;function Gh(e){return 9===e||32===e}!function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"}(Zh||(Zh={})),function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension",e.TYPE_COORDINATE="TypeCoordinate",e.MEMBER_COORDINATE="MemberCoordinate",e.ARGUMENT_COORDINATE="ArgumentCoordinate",e.DIRECTIVE_COORDINATE="DirectiveCoordinate",e.DIRECTIVE_ARGUMENT_COORDINATE="DirectiveArgumentCoordinate"}(Wh||(Wh={}));function Hh(e){return Jh(e,[])}function Jh(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return function(e,t){if(null===e)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(function(e){return"function"==typeof e.toJSON}(e)){const t=e.toJSON();if(t!==e)return"string"==typeof t?t:Jh(t,n)}else if(Array.isArray(e))return function(e,t){if(0===e.length)return"[]";if(t.length>2)return"[Array]";const n=Math.min(10,e.length),r=e.length-n,s=[];for(let r=0;r<n;++r)s.push(Jh(e[r],t));1===r?s.push("... 1 more item"):r>1&&s.push(`... ${r} more items`);return"["+s.join(", ")+"]"}(e,n);return function(e,t){const n=Object.entries(e);if(0===n.length)return"{}";if(t.length>2)return"["+function(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if("Object"===t&&"function"==typeof e.constructor){const t=e.constructor.name;if("string"==typeof t&&""!==t)return t}return t}(e)+"]";const r=n.map(([e,n])=>e+": "+Jh(n,t));return"{ "+r.join(", ")+" }"}(e,n)}(e,t);default:return String(e)}}const Yh=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Xh(e){return Qh[e.charCodeAt(0)]}const Qh=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],ef=Object.freeze({});function tf(e,t){const n=e[t];return"object"==typeof n?n:"function"==typeof n?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function nf(e){return function(e,t,n=Kh){const r=new Map;for(const e of Object.values(Wh))r.set(e,tf(t,e));let s,i,a,o=Array.isArray(e),c=[e],u=-1,d=[],l=e;const h=[],f=[];do{u++;const e=u===c.length,y=e&&0!==d.length;if(e){if(i=0===f.length?void 0:h[h.length-1],l=a,a=f.pop(),y)if(o){l=l.slice();let e=0;for(const[t,n]of d){const r=t-e;null===n?(l.splice(r,1),e++):l[r]=n}}else{l={...l};for(const[e,t]of d)l[e]=t}u=s.index,c=s.keys,d=s.edits,o=s.inArray,s=s.prev}else if(a){if(i=o?u:c[u],l=a[i],null==l)continue;h.push(i)}let b;if(!Array.isArray(l)){var p,g;qh(l)||Vh(!1,`Invalid AST Node: ${Hh(l)}.`);const n=e?null===(p=r.get(l.kind))||void 0===p?void 0:p.leave:null===(g=r.get(l.kind))||void 0===g?void 0:g.enter;if(b=null==n?void 0:n.call(t,l,i,a,h,f),b===ef)break;if(!1===b){if(!e){h.pop();continue}}else if(void 0!==b&&(d.push([i,b]),!e)){if(!qh(b)){h.pop();continue}l=b}}var m;void 0===b&&y&&d.push([i,l]),e?h.pop():(s={inArray:o,index:u,keys:c,edits:d,prev:s},o=Array.isArray(l),c=o?l:null!==(m=n[l.kind])&&void 0!==m?m:[],u=-1,d=[],a&&f.push(a),a=l)}while(void 0!==s);return 0!==d.length?d[d.length-1][1]:e}(e,rf)}const rf={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>sf(e.definitions,"\n\n")},OperationDefinition:{leave(e){const t=uf(e.variableDefinitions)?of("(\n",sf(e.variableDefinitions,"\n"),"\n)"):of("(",sf(e.variableDefinitions,", "),")"),n=of("",e.description,"\n")+sf([e.operation,sf([e.name,t]),sf(e.directives," ")]," ");return("query"===n?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r,description:s})=>of("",s,"\n")+e+": "+t+of(" = ",n)+of(" ",sf(r," "))},SelectionSet:{leave:({selections:e})=>af(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:s}){const i=of("",e,": ")+t;let a=i+of("(",sf(n,", "),")");return a.length>80&&(a=i+of("(\n",cf(sf(n,"\n")),"\n)")),sf([a,sf(r," "),s]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+of(" ",sf(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>sf(["...",of("on ",e),sf(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:s,description:i})=>of("",i,"\n")+`fragment ${e}${of("(",sf(n,", "),")")} `+`on ${t} ${of("",sf(r," ")," ")}`+s},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?function(e,t){const n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),s=1===r.length,i=r.length>1&&r.slice(1).every(e=>0===e.length||Gh(e.charCodeAt(0))),a=n.endsWith('\\"""'),o=e.endsWith('"')&&!a,c=e.endsWith("\\"),u=o||c,d=!(null!=t&&t.minimize)&&(!s||e.length>70||u||i||a);let l="";const h=s&&Gh(e.charCodeAt(0));return(d&&!h||i)&&(l+="\n"),l+=n,(d||u)&&(l+="\n"),'"""'+l+'"""'}(e):`"${e.replace(Yh,Xh)}"`},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+sf(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+sf(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+of("(",sf(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>of("",e,"\n")+sf(["schema",sf(t," "),af(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>of("",e,"\n")+sf(["scalar",t,sf(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>of("",e,"\n")+sf(["type",t,of("implements ",sf(n," & ")),sf(r," "),af(s)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:s})=>of("",e,"\n")+t+(uf(n)?of("(\n",cf(sf(n,"\n")),"\n)"):of("(",sf(n,", "),")"))+": "+r+of(" ",sf(s," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:s})=>of("",e,"\n")+sf([t+": "+n,of("= ",r),sf(s," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>of("",e,"\n")+sf(["interface",t,of("implements ",sf(n," & ")),sf(r," "),af(s)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>of("",e,"\n")+sf(["union",t,sf(n," "),of("= ",sf(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>of("",e,"\n")+sf(["enum",t,sf(n," "),af(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>of("",e,"\n")+sf([t,sf(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>of("",e,"\n")+sf(["input",t,sf(n," "),af(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:s})=>of("",e,"\n")+"directive @"+t+(uf(n)?of("(\n",cf(sf(n,"\n")),"\n)"):of("(",sf(n,", "),")"))+(r?" repeatable":"")+" on "+sf(s," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>sf(["extend schema",sf(e," "),af(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>sf(["extend scalar",e,sf(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>sf(["extend type",e,of("implements ",sf(t," & ")),sf(n," "),af(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>sf(["extend interface",e,of("implements ",sf(t," & ")),sf(n," "),af(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>sf(["extend union",e,sf(t," "),of("= ",sf(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>sf(["extend enum",e,sf(t," "),af(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>sf(["extend input",e,sf(t," "),af(n)]," ")},TypeCoordinate:{leave:({name:e})=>e},MemberCoordinate:{leave:({name:e,memberName:t})=>sf([e,of(".",t)])},ArgumentCoordinate:{leave:({name:e,fieldName:t,argumentName:n})=>sf([e,of(".",t),of("(",n,":)")])},DirectiveCoordinate:{leave:({name:e})=>sf(["@",e])},DirectiveArgumentCoordinate:{leave:({name:e,argumentName:t})=>sf(["@",e,of("(",t,":)")])}};function sf(e,t=""){var n;return null!==(n=null==e?void 0:e.filter(e=>e).join(t))&&void 0!==n?n:""}function af(e){return of("{\n",cf(sf(e,"\n")),"\n}")}function of(e,t,n=""){return null!=t&&""!==t?e+t+n:""}function cf(e){return of(" ",e.replace(/\n/g,"\n "))}function uf(e){var t;return null!==(t=null==e?void 0:e.some(e=>e.includes("\n")))&&void 0!==t&&t}var df=(e=>(e.PersonalMessage="PERSONAL_MESSAGE",e.TransactionData="TRANSACTION_DATA",e))(df||{});class lf extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t}toString(){return this.value}}new lf("\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}\n ",{fragmentName:"OBJECT_OWNER_FIELDS"}),new lf("\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n asMoveObject {\n contents {\n bcs\n type {\n repr\n }\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}",{fragmentName:"OBJECT_FIELDS"}),new lf("\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n contents {\n bcs\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}",{fragmentName:"MOVE_OBJECT_FIELDS"}),new lf("\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}\n ",{fragmentName:"TRANSACTION_FIELDS"});const hf=new lf("\n query getAllBalances($owner: SuiAddress!, $limit: Int, $cursor: String) {\n address(address: $owner) {\n balances(first: $limit, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n coinType {\n repr\n }\n totalBalance\n }\n }\n }\n}\n "),ff=new lf('\n query getBalance($owner: SuiAddress!, $coinType: String! = "0x2::sui::SUI") {\n address(address: $owner) {\n balance(coinType: $coinType) {\n coinType {\n repr\n }\n totalBalance\n }\n }\n}\n '),pf=new lf('\n query getCoins($owner: SuiAddress!, $first: Int, $cursor: String, $type: String! = "0x2::coin::Coin<0x2::sui::SUI>") {\n address(address: $owner) {\n address\n objects(first: $first, after: $cursor, filter: {type: $type}) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n contents {\n bcs\n json\n type {\n repr\n }\n }\n address\n version\n digest\n previousTransaction {\n digest\n }\n }\n }\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}'),gf=new lf("\n query getDynamicFields($parentId: SuiAddress!, $first: Int, $cursor: String) {\n address(address: $parentId) {\n dynamicFields(first: $first, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n name {\n bcs\n type {\n repr\n }\n }\n value {\n __typename\n ... on MoveValue {\n type {\n repr\n }\n }\n ... on MoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n}\n "),mf=new lf("\n query getMoveFunction($package: SuiAddress!, $module: String!, $function: String!) {\n package(address: $package) {\n module(name: $module) {\n function(name: $function) {\n name\n visibility\n isEntry\n typeParameters {\n constraints\n }\n parameters {\n signature\n }\n return {\n signature\n }\n }\n }\n }\n}\n "),yf=new lf("\n query getReferenceGasPrice {\n epoch {\n referenceGasPrice\n }\n}\n "),bf=new lf("\n query defaultSuinsName($address: SuiAddress!) {\n address(address: $address) {\n defaultSuinsName\n }\n}\n "),wf=new lf("\n query getOwnedObjects($owner: SuiAddress!, $limit: Int, $cursor: String, $filter: ObjectFilter) {\n address(address: $owner) {\n objects(first: $limit, after: $cursor, filter: $filter) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n ...MOVE_OBJECT_FIELDS\n }\n }\n }\n}\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n contents {\n bcs\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}"),vf=new lf("\n query multiGetObjects($objectKeys: [ObjectKey!]!) {\n multiGetObjects(keys: $objectKeys) {\n ...OBJECT_FIELDS\n }\n}\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n asMoveObject {\n contents {\n bcs\n type {\n repr\n }\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}"),Ef=new lf("\n query simulateTransaction($transaction: JSON!) {\n simulateTransaction(transaction: $transaction) {\n error\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),kf=new lf("\n mutation executeTransaction($transactionDataBcs: Base64!, $signatures: [Base64!]!) {\n executeTransaction(\n transactionDataBcs: $transactionDataBcs\n signatures: $signatures\n ) {\n errors\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),Sf=new lf("\n query getTransactionBlock($digest: String!) {\n transaction(digest: $digest) {\n ...TRANSACTION_FIELDS\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),Of=new lf("\n query verifyZkLoginSignature($bytes: Base64!, $signature: Base64!, $intentScope: ZkLoginIntentScope!, $author: SuiAddress!) {\n verifyZkLoginSignature(\n bytes: $bytes\n signature: $signature\n intentScope: $intentScope\n author: $author\n ) {\n success\n error\n }\n}\n ");var xf,If,Tf,_f=e=>{throw TypeError(e)},Af=(e,t,n)=>t.has(e)||_f("Cannot "+n),Cf=(e,t,n)=>t.has(e)?_f("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),jf=(e,t,n)=>(Af(e,t,"access private method"),n);class Pf extends Ma{constructor({graphqlClient:e,mvr:t}){var n,r,s,i;super({network:e.network,base:e,mvr:t}),Cf(this,If),Cf(this,xf),s=e,Af(n=this,r=xf,"write to private field"),i?i.call(n,s):r.set(n,s)}async getObjects(e){const t=Ae(e.objectIds,50),n=[];for(const e of t){const t=await jf(this,If,Tf).call(this,{query:vf,variables:{objectKeys:e.map(e=>({address:e}))}},e=>e.multiGetObjects);n.push(...e.map(e=>tn(e)).map(e=>t.find(t=>t?.address===e)??new Da("notFound",`Object ${e} not found`)).map(e=>e instanceof Da?e:{id:e.address,version:e.version?.toString(),digest:e.digest,owner:Nf(e.owner),type:e.asMoveObject?.contents?.type?.repr,content:Promise.resolve(e.asMoveObject?.contents?.bcs?Oe(e.asMoveObject.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}return{objects:n}}async getOwnedObjects(e){const t=await jf(this,If,Tf).call(this,{query:wf,variables:{owner:e.address,limit:e.limit,cursor:e.cursor,filter:e.type?{type:(await this.mvr.resolveType({type:e.type})).type}:void 0}},e=>e.address?.objects);return{objects:t.nodes.map(e=>({id:e.address,version:e.version?.toString(),digest:e.digest,owner:Nf(e.owner),type:e.contents?.type?.repr,content:Promise.resolve(e.contents?.bcs?Oe(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null})),hasNextPage:t.pageInfo.hasNextPage,cursor:t.pageInfo.endCursor??null}}async getCoins(e){const t=await jf(this,If,Tf).call(this,{query:pf,variables:{owner:e.address,cursor:e.cursor,first:e.limit,type:`0x2::coin::Coin<${(await this.mvr.resolveType({type:e.coinType})).type}>`}},e=>e.address?.objects);return{cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage,objects:t.nodes.map(e=>({id:e.address,version:e.version?.toString(),digest:e.digest,owner:Nf(e.owner),type:e.contents?.type?.repr,balance:e.contents?.json?.balance,content:Promise.resolve(e.contents?.bcs?Oe(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}}async getBalance(e){const t=await jf(this,If,Tf).call(this,{query:ff,variables:{owner:e.address,type:(await this.mvr.resolveType({type:e.coinType})).type}},e=>e.address?.balance);return{balance:{coinType:t.coinType?.repr,balance:t.totalBalance}}}async getAllBalances(e){const t=await jf(this,If,Tf).call(this,{query:hf,variables:{owner:e.address}},e=>e.address?.balances);return{cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage,balances:t.nodes.map(e=>({coinType:e.coinType?.repr,balance:e.totalBalance}))}}async getTransaction(e){return{transaction:Rf(await jf(this,If,Tf).call(this,{query:Sf,variables:{digest:e.digest}},e=>e.transaction))}}async executeTransaction(e){const t=await jf(this,If,Tf).call(this,{query:kf,variables:{transactionDataBcs:Ie(e.transaction),signatures:e.signatures}},e=>e.executeTransaction);if(t.errors){if(1===t.errors.length)throw new Error(t.errors[0]);throw new AggregateError(t.errors.map(e=>new Error(e)))}return{transaction:Rf(t.effects?.transaction)}}async dryRunTransaction(e){const t=await jf(this,If,Tf).call(this,{query:Ef,variables:{transaction:{bcs:{value:Ie(e.transaction)}}}},e=>e.simulateTransaction);if(t.error)throw new Error(t.error);return{transaction:Rf(t.effects?.transaction)}}async getReferenceGasPrice(){return{referenceGasPrice:await jf(this,If,Tf).call(this,{query:yf},e=>e.epoch?.referenceGasPrice)}}async getDynamicFields(e){const t=await jf(this,If,Tf).call(this,{query:gf,variables:{parentId:e.parentId}},e=>e.address?.dynamicFields);return{dynamicFields:t.nodes.map(t=>{const n="MoveObject"===t.value?.__typename?t.value.contents?.type?.repr:t.value?.type?.repr;return{id:mi(e.parentId,t.name?.type?.repr,Oe(t.name?.bcs)),type:en("MoveObject"===t.value?.__typename?`0x2::dynamic_field::Field<0x2::dynamic_object_field::Wrapper<${t.name?.type?.repr}>,0x2::object::ID>`:`0x2::dynamic_field::Field<${t.name?.type?.repr},${n}>`),name:{type:t.name?.type?.repr,bcs:Oe(t.name?.bcs)},valueType:n}}),cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage}}async verifyZkLoginSignature(e){const t="TransactionData"===e.intentScope?df.TransactionData:df.PersonalMessage,n=await jf(this,If,Tf).call(this,{query:Of,variables:{bytes:e.bytes,signature:e.signature,intentScope:t,author:e.author}},e=>e.verifyZkLoginSignature);return{success:n.success??!1,errors:n.error?[n.error]:[]}}async defaultNameServiceName(e){return{data:{name:await jf(this,If,Tf).call(this,{query:bf,signal:e.signal,variables:{address:e.address}},e=>e.address?.defaultSuinsName??null)}}}async getMoveFunction(e){const t=await jf(this,If,Tf).call(this,{query:mf,variables:{package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name}},e=>e.package?.module?.function);let n="unknown";switch(t.visibility){case"PUBLIC":n="public";break;case"PRIVATE":n="private";break;case"FRIEND":n="friend"}return{function:{packageId:tn(e.packageId),moduleName:e.moduleName,name:t.name,visibility:n,isEntry:t.isEntry??!1,typeParameters:t.typeParameters?.map(({constraints:e})=>({isPhantom:!1,constraints:e.map(e=>{switch(e){case"COPY":return"copy";case"DROP":return"drop";case"STORE":return"store";case"KEY":return"key";default:return"unknown"}})??[]}))??[],parameters:t.parameters?.map(e=>$f(e.signature))??[],returns:t.return?.map(({signature:e})=>$f(e))??[]}}}resolveTransactionPlugin(){throw new Error("GraphQL client does not support transaction resolution yet")}}xf=new WeakMap,If=new WeakSet,Tf=async function(e,t){const{data:n,errors:r}=await(s=this,i=xf,Af(s,i,"read from private field"),a?a.call(s):i.get(s)).query(e);var s,i,a;!function(e){if(!e||0===e.length)return;const t=e.map(e=>new Bf(e));if(1===t.length)throw t[0];throw new AggregateError(t)}(r);const o=n&&(t?t(n):n);if(null==o)throw new Error("Missing response data");return o};class Bf extends Error{constructor(e){super(e.message),this.locations=e.locations}}function Nf(e){switch(e.__typename){case"AddressOwner":return{$kind:"AddressOwner",AddressOwner:e.address?.address};case"ConsensusAddressOwner":return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:e?.address?.address,startVersion:String(e.startVersion)}};case"ObjectOwner":return{$kind:"ObjectOwner",ObjectOwner:e.address?.address};case"Immutable":return{$kind:"Immutable",Immutable:!0};case"Shared":return{$kind:"Shared",Shared:{initialSharedVersion:String(e.initialSharedVersion)}}}}function Rf(e){const t={};if(e.effects?.unchangedConsensusObjects?.nodes.forEach(e=>{if("ConsensusObjectRead"===e.__typename){const n=e.object?.asMoveObject?.contents?.type?.repr,r=e.object?.asMoveObject?.address;n&&r&&(t[r]=n)}}),e.effects?.objectChanges?.nodes.forEach(e=>{const n=e.address,r=e.inputState?.asMoveObject?.contents?.type?.repr??e.outputState?.asMoveObject?.contents?.type?.repr;n&&r&&(t[n]=r)}),e.effects?.balanceChanges?.pageInfo.hasNextPage)throw new Error("Pagination for balance changes is not supported");return{digest:e.digest,effects:La(Oe(e.effects?.effectsBcs)),epoch:e.effects?.epoch?.epochId?.toString()??null,objectTypes:Promise.resolve(t),transaction:Fa(Oe(e.transactionBcs)),signatures:e.signatures.map(e=>e.signatureBytes),balanceChanges:e.effects?.balanceChanges?.nodes.map(e=>({coinType:e?.coinType?.repr,address:e.owner?.address,amount:e.amount}))??[]}}function $f(e){let t=null;return"&"===e.ref?t="immutable":"&mut"===e.ref&&(t="mutable"),{reference:t,body:Mf(e.body)}}function Mf(e){switch(e){case"address":return{$kind:"address"};case"bool":return{$kind:"bool"};case"u8":return{$kind:"u8"};case"u16":return{$kind:"u16"};case"u32":return{$kind:"u32"};case"u64":return{$kind:"u64"};case"u128":return{$kind:"u128"};case"u256":return{$kind:"u256"}}if("string"==typeof e)throw new Error(`Unknown type: ${e}`);if("vector"in e)return{$kind:"vector",vector:Mf(e.vector)};if("datatype"in e)return{$kind:"datatype",datatype:{typeName:`${tn(e.datatype.package)}::${e.datatype.module}::${e.datatype.type}`,typeParameters:e.datatype.typeParameters.map(e=>Mf(e))}};if("typeParameter"in e)return{$kind:"typeParameter",index:e.typeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}var Uf,Df,Ff,Lf,Vf=e=>{throw TypeError(e)},Kf=(e,t,n)=>t.has(e)||Vf("Cannot "+n),zf=(e,t,n)=>(Kf(e,t,"read from private field"),n?n.call(e):t.get(e)),qf=(e,t,n)=>t.has(e)?Vf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Zf=(e,t,n,r)=>(Kf(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class Wf extends Error{}class Gf extends gt{constructor({url:e,fetch:t=fetch,headers:n={},queries:r={},network:s="unknown",mvr:i}){super({network:s}),qf(this,Uf),qf(this,Df),qf(this,Ff),qf(this,Lf),Zf(this,Uf,e),Zf(this,Df,r),Zf(this,Ff,n),Zf(this,Lf,(...e)=>t(...e)),this.core=new Pf({graphqlClient:this,mvr:i})}async query(e){const t=await zf(this,Lf).call(this,zf(this,Uf),{method:"POST",headers:{"Content-Type":"application/json",...zf(this,Ff)},body:JSON.stringify({query:"string"==typeof e.query||e.query instanceof String?String(e.query):nf(e.query),variables:e.variables,extensions:e.extensions,operationName:e.operationName}),signal:e.signal});if(!t.ok)throw new Wf(`GraphQL request failed: ${t.statusText} (${t.status})`);return await t.json()}async execute(e,t){return this.query({...t,query:zf(this,Df)[e]})}}function Hf(e,t){return Cs(e.toString(16).padStart(2*t,"0").slice(2*-t))}function Jf(e,t){const n=Hf(e,t),r=function(e){for(let t=0;t<e.length;t++)if(0!==e[t])return t;return-1}(n);return-1===r?new Uint8Array([0]):n.slice(r)}function Yf(e){if(1!==e.length)throw new Error("Invalid base64Url character: "+e);const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(e);if(-1===t)throw new Error("Invalid base64Url character: "+e);const n=t.toString(2).padStart(6,"0");return Array.from(n).map(Number)}function Xf(e,t){if(e.length<2)throw new Error(`Input (s = ${e}) is not tightly packed because s.length < 2`);let n=function(e){let t=[];for(let n=0;n<e.length;n++){const r=Yf(e.charAt(n));t=t.concat(r)}return t}(e);const r=t%4;if(0===r);else if(1===r)n=n.slice(2);else{if(2!==r)throw new Error(`Input (s = ${e}) is not tightly packed because i%4 = 3 (i = ${t}))`);n=n.slice(4)}const s=(t+e.length-1)%4;if(3===s);else if(2===s)n=n.slice(0,n.length-2);else{if(1!==s)throw new Error(`Input (s = ${e}) is not tightly packed because (i + s.length - 1)%4 = 0 (i = ${t}))`);n=n.slice(0,n.length-4)}if(n.length%8!=0)throw new Error("We should never reach here...");const i=new Uint8Array(Math.floor(n.length/8));let a=0;for(let e=0;e<n.length;e+=8){const t=n.slice(e,e+8),r=parseInt(t.join(""),2);i[a++]=r}return(new TextDecoder).decode(i)}function Qf(e,t){const n=Xf(e.value,e.indexMod4),[r,s]=function(e){if("}"!==e.slice(-1)&&","!==e.slice(-1))throw new Error("Invalid claim");const t=JSON.parse("{"+e.slice(0,-1)+"}");if(1!==Object.keys(t).length)throw new Error("Invalid claim");const n=Object.keys(t)[0];return[n,t[n]]}(n);if(r!==t)throw new Error(`Invalid field name: found ${r} expected ${t}`);return s}Uf=new WeakMap,Df=new WeakMap,Ff=new WeakMap,Lf=new WeakMap;const ep=at.struct("ZkLoginSignature",{inputs:at.struct("ZkLoginSignatureInputs",{proofPoints:at.struct("ZkLoginSignatureInputsProofPoints",{a:at.vector(at.string()),b:at.vector(at.vector(at.string())),c:at.vector(at.string())}),issBase64Details:at.struct("ZkLoginSignatureInputsClaim",{value:at.string(),indexMod4:at.u8()}),headerBase64:at.string(),addressSeed:at.string()}),maxEpoch:at.u64(),userSignature:at.byteVector()});var tp,np,rp,sp,ip,ap=e=>{throw TypeError(e)},op=(e,t,n)=>t.has(e)||ap("Cannot "+n),cp=(e,t,n)=>(op(e,t,"read from private field"),n?n.call(e):t.get(e)),up=(e,t,n)=>t.has(e)?ap("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),dp=(e,t,n,r)=>(op(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),lp=(e,t,n)=>(op(e,t,"access private method"),n);tp=new WeakMap,np=new WeakMap,rp=new WeakMap,sp=new WeakSet,ip=function(){const e=pp(cp(this,tp),!0),t=new Uint8Array(e.length+1);return t[0]=this.flag(),t.set(e,1),tn(ks(gi(t,{dkLen:32})).slice(0,64))};let hp=class e extends Dh{constructor(e,{client:t}={}){super(),up(this,sp),up(this,tp),up(this,np),up(this,rp),dp(this,np,t),"string"==typeof e?dp(this,tp,Oe(e)):e instanceof Uint8Array?dp(this,tp,e):dp(this,tp,Uint8Array.from(e)),dp(this,rp,cp(this,tp).length!==cp(this,tp)[0]+1+32),cp(this,rp)&&dp(this,tp,pp(cp(this,tp)))}static fromBytes(t,{client:n,address:r,legacyAddress:s}={}){let i;if(!0===s?i=new e(pp(t,!0),{client:n}):!1===s?i=new e(pp(t,!1),{client:n}):r?(i=new e(pp(t,!1),{client:n}),i.toSuiAddress()!==r&&(i=new e(pp(t,!0),{client:n}))):i=new e(t,{client:n}),r&&i.toSuiAddress()!==r)throw new Error("Public key bytes do not match the provided address");return i}static fromProof(e,t){const{issBase64Details:n,addressSeed:r}=t,s=Qf(n,"iss"),i=fp(BigInt(r),s,{legacyAddress:!0});if(i.toSuiAddress()===e)return i;const a=fp(BigInt(r),s,{legacyAddress:!1});if(a.toSuiAddress()!==e)throw new Error("Proof does not match address");return a}equals(e){return super.equals(e)}toSuiAddress(){return cp(this,rp)?lp(this,sp,ip).call(this):super.toSuiAddress()}toRawBytes(){return cp(this,tp)}flag(){return ch.ZkLogin}async verify(e,t){throw Error("does not support")}verifyPersonalMessage(t,n){const r=mp(n);return gp({address:new e(r.publicKey).toSuiAddress(),bytes:Ie(t),signature:r.serializedSignature,intentScope:"PersonalMessage",client:cp(this,np)})}verifyTransaction(t,n){const r=mp(n);return gp({address:new e(r.publicKey).toSuiAddress(),bytes:Ie(t),signature:r.serializedSignature,intentScope:"TransactionData",client:cp(this,np)})}verifyAddress(e){return e===super.toSuiAddress()||e===lp(this,sp,ip).call(this)}};function fp(e,t,n){const r=n?.legacyAddress?Jf(e,32):Hf(e,32),s=(new TextEncoder).encode(function(e){return"accounts.google.com"===e?"https://accounts.google.com":e}(t)),i=new Uint8Array(1+s.length+r.length);return i.set([s.length],0),i.set(s,1),i.set(r,1+s.length),new hp(i,n)}function pp(e,t=!1){const n=e[0]+1,r=BigInt(`0x${_e(e.slice(n))}`),s=t?Jf(r,32):Hf(r,32),i=new Uint8Array(n+s.length);return i.set(e.slice(0,n),0),i.set(s,n),i}async function gp({address:e,bytes:t,signature:n,intentScope:r,client:s=new Gf({url:"https://graphql.mainnet.sui.io/graphql"})}){const i=await s.core.verifyZkLoginSignature({bytes:t,signature:n,intentScope:r,author:e});return!0===i.success&&0===i.errors.length}function mp(e){const t="string"==typeof e?Oe(e):e;if(t[0]!==ch.ZkLogin)throw new Error("Invalid signature scheme");const n=t.slice(1),{inputs:r,maxEpoch:s,userSignature:i}=function(e){return ep.parse("string"==typeof e?Oe(e):e)}(n),{issBase64Details:a,addressSeed:o}=r,c=Qf(a,"iss"),u=fp(BigInt(o),c);return{serializedSignature:Ie(t),signatureScheme:"ZkLogin",zkLogin:{inputs:r,maxEpoch:s,userSignature:i,iss:c,addressSeed:BigInt(o)},signature:t,publicKey:u.toRawBytes()}}function yp(e){const t=Oe(e),n=dh[t[0]];switch(n){case"Passkey":return Lh(e);case"MultiSig":return{serializedSignature:e,signatureScheme:n,multisig:xr.MultiSig.parse(t.slice(1)),bytes:t,signature:void 0};case"ZkLogin":return mp(e);case"ED25519":case"Secp256k1":case"Secp256r1":return Fh(e);default:throw new Error("Unsupported signature scheme")}}const bp="suiprivkey";class wp{async signWithIntent(e,t){const n=oh(t,e),r=gi(n,{dkLen:32});return{signature:function({signature:e,signatureScheme:t,publicKey:n}){if(!n)throw new Error("`publicKey` is required");const r=n.toRawBytes(),s=new Uint8Array(1+e.length+r.length);return s.set([ch[t]]),s.set(e,1),s.set(r,1+e.length),Ie(s)}({signature:await this.sign(r),signatureScheme:this.getKeyScheme(),publicKey:this.getPublicKey()}),bytes:Ie(e)}}async signTransaction(e){return this.signWithIntent(e,"TransactionData")}async signPersonalMessage(e){const{signature:t}=await this.signWithIntent(at.byteVector().serialize(e).toBytes(),"PersonalMessage");return{bytes:Ie(e),signature:t}}async signAndExecuteTransaction({transaction:e,client:t}){const n=await e.build({client:t}),{signature:r}=await this.signTransaction(n);return(await t.core.executeTransaction({transaction:n,signatures:[r]})).transaction}toSuiAddress(){return this.getPublicKey().toSuiAddress()}}class vp extends wp{}function Ep(e){const{prefix:t,words:n}=Ee.decode(e);if(t!==bp)throw new Error("invalid private key prefix");const r=new Uint8Array(Ee.fromWords(n)),s=r.slice(1),i=dh[r[0]];return{scheme:i,schema:i,secretKey:s}}function kp(e,t){if(32!==e.length)throw new Error("Invalid bytes length");const n=ch[t],r=new Uint8Array(e.length+1);return r.set([n]),r.set(e,1),Ee.encode(bp,Ee.toWords(r))}function Sp(e,t,n,r){cs(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},r),{c:i,dkLen:a,asyncTick:o}=s;if(as(i),as(a),as(o),i<1)throw new Error("iterations (c) should be >= 1");const c=Bs(t),u=Bs(n),d=new Uint8Array(a),l=hh.create(e,c),h=l._cloneInto().update(u);return{c:i,dkLen:a,asyncTick:o,DK:d,PRF:l,PRFSalt:h}}function Op(e,t,n,r){const{c:s,dkLen:i,DK:a,PRF:o,PRFSalt:c}=Sp(e,t,n,r);let u;const d=new Uint8Array(4),l=fs(d),h=new Uint8Array(o.outputLen);for(let e=1,t=0;t<i;e++,t+=o.outputLen){const n=a.subarray(t,t+o.outputLen);l.setInt32(0,e,!1),(u=c._cloneInto(u)).update(d).digestInto(h),n.set(h.subarray(0,n.length));for(let e=1;e<s;e++){o._cloneInto(u).update(h).digestInto(h);for(let e=0;e<n.length;e++)n[e]^=h[e]}}return function(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),hs(s),n}(o,c,a,u,h)}function xp(e){if("string"!=typeof e)throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function Ip(e,t=""){return Op(Td,function(e){const t=xp(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}(e).nfkd,(e=>xp("mnemonic"+e))(t),{c:2048,dkLen:64})}function Tp(e){return!!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(e)}function _p(e){return!!new RegExp("^m\\/(54|74)'\\/784'\\/[0-9]+'\\/[0-9]+\\/[0-9]+$").test(e)}function Ap(e){return Ip(e,"")}const Cp=Td,jp=new RegExp("^m(\\/[0-9]+')+$"),Pp=e=>e.replace("'",""),Bp=(e,t,n=2147483648)=>{if(!(e=>!!jp.test(e)&&!e.split("/").slice(1).map(Pp).some(isNaN))(e))throw new Error("Invalid derivation path");const{key:r,chainCode:s}=(e=>{const t=hh.create(Cp,"ed25519 seed").update(Te(e)).digest();return{key:t.slice(0,32),chainCode:t.slice(32)}})(t);return e.split("/").slice(1).map(Pp).map(e=>parseInt(e,10)).reduce((e,t)=>(({key:e,chainCode:t},n)=>{const r=new ArrayBuffer(4);new DataView(r).setUint32(0,n);const s=new Uint8Array(1+e.length+r.byteLength);s.set(new Uint8Array(1).fill(0)),s.set(e,1),s.set(new Uint8Array(r,0,r.byteLength),e.length+1);const i=hh.create(Cp,t).update(s).digest();return{key:i.slice(0,32),chainCode:i.slice(32)}})(e,t+n),{key:r,chainCode:s})};class Np extends Dh{constructor(e){if(super(),"string"==typeof e?this.data=Oe(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),32!==this.data.length)throw new Error(`Invalid public key input. Expected 32 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return ch.ED25519}async verify(e,t){let n;if("string"==typeof t){const e=Fh(t);if("ED25519"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Uh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Jl.verify(n,e,this.toRawBytes())}}Np.SIZE=32;const Rp="m/44'/784'/0'/0'/0'";class $p extends vp{constructor(e){if(super(),e)this.keypair={publicKey:e.publicKey,secretKey:e.secretKey.slice(0,32)};else{const e=Jl.utils.randomPrivateKey();this.keypair={publicKey:Jl.getPublicKey(e),secretKey:e}}}getKeyScheme(){return"ED25519"}static generate(){const e=Jl.utils.randomPrivateKey();return new $p({publicKey:Jl.getPublicKey(e),secretKey:e})}static fromSecretKey(e,t){if("string"==typeof e){const n=Ep(e);if("ED25519"!==n.schema)throw new Error(`Expected a ED25519 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=e.length;if(32!==n)throw new Error(`Wrong secretKey size. Expected 32 bytes, got ${n}.`);const r={publicKey:Jl.getPublicKey(e),secretKey:e};if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),n=Jl.sign(t,e);if(!Jl.verify(n,t,r.publicKey))throw new Error("provided secretKey is invalid")}return new $p(r)}getPublicKey(){return new Np(this.keypair.publicKey)}getSecretKey(){return kp(this.keypair.secretKey.slice(0,32),this.getKeyScheme())}async sign(e){return Jl.sign(e,this.keypair.secretKey)}static deriveKeypair(e,t){if(null==t&&(t=Rp),!Tp(t))throw new Error("Invalid derivation path");const{key:n}=Bp(t,function(e){return _e(Ap(e))}(e));return $p.fromSecretKey(n)}static deriveKeypairFromSeed(e,t){if(null==t&&(t=Rp),!Tp(t))throw new Error("Invalid derivation path");const{key:n}=Bp(t,e);return $p.fromSecretKey(n)}}const Mp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Up={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Dp=BigInt(2);const Fp=fl(Mp.p,void 0,void 0,{sqrt:function(e){const t=Mp.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,l=nl(d,n,t)*d%t,h=nl(l,n,t)*d%t,f=nl(h,Dp,t)*u%t,p=nl(f,s,t)*f%t,g=nl(p,i,t)*p%t,m=nl(g,o,t)*g%t,y=nl(m,c,t)*m%t,b=nl(y,o,t)*g%t,w=nl(b,n,t)*d%t,v=nl(w,a,t)*p%t,E=nl(v,r,t)*u%t,k=nl(E,Dp,t);if(!Fp.eql(Fp.sqr(k),e))throw new Error("Cannot find square root");return k}}),Lp=_h({...Mp,Fp:Fp,lowS:!0,endo:Up},Id),Vp=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Kp=(()=>Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)))(),zp=(()=>Kp.map(e=>(9*e+5)%16))(),qp=(()=>{const e=[[Kp],[zp]];for(let t=0;t<4;t++)for(let n of e)n.push(n[t].map(e=>Vp[e]));return e})(),Zp=(()=>qp[0])(),Wp=(()=>qp[1])(),Gp=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),Hp=Zp.map((e,t)=>e.map(e=>Gp[t][e])),Jp=Wp.map((e,t)=>e.map(e=>Gp[t][e])),Yp=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Xp=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Qp(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const eg=new Uint32Array(16);class tg extends Vs{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:s}=this;return[e,t,n,r,s]}set(e,t,n,r,s){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(e,t){for(let n=0;n<16;n++,t+=4)eg[n]=e.getUint32(t,!0);let n=0|this.h0,r=n,s=0|this.h1,i=s,a=0|this.h2,o=a,c=0|this.h3,u=c,d=0|this.h4,l=d;for(let e=0;e<5;e++){const t=4-e,h=Yp[e],f=Xp[e],p=Zp[e],g=Wp[e],m=Hp[e],y=Jp[e];for(let t=0;t<16;t++){const r=gs(n+Qp(e,s,a,c)+eg[p[t]]+h,m[t])+d|0;n=d,d=c,c=0|gs(a,10),a=s,s=r}for(let e=0;e<16;e++){const n=gs(r+Qp(t,i,o,u)+eg[g[e]]+f,y[e])+l|0;r=l,l=u,u=0|gs(o,10),o=i,i=n}}this.set(this.h1+a+u|0,this.h2+c+l|0,this.h3+d+r|0,this.h4+n+i|0,this.h0+s+o|0)}roundClean(){hs(eg)}destroy(){this.destroyed=!0,hs(this.buffer),this.set(0,0,0,0,0)}}const ng=$s(()=>new tg),rg=Lp.ProjectivePoint,sg=(e=>{return te((n=t=>e(e(t)),Y(t=4),H(n),{encode(e){if(!W(e))throw new Error("checksum.encode: input should be Uint8Array");const r=n(e).slice(0,t),s=new Uint8Array(e.length+t);return s.set(e),s.set(r,e.length),s},decode(e){if(!W(e))throw new Error("checksum.decode: input should be Uint8Array");const r=e.slice(0,-t),s=e.slice(-t),i=n(r).slice(0,t);for(let e=0;e<t;e++)if(i[e]!==s[e])throw new Error("Invalid checksum");return r}}),ge);var t,n})(Id);function ig(e){os(e);const t=0===e.length?"0":ks(e);return BigInt("0x"+t)}const ag=js("Bitcoin seed"),og={private:76066276,public:76067358},cg=2147483648,ug=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error("invalid number, should be from 0 to 2**32-1, got "+e);const t=new Uint8Array(4);return fs(t).setUint32(0,e,!1),t};class dg{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return fs(this.pubHash).getUint32(0,!1)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){const e=this.privateKey;if(!e)throw new Error("No private key");return sg.encode(this.serialize(this.versions.private,Ns(new Uint8Array([0]),e)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return sg.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(e,t=og){if(os(e),8*e.length<128||8*e.length>512)throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+e.length);const n=hh(Td,ag,e);return new dg({versions:t,chainCode:n.slice(32),privateKey:n.slice(0,32)})}static fromExtendedKey(e,t=og){const n=sg.decode(e),r=fs(n),s=r.getUint32(0,!1),i={versions:t,depth:n[4],parentFingerprint:r.getUint32(5,!1),index:r.getUint32(9,!1),chainCode:n.slice(13,45)},a=n.slice(45),o=0===a[0];if(s!==t[o?"private":"public"])throw new Error("Version mismatch");return new dg(o?{...i,privateKey:a.slice(1)}:{...i,publicKey:a})}static fromJSON(e){return dg.fromExtendedKey(e.xpriv)}constructor(e){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!e||"object"!=typeof e)throw new Error("HDKey.constructor must not be called directly");if(this.versions=e.versions||og,this.depth=e.depth||0,this.chainCode=e.chainCode||null,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(e.publicKey&&e.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(e.privateKey){if(!Lp.utils.isValidPrivateKey(e.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof e.privateKey?e.privateKey:ig(e.privateKey),this.privKeyBytes=function(e){if("bigint"!=typeof e)throw new Error("bigint expected");return Cs(e.toString(16).padStart(64,"0"))}(this.privKey),this.pubKey=Lp.getPublicKey(e.privateKey,!0)}else{if(!e.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=rg.fromHex(e.publicKey).toRawBytes(!0)}var t;this.pubHash=(t=this.pubKey,ng(Id(t)))}derive(e){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;const t=e.replace(/^[mM]'?\//,"").split("/");let n=this;for(const e of t){const t=/^(\d+)('?)$/.exec(e),r=t&&t[1];if(!t||3!==t.length||"string"!=typeof r)throw new Error("invalid child index: "+e);let s=+r;if(!Number.isSafeInteger(s)||s>=cg)throw new Error("Invalid index");"'"===t[2]&&(s+=cg),n=n.deriveChild(s)}return n}deriveChild(e){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let t=ug(e);if(e>=cg){const e=this.privateKey;if(!e)throw new Error("Could not derive hardened child key");t=Ns(new Uint8Array([0]),e,t)}else t=Ns(this.pubKey,t);const n=hh(Td,this.chainCode,t),r=ig(n.slice(0,32)),s=n.slice(32);if(!Lp.utils.isValidPrivateKey(r))throw new Error("Tweak bigger than curve order");const i={versions:this.versions,chainCode:s,depth:this.depth+1,parentFingerprint:this.fingerprint,index:e};try{if(this.privateKey){const e=tl(this.privKey+r,Lp.CURVE.n);if(!Lp.utils.isValidPrivateKey(e))throw new Error("The tweak was out of range or the resulted private key is invalid");i.privateKey=e}else{const e=rg.fromHex(this.pubKey).add(rg.fromPrivateKey(r));if(e.equals(rg.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=e.toRawBytes(!0)}return new dg(i)}catch(t){return this.deriveChild(e+1)}}sign(e){if(!this.privateKey)throw new Error("No privateKey set!");return os(e,32),Lp.sign(e,this.privKey).toCompactRawBytes()}verify(e,t){if(os(e,32),os(t,64),!this.publicKey)throw new Error("No publicKey set!");let n;try{n=Lp.Signature.fromCompact(t)}catch(e){return!1}return Lp.verify(n,e,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(e,t){if(!this.chainCode)throw new Error("No chainCode set");return os(t,33),Ns(ug(e),new Uint8Array([this.depth]),ug(this.parentFingerprint),ug(this.index),this.chainCode,t)}}class lg extends Dh{constructor(e){if(super(),"string"==typeof e?this.data=Oe(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return ch.Secp256k1}async verify(e,t){let n;if("string"==typeof t){const e=Fh(t);if("Secp256k1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Uh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Lp.verify(Lp.Signature.fromCompact(n),Mh(e),this.toRawBytes())}}lg.SIZE=33;class hg extends vp{constructor(e){if(super(),e)this.keypair=e;else{const e=Lp.utils.randomPrivateKey(),t=Lp.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256k1"}static generate(){return new hg}static fromSecretKey(e,t){if("string"==typeof e){const n=Ep(e);if("Secp256k1"!==n.schema)throw new Error(`Expected a Secp256k1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=Lp.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=ks(gi(t,{dkLen:32})),s=Lp.sign(r,e);if(!Lp.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new hg({publicKey:n,secretKey:e})}static fromSeed(e){const t=Lp.getPublicKey(e,!0);return new hg({publicKey:t,secretKey:e})}getPublicKey(){return new lg(this.keypair.publicKey)}getSecretKey(){return kp(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Mh(e);return Lp.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/54'/784'/0'/0/0"),!_p(t))throw new Error("Invalid derivation path");const n=dg.fromMasterSeed(Ap(e)).derive(t);if(null==n.publicKey||null==n.privateKey)throw new Error("Invalid key");return new hg({publicKey:n.publicKey,secretKey:n.privateKey})}}class fg extends Dh{constructor(e){if(super(),"string"==typeof e?this.data=Oe(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return ch.Secp256r1}async verify(e,t){let n;if("string"==typeof t){const e=yp(t);if("Secp256r1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Uh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return $h.verify($h.Signature.fromCompact(n),Mh(e),this.toRawBytes())}}fg.SIZE=33;class pg extends vp{constructor(e){if(super(),e)this.keypair=e;else{const e=$h.utils.randomPrivateKey(),t=$h.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256r1"}static generate(){return new pg}static fromSecretKey(e,t){if("string"==typeof e){const n=Ep(e);if("Secp256r1"!==n.schema)throw new Error(`Expected a Secp256r1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=$h.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=ks(gi(t,{dkLen:32})),s=$h.sign(r,e,{lowS:!0});if(!$h.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new pg({publicKey:n,secretKey:e})}static fromSeed(e){const t=$h.getPublicKey(e,!0);return new pg({publicKey:t,secretKey:e})}getPublicKey(){return new fg(this.keypair.publicKey)}getSecretKey(){return kp(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Mh(e);return $h.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/74'/784'/0'/0/0"),!_p(t))throw new Error("Invalid derivation path");const n=dg.fromMasterSeed(Ap(e)).derive(t).privateKey;return pg.fromSecretKey(n)}}var gg;function mg(e,t=!1){let n,r;if("object"==typeof e){if(!t)throw new Error("Invalid secret key format");r=Oe(e.privateKey),n=e.schema}else{const t=Ep(e);n=t.schema,r=t.secretKey}switch(n){case"ED25519":{let e=r;return 64===r.length&&(e=r.slice(0,32)),$p.fromSecretKey(e)}case"Secp256k1":return hg.fromSecretKey(r);case"Secp256r1":return pg.fromSecretKey(r);default:throw new Error(`Invalid keypair schema: ${n}`)}}async function yg(e,t){const n=await e.signPersonalMessage(t);return bg("string"==typeof n?n:n.signature,!0)}function bg(e,t=!1){const n=yp(e);let r=o.from(n.signature).toString("hex"),s=o.from(n.publicKey).toString("base64"),i=gg.KP_SECP256;if("Secp256k1"===n.signatureScheme||"Secp256r1"===n.signatureScheme)i=gg.KP_SECP256;else if("ED25519"===n.signatureScheme)i=t?gg.KP_ED25519:gg.UI_ED25519;else{if("ZkLogin"!==n.signatureScheme)throw new Error(`Unsupported signature scheme: ${n.signatureScheme}`);i=gg.ZK_ED25519}return`${r}${i}${s}`}function wg(e,t=18){if(!e&&0!==e)return"0";try{const n=new r(e);if(n.isNaN())return"0";return n.multipliedBy(new r(10).pow(t)).integerValue(r.ROUND_DOWN).toString(10)}catch(e){return"0"}}function vg(e,t=18){return new r(e).multipliedBy(new r(10).pow(t))}function Eg(e){return e instanceof Error?e.message:"string"==typeof e?e:String(e)}function kg(e){const t=function(){try{if(void 0!==import.meta&&import.meta.url){const e=d(import.meta.url);return u.dirname(e)}}catch(e){}return"undefined"!=typeof __dirname?__dirname:process.cwd()}();let n=null;if(u.isAbsolute(e))n=e;else{const r=u.resolve(t,".."),s=u.resolve(r,e);if(c.existsSync(s))n=s;else{const r=function(e){let t=e;const n=u.parse(t).root;for(;t!==n;){const e=u.join(t,"package.json");if(c.existsSync(e))try{if("@dipcoinlab/perp-client-ts"===JSON.parse(c.readFileSync(e,"utf-8")).name)return t}catch(e){}const n=u.dirname(t);if(n===t)break;t=n}return null}(t);if(r){const t=u.resolve(r,"dist",e);c.existsSync(t)&&(n=t)}if(!n){const t=u.resolve(process.cwd(),e);c.existsSync(t)&&(n=t)}}}if(!n||!c.existsSync(n))return{packages:[]};const r=JSON.parse(c.readFileSync(n).toString());return r.packages&&Array.isArray(r.packages)||(r.packages=[]),r}!function(e){e.KP_SECP256="0",e.KP_ED25519="1",e.UI_ED25519="2",e.ZK_ED25519="3"}(gg||(gg={}));class Sg{httpClient;keypair;subKeypair;walletAddress;subAddress;options;jwtToken;subJwtToken;isAuthenticating=!1;isSubAuthenticating=!1;exchangeOnChain;deploymentConfig;suiClient;transactionBuilder;priceServiceConnection;pythClient;tradingPairsCache;tradingPairsCacheTimestamp;constructor(n,r){this.options=r,this.httpClient=new fd(r.apiBaseUrl),this.keypair="string"==typeof n?mg(n):n,r.subAccountKey&&(this.subKeypair=mg(r.subAccountKey),this.subAddress=this.subKeypair.getPublicKey().toSuiAddress()),this.walletAddress=this.keypair.getPublicKey().toSuiAddress(),this.httpClient.setWalletAddress(this.walletAddress),this.deploymentConfig=kg(`config/deployed/${r.network}/main_contract.json`);const s=r.customRpc||function(e){switch(e){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${e}`)}}(r.network);this.suiClient=new ro({url:s}),this.exchangeOnChain=new e(this.deploymentConfig,this.suiClient,this.keypair);const i=this.getDeploymentPackageId(),a=this.getDeploymentProtocolConfigId();this.transactionBuilder=new t(i,a,this.deploymentConfig,this.suiClient)}get address(){return this.walletAddress}get subAccountAddress(){return this.subAddress}get optionsField(){return this.options}async authenticate(){try{if(this.jwtToken)return{status:!0,data:this.jwtToken};if(this.isAuthenticating&&(await new Promise(e=>setTimeout(e,100)),this.jwtToken))return{status:!0,data:this.jwtToken};this.isAuthenticating=!0;const e=(new TextEncoder).encode(dd),t=await yg(this.keypair,e),n=await this.httpClient.post(ud.AUTHORIZE,{userAddress:this.walletAddress,isTermAccepted:!0,signature:t});return 200===n.code&&n.data?.token?(this.jwtToken=n.data.token,this.httpClient.setAuthToken(this.jwtToken),this.isAuthenticating=!1,{status:!0,data:this.jwtToken}):(this.isAuthenticating=!1,{status:!1,error:n.message||"Failed to authenticate"})}catch(e){return this.isAuthenticating=!1,{status:!1,error:Eg(e)}}}async authenticateSub(){if(!this.subKeypair)return{status:!1,error:"Sub-account keypair not configured"};try{if(this.subJwtToken)return{status:!0,data:this.subJwtToken};if(this.isSubAuthenticating&&(await new Promise(e=>setTimeout(e,100)),this.subJwtToken))return{status:!0,data:this.subJwtToken};this.isSubAuthenticating=!0;const e=(new TextEncoder).encode(dd),t=await yg(this.subKeypair,e),n=this.subKeypair.getPublicKey().toSuiAddress(),r=await this.httpClient.post(ud.AUTHORIZE,{userAddress:n,isTermAccepted:!0,signature:t});return 200===r.code&&r.data?.token?(this.subJwtToken=r.data.token,this.isSubAuthenticating=!1,{status:!0,data:this.subJwtToken}):(this.isSubAuthenticating=!1,{status:!1,error:r.message||"Failed to authenticate sub-account"})}catch(e){return this.isSubAuthenticating=!1,{status:!1,error:Eg(e)}}}async authenticateForTrading(){if(this.subKeypair){const e=await this.authenticateSub();return e.status&&e.data?(this.httpClient.setAuthToken(e.data),this.subAddress&&this.httpClient.setWalletAddress(this.subAddress),e):e}return this.authenticate()}restoreMainAuth(){this.httpClient.setWalletAddress(this.walletAddress),this.jwtToken&&this.httpClient.setAuthToken(this.jwtToken)}async getJWTToken(e=!1){return e&&(this.jwtToken=void 0,this.httpClient.setAuthToken("")),this.authenticate()}clearAuth(){this.jwtToken=void 0,this.subJwtToken=void 0,this.httpClient.setAuthToken("")}async placeOrder(e){try{const t=await this.authenticateForTrading();if(!t.status)return this.restoreMainAuth(),{status:!1,error:t.error||"Authentication failed"};if(!(e.symbol&&e.side&&e.orderType&&e.quantity&&e.leverage))throw new Error("Missing required order parameters");if(e.orderType===gd.LIMIT&&!e.price)throw new Error("Price is required for LIMIT orders");const{symbol:s,side:i,orderType:a,quantity:o,price:c,leverage:u,market:d,reduceOnly:l=!1,clientId:h="",creator:f,tpTriggerPrice:p,tpOrderType:g=gd.MARKET,tpOrderPrice:m="",slTriggerPrice:y,slOrderType:b=gd.MARKET,slOrderPrice:w=""}=e,v=f||this.walletAddress,E=this.subKeypair||this.keypair;if(!d)throw new Error("Market (PerpetualID) is required. Please provide the market parameter with the PerpetualID for the trading pair.");const k=c&&""!==c?vg(c):new r(0),S=vg(o),O=vg(u),x=new r(0),I=new r(+new Date),T={market:d,creator:v,isLong:i===pd.BUY,reduceOnly:l,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:a===gd.LIMIT?k:new r(0),leverage:O,expiration:x,salt:I};let _=null,A=null;p&&(A=new r(Date.now()+1),_={market:T.market,creator:v,isLong:!T.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:g===gd.LIMIT?vg(m||p):vg(""),leverage:O,expiration:x,salt:A});let C=null,j=null;y&&(j=new r(Date.now()+2),C={market:T.market,creator:v,isLong:!T.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:b===gd.LIMIT?vg(w||y):vg(""),leverage:O,expiration:x,salt:j});const P=n.getOrderMessageForUIWallet(T),B=(new TextEncoder).encode(P),N=await yg(E,B);let R,$;if(_){const e=n.getOrderMessageForUIWallet(_),t=(new TextEncoder).encode(e);R=await yg(E,t)}if(C){const e=n.getOrderMessageForUIWallet(C),t=(new TextEncoder).encode(e);$=await yg(E,t)}const M={symbol:s,side:i,orderType:a,quantity:wg(o),price:wg(c||""),leverage:wg(u),salt:I.toString(),creator:v,clientId:h,reduceOnly:l,orderSignature:N};p&&R&&(M.tpOrderSignature=R,M.tpTriggerPrice=wg(p),M.tpOrderType=g,M.tpOrderPrice=g===gd.LIMIT?wg(m||p):wg(""),M.tpSalt=A?.toString(),M.triggerWay="oracle"),y&&$&&(M.slOrderSignature=$,M.slTriggerPrice=wg(y),M.slOrderType=b,M.slOrderPrice=b===gd.LIMIT?wg(w||y):wg(""),M.slSalt=j?.toString());const U=await this.httpClient.post(ud.PLACE_ORDER,M);if(1e3===U.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(ud.PLACE_ORDER,M);if(this.restoreMainAuth(),200===e.code)return{status:!0,data:e}}return this.restoreMainAuth(),{status:!1,error:"Authentication expired and refresh failed"}}return this.restoreMainAuth(),200===U.code?{status:!0,data:U}:{status:!1,error:U.message||"Order failed",data:U}}catch(e){return this.restoreMainAuth(),{status:!1,error:Eg(e)}}}async cancelOrder(e){try{const t=await this.authenticateForTrading();if(!t.status)return this.restoreMainAuth(),{status:!1,error:t.error||"Authentication failed"};const{symbol:n,orderHashes:r,parentAddress:s=this.walletAddress}=e;if(!r||0===r.length)throw new Error("Order hashes are required");const i=this.subKeypair||this.keypair,a={orderHashes:r},o=(new TextEncoder).encode(JSON.stringify(a)),c={symbol:n,orderHashes:r,signature:await yg(i,o),parentAddress:s},u=await this.httpClient.post(ud.CANCEL_ORDER,c);if(1e3===u.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(ud.CANCEL_ORDER,c);if(this.restoreMainAuth(),200===e.code)return{status:!0,data:e}}return this.restoreMainAuth(),{status:!1,error:"Authentication expired and refresh failed"}}return this.restoreMainAuth(),200===u.code?{status:!0,data:u}:{status:!1,error:u.message||"Cancellation Failed",data:u}}catch(e){return this.restoreMainAuth(),{status:!1,error:Eg(e)}}}async adjustLeverage(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const{symbol:n,leverage:r,marginType:s="ISOLATED"}=e;if(!n)throw new Error("Symbol is required for adjusting leverage");if(!this.isPositiveNumber(r))throw new Error("Leverage must be greater than zero");const i={symbol:n,marginType:s,leverage:wg(r)};let a=await this.httpClient.post(ud.ADJUST_LEVERAGE,i);if(1e3===a.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};a=await this.httpClient.post(ud.ADJUST_LEVERAGE,i)}return 200===a.code?{status:!0,data:a}:{status:!1,data:a,error:a.message||"Failed to adjust leverage"}}catch(e){return{status:!1,error:Eg(e)}}}async getUserConfig(e){if(!e)return{status:!1,error:"Symbol is required"};try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={symbol:e};let r=await this.httpClient.get(ud.GET_USER_CONFIG,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(ud.GET_USER_CONFIG,{params:n})}if(200===r.code&&r.data){const t=Array.isArray(r.data)?r.data[0]:r.data;if(!t)return{status:!1,error:"User config not found"};const n=t.leverage??t.leverageWei??"0";return{status:!0,data:{...t,symbol:t.symbol||e,marginType:t.marginType||t.marginTypeEnum,leverageWei:n,leverage:this.formatWeiToNormal(n)}}}return{status:!1,error:r.message||"Failed to fetch user config"}}catch(e){return{status:!1,error:Eg(e)}}}async placePositionTpSlOrders(e){try{const t=await this.authenticateForTrading();if(!t.status)return this.restoreMainAuth(),{status:!1,error:t.error||"Authentication failed"};const s=this.subKeypair||this.keypair,{symbol:i,market:a,side:o,isLong:c,leverage:u,quantity:d,reduceOnly:l=!0,postOnly:h=!1,orderbookOnly:f=!0,ioc:p=!1,tp:g,sl:m}=e;if(!this.isPositiveNumber(d))return{status:!1,error:"Quantity must be greater than zero"};const y=this.hasTpSlOrderConfig(g,d),b=this.hasTpSlOrderConfig(m,d);if(!y&&!b)return{status:!1,error:"At least one TP or SL configuration is required"};const w=vg(u),v=wg(u),E=new r(0),k=new r(+new Date),S=k.plus(1),O={symbol:i,side:o,leverage:v,creator:this.walletAddress},x=async e=>{let t=await this.httpClient.post(ud.PLAN_CLOSE_ORDER,e);if(1e3===t.code){this.clearAuth();(await this.authenticate()).status&&(t=await this.httpClient.post(ud.PLAN_CLOSE_ORDER,e))}return t},I={};let T,_;if(y&&g){if(!this.isPositiveNumber(g.triggerPrice))return{status:!1,error:"TP trigger price must be greater than zero"};const e=g.salt?new r(g.salt):k,t=vg(g.quantity??d),i=(g.orderType||gd.MARKET)===gd.LIMIT?vg(g.orderPrice??g.triggerPrice??"0"):new r(0),o={market:a,creator:this.walletAddress,isLong:c,reduceOnly:l,postOnly:h,orderbookOnly:f,ioc:p,quantity:t,price:i,leverage:w,expiration:E,salt:e},u=n.getOrderMessageForUIWallet(o),m=await yg(s,(new TextEncoder).encode(u));T={...O,tpOrderType:g.orderType||gd.MARKET,tpTpslType:g.tpslType||"position",tpTriggerPrice:wg(g.triggerPrice),tpOrderPrice:(g.orderType||gd.MARKET)===gd.LIMIT?wg(g.orderPrice??g.triggerPrice??"0"):"0",tpQuantity:wg(g.quantity??d),tpTriggerWay:g.triggerWay||"oracle",tpSalt:e.toString(),tpOrderSignature:m},void 0!==g.planId&&(T.tpPlanId=g.planId)}if(b&&m){if(!this.isPositiveNumber(m.triggerPrice))return{status:!1,error:"SL trigger price must be greater than zero"};const e=m.salt?new r(m.salt):S,t=vg(m.quantity??d),i=(m.orderType||gd.MARKET)===gd.LIMIT?vg(m.orderPrice??m.triggerPrice??"0"):new r(0),o={market:a,creator:this.walletAddress,isLong:c,reduceOnly:l,postOnly:h,orderbookOnly:f,ioc:p,quantity:t,price:i,leverage:w,expiration:E,salt:e},u=n.getOrderMessageForUIWallet(o),g=await yg(s,(new TextEncoder).encode(u));_={...O,slOrderType:m.orderType||gd.MARKET,slTpslType:m.tpslType||"position",slTriggerPrice:wg(m.triggerPrice),slOrderPrice:(m.orderType||gd.MARKET)===gd.LIMIT?wg(m.orderPrice??m.triggerPrice??"0"):"0",slQuantity:wg(m.quantity??d),slTriggerWay:m.triggerWay||"oracle",slSalt:e.toString(),slOrderSignature:g},void 0!==m.planId&&(_.slPlanId=m.planId)}if(y&&b&&T&&_){const e={...T,..._},t=await x(e);I.tpResult=t,I.slResult=t}else y&&T?I.tpResult=await x(T):b&&_&&(I.slResult=await x(_));return[I.tpResult,I.slResult].some(e=>e&&200===e.code)?(this.restoreMainAuth(),{status:!0,data:I}):(this.restoreMainAuth(),{status:!1,data:I,error:I.tpResult?.message||I.slResult?.message||"Failed to place TP/SL order"})}catch(e){return this.restoreMainAuth(),{status:!1,error:Eg(e)}}}async getPositionTpSl(e,t="normal"){try{const n=await this.authenticate();if(!n.status)return{status:!1,error:n.error||"Authentication failed"};const r={positionId:e,tpslType:t};let s=await this.httpClient.get(ud.GET_POSITION_TPSL,{params:r});if(1e3===s.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};s=await this.httpClient.get(ud.GET_POSITION_TPSL,{params:r})}if(200===s.code){const e=Array.isArray(s.data)?s.data:s.data?.data||[];return{status:!0,data:e.map(e=>this.transformPositionTpSlOrder(e))}}return{status:!1,error:s.message||"Failed to fetch TP/SL orders"}}catch(e){return{status:!1,error:Eg(e)}}}async cancelTpSlOrders(e){return this.cancelOrder(e)}async getAccountInfo(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.parentAddress&&(n.parentAddress=e.parentAddress);const r=await this.httpClient.get(ud.GET_ACCOUNT_INFO,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ud.GET_ACCOUNT_INFO,{params:n});if(200===e.code&&e.data)return{status:!0,data:{walletBalance:e.data.walletBalance||"0",totalUnrealizedProfit:e.data.totalUnrealizedProfit||"0",accountValue:e.data.accountValue||"0",freeCollateral:e.data.freeCollateral||"0",totalMargin:e.data.totalMargin||"0"}}}return{status:!1,error:"Authentication expired and refresh failed"}}return 200===r.code&&r.data?{status:!0,data:{walletBalance:r.data.walletBalance||"0",totalUnrealizedProfit:r.data.totalUnrealizedProfit||"0",accountValue:r.data.accountValue||"0",freeCollateral:r.data.freeCollateral||"0",totalMargin:r.data.totalMargin||"0"}}:{status:!1,error:r.message||"Failed to get account info"}}catch(e){return{status:!1,error:Eg(e)}}}async getPositions(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};"string"==typeof e?n.symbol=e:e&&(e.symbol&&(n.symbol=e.symbol),e.parentAddress&&(n.parentAddress=e.parentAddress));const r=await this.httpClient.get(ud.GET_POSITIONS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ud.GET_POSITIONS,{params:n});if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}}return{status:!1,error:"Authentication expired and refresh failed"}}if(200===r.code){return{status:!0,data:Array.isArray(r.data)?r.data:r.data?.data||[]}}return{status:!1,error:r.message||"Failed to get positions"}}catch(e){return{status:!1,error:Eg(e)}}}async getTradingPairs(){try{const e=await this.authenticate();if(!e.status)return{status:!1,error:e.error||"Authentication failed"};const t=await this.httpClient.get(ud.GET_TRADING_PAIRS);if(1e3===t.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ud.GET_TRADING_PAIRS);if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}}return{status:!1,error:"Authentication expired and refresh failed"}}if(200===t.code){return{status:!0,data:Array.isArray(t.data)?t.data:t.data?.data||[]}}return{status:!1,error:t.message||"Failed to get trading pairs"}}catch(e){return{status:!1,error:Eg(e)}}}async getPerpetualID(e){try{const t=await this.getTradingPairs();if(t.status&&t.data){const n=t.data.find(t=>t.symbol===e);return n?.perpId||null}return null}catch(e){return null}}async getOpenOrders(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};"string"==typeof e?n.symbol=e:e&&(e.symbol&&(n.symbol=e.symbol),e.page&&(n.page=e.page),e.pageSize&&(n.pageSize=e.pageSize),e.parentAddress&&(n.parentAddress=e.parentAddress));const r=await this.httpClient.get(ud.GET_OPEN_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ud.GET_OPEN_ORDERS,{params:n});if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}}return{status:!1,error:"Authentication expired and refresh failed"}}if(200===r.code){return{status:!0,data:Array.isArray(r.data)?r.data:r.data?.data||[]}}return{status:!1,error:r.message||"Failed to get open orders"}}catch(e){return{status:!1,error:Eg(e)}}}async getOrderBook(e){try{if(!e)return{status:!1,error:"Symbol is required"};await this.authenticate().catch(()=>{});const t={symbol:e},n=await this.httpClient.get(ud.GET_ORDER_BOOK,{params:t});if(200===n.code&&n.data){let t=n.data;if(t.data&&(t=t.data),!t||!Array.isArray(t.bids)||!Array.isArray(t.asks))return{status:!1,error:"Invalid order book data structure"};const r=this.processOrderBookEntries(t.bids,"bids"),s=this.processOrderBookEntries(t.asks,"asks");return{status:!0,data:{symbol:e,bids:r,asks:s,timestamp:Date.now()}}}return{status:!1,error:n.message||"Failed to get order book"}}catch(e){return{status:!1,error:Eg(e)}}}processOrderBookEntries(e,t){return Array.isArray(e)?e.filter(e=>{if(Array.isArray(e)&&e.length>=2){const[t,n]=e;return t&&n&&!isNaN(parseFloat(String(t)))&&!isNaN(parseFloat(String(n)))&&parseFloat(String(n))>0}return!!(e&&e.price&&e.quantity)&&(!isNaN(parseFloat(String(e.price)))&&!isNaN(parseFloat(String(e.quantity)))&&parseFloat(String(e.quantity))>0)}).map(e=>{let t,n;return Array.isArray(e)&&e.length>=2?[t,n]=e:(t=e.price,n=e.quantity),{price:String(t),quantity:String(n)}}).sort((e,n)=>{const r=parseFloat(e.price),s=parseFloat(n.price);return"bids"===t?s-r:r-s}):[]}formatWeiToNormal(e,t=18){try{const n=new r(e);return n.isNaN()||n.isZero()?"0":n.dividedBy(new r(10).pow(t)).toString()}catch(e){return"0"}}async getTicker(e){try{if(!e)return{status:!1,error:"Symbol is required"};await this.authenticate().catch(()=>{});const t={symbol:e},n=await this.httpClient.get(ud.GET_TICKER,{params:t});if(200===n.code&&n.data){let e=n.data;if(e.data&&(e=e.data),!e||!e.symbol)return{status:!1,error:"Invalid ticker data structure"};return{status:!0,data:this.processTickerData(e)}}return{status:!1,error:n.message||"Failed to get ticker"}}catch(e){return{status:!1,error:Eg(e)}}}transformPositionTpSlOrder(e){const t=e=>null!=e&&""!==e?this.formatWeiToNormal(e):void 0,n=e.planOrderType;return{...e,id:e.id??e.planId??e.planBatchId,planBatchId:e.planBatchId??e.id,planOrderType:n,orderType:e.orderType,symbol:e.symbol,side:e.side,status:e.status,hash:e.hash,quantity:t(e.quantity)??"0",price:t(e.price),triggerPrice:t(e.triggerPrice),tpTriggerPrice:t(e.tpTriggerPrice),tpOrderPrice:t(e.tpOrderPrice),slTriggerPrice:t(e.slTriggerPrice),slOrderPrice:t(e.slOrderPrice),tpPlanId:"takeProfit"===n?e.tpPlanId??e.id??null:e.tpPlanId??null,slPlanId:"stopLoss"===n?e.slPlanId??e.id??null:e.slPlanId??null,tpslType:e.tpslType,createdAt:e.createdAt,updatedAt:e.updatedAt}}hasTpSlOrderConfig(e,t){if(!e)return!1;if(!this.isPositiveNumber(e.triggerPrice))return!1;const n=e.quantity??t;return this.isPositiveNumber(n)}isPositiveNumber(e){if(null==e||""===e)return!1;try{return new r(e).gt(0)}catch{return!1}}processTickerData(e){let t;if(e.bestAskPrice&&e.bestBidPrice){const n=new r(e.bestAskPrice),s=new r(e.bestBidPrice);t=n.plus(s).dividedBy(2).toString()}else t=e.bestAskPrice?String(e.bestAskPrice):e.bestBidPrice?String(e.bestBidPrice):"0";const n={symbol:e.symbol,lastPrice:String(e.lastPrice||"0"),high24h:String(e.high24h||"0"),low24h:String(e.low24h||"0"),amount24h:String(e.amount24h||"0"),volume24h:String(e.volume24h||"0"),midPrice:t,timestamp:e.timestamp||Date.now()};return e.markPrice&&(n.markPrice=String(e.markPrice)),e.bestAskPrice&&(n.bestAskPrice=String(e.bestAskPrice)),e.bestBidPrice&&(n.bestBidPrice=String(e.bestBidPrice)),e.bestAskAmount&&(n.bestAskAmount=String(e.bestAskAmount)),e.bestBidAmount&&(n.bestBidAmount=String(e.bestBidAmount)),e.open24h&&(n.open24h=String(e.open24h)),e.change24h&&(n.change24h=String(e.change24h)),e.rate24h&&(n.rate24h=String(e.rate24h)),e.openPrice&&(n.openPrice=String(e.openPrice)),e.oraclePrice&&(n.oraclePrice=String(e.oraclePrice)),e.fundingRate&&(n.fundingRate=String(e.fundingRate)),e.openInterest&&(n.openInterest=String(e.openInterest)),n}async getHistoryOrders(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.symbol&&(n.symbol=e.symbol),e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress);let r=await this.httpClient.get(ud.HISTORY_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(ud.HISTORY_ORDERS,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get history orders"}}catch(e){return{status:!1,error:Eg(e)}}}async getFundingSettlements(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.symbol&&(n.symbol=e.symbol),e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress);let r=await this.httpClient.get(ud.FUNDING_SETTLEMENTS,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(ud.FUNDING_SETTLEMENTS,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get funding settlements"}}catch(e){return{status:!1,error:Eg(e)}}}async getBalanceChanges(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress);let r=await this.httpClient.get(ud.BALANCE_CHANGES,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(ud.BALANCE_CHANGES,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get balance changes"}}catch(e){return{status:!1,error:Eg(e)}}}async getOraclePrice(e){try{if(!e)return{status:!1,error:"Symbol is required"};await this.authenticate().catch(()=>{});const t=await this.httpClient.get(ud.ORACLE,{params:{symbol:e}});return 200===t.code&&void 0!==t.data?{status:!0,data:String(t.data)}:{status:!1,error:t.message||"Failed to get oracle price"}}catch(e){return{status:!1,error:Eg(e)}}}async addMargin(e){const t=await this.buildMarginTransaction(e,"add");if(t)return this.exchangeOnChain.executeTxBlock(t,this.keypair);const n=this.buildMarginCallArgs(e,"add");return this.exchangeOnChain.addMargin(n)}async removeMargin(e){const t=await this.buildMarginTransaction(e,"remove");if(t)return this.exchangeOnChain.executeTxBlock(t,this.keypair);const n=this.buildMarginCallArgs(e,"remove");return this.exchangeOnChain.removeMargin(n)}buildMarginCallArgs(e,t){const{amount:n,accountAddress:s,symbol:i,market:a,perpId:o,subAccountsMapId:c,gasBudget:u,txHash:d}=e;if(!this.isPositiveNumber(n))throw new Error(`Amount must be greater than zero to ${t} margin`);const l=new r(n).toNumber();if(!Number.isFinite(l))throw new Error("Amount is too large to represent as a number");const h=a||i,f=h?h.toUpperCase():void 0,p=o||(f?this.resolvePerpIdFromDeployment(f):void 0);if(!f&&!p)throw new Error("Either market/symbol or perpId must be provided for margin adjustments");return{amount:l,account:s||this.walletAddress,market:f,perpID:p,subAccountsMapID:c,gasBudget:u,txHash:d}}getDeploymentPackageId(){const e=this.deploymentConfig?.packages;if(!e||!e.length)throw new Error("Deployment config missing packages array");return e[e.length-1]}getDeploymentProtocolConfigId(){const e=this.deploymentConfig?.objects?.ProtocolConfig?.id;if(!e)throw new Error("Deployment config missing ProtocolConfig id");return e}async buildMarginTransaction(e,t){if(!this.transactionBuilder)return;const n=this.buildMarginCallArgs(e,t),r=(n.market?await this.buildUpdatePriceTransaction(n.market):void 0)||new Ra;return"add"===t?this.transactionBuilder.exchange_addMarginTx(n,r,e.gasBudget):this.transactionBuilder.exchange_removeMarginTx(n,r,e.gasBudget)}async buildUpdatePriceTransaction(e){if(e)try{return"mainnet"===this.options.network?await this.buildMainnetPriceUpdateTransaction(e):await this.buildTestnetPriceUpdateTransaction(e)}catch(e){return}}async buildMainnetPriceUpdateTransaction(e){const t=this.getPriceInfoObjectId(e),n=await this.resolvePriceFeedId(e);if(!t||!n)return;if(this.ensurePythClients(),!this.priceServiceConnection||!this.pythClient)return;const r=new Ra,s=[n],i=await this.priceServiceConnection.getPriceFeedsUpdateData(s),[a,o]=await this.suiClient.multiGetObjects({ids:[t,"0x6"],options:{showContent:!0,showBcs:!0,showType:!0}}),c=this.extractOracleArrivalTime(a);return this.extractClockTimeSeconds(o)-c>5&&await this.pythClient.updatePriceFeeds(r,i,s),r}async buildTestnetPriceUpdateTransaction(e){try{const t=await this.exchangeOnChain.getOraclePrice(e);if(null==t)return;return this.transactionBuilder.price_info_setOraclePriceTx({price:Number(t),market:e})}catch(e){return}}getPriceInfoObjectId(e){const t=e?.toUpperCase(),n=this.getDeploymentMarket(t);return n?.Objects?.PriceInfoObject?.id}getDeploymentMarket(e){if(!e)return;const t=this.deploymentConfig?.markets,n=e.toUpperCase();return t?.[n]||t?.[e]}async resolvePriceFeedId(e){const t=e?.toUpperCase(),n=this.getDeploymentMarket(t),r=n?.Config?.priceInfoFeedId||n?.Config?.priceIdentifierId;if(r)return r;const s=(await this.getCachedTradingPairs()).find(n=>n.symbol?.toUpperCase()===t||n.symbol===e);return s?s.priceIdentifierId||s.priceInfoFeedId:void 0}async getCachedTradingPairs(){const e=this.tradingPairsCacheTimestamp?Date.now()-this.tradingPairsCacheTimestamp:1/0;if(this.tradingPairsCache&&e<6e4)return this.tradingPairsCache;const t=await this.getTradingPairs();return t.status&&t.data?(this.tradingPairsCache=t.data,this.tradingPairsCacheTimestamp=Date.now(),t.data):this.tradingPairsCache||[]}ensurePythClients(){const e=hd[this.options.network];e&&(this.priceServiceConnection||(this.priceServiceConnection=new id(e.priceServiceUrl)),this.pythClient||(this.pythClient=new od(this.suiClient,e.pythStateId,e.wormholeStateId)))}extractOracleArrivalTime(e){const t=e?.data?.content&&"fields"in e.data.content&&e.data.content.fields?.price_info?.fields?.arrival_time;if("number"==typeof t)return t;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e:0}return 0}extractClockTimeSeconds(e){const t=e?.data?.content&&"fields"in e.data.content&&e.data.content.fields?.timestamp_ms;if("number"==typeof t)return t/1e3;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e/1e3:0}return 0}resolvePerpIdFromDeployment(e){try{return this.exchangeOnChain.getPerpetualID(e)||void 0}catch(e){return}}async setSubAccount(e){return await this.exchangeOnChain.setSubAccount({account:e,status:!0},this.keypair)}async depositToBank(e){return await this.exchangeOnChain.depositToBank({amount:wg(e,ld.USDC),accountAddress:this.address},this.keypair)}async withdrawFromBank(e){return await this.exchangeOnChain.withdrawFromBank({amount:wg(e,ld.USDC),accountAddress:this.address},this.keypair)}async getAllBalances(){try{return{status:!0,data:await this.suiClient.getAllBalances({owner:this.walletAddress})}}catch(e){return{status:!1,error:Eg(e)}}}async getCoinMetadata(e){try{const t=await this.suiClient.getCoinMetadata({coinType:e});return t?{status:!0,data:{decimals:t.decimals,symbol:t.symbol,name:t.name}}:{status:!1,error:"Coin metadata not found"}}catch(e){return{status:!1,error:Eg(e)}}}}function Og(e,t){const n=h(t);return new Sg(e,n)}export{ud as API_ENDPOINTS,ld as DECIMALS,l as DEFAULT_API_URLS,cd as DEFAULT_SLIPPAGE,Sg as DipCoinPerpSDK,fd as HttpClient,dd as ONBOARDING_MESSAGE,pd as OrderSide,gd as OrderType,hd as PYTH_CONFIG,gg as SignerTypes,bg as buildSignature,Sg as default,Eg as formatError,wg as formatNormalToWei,vg as formatNormalToWeiBN,mg as fromExportedKeypair,Og as initDipCoinPerpSDK,h as initSDKOptions,kg as readFile,yg as signMessage};
|
|
3
|
+
function z(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Z(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function W(e){if("function"!=typeof e)throw new Error("function expected");return!0}function G(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function H(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function J(e){if(!Array.isArray(e))throw new Error("array expected")}function Y(e,t){if(!Z(!0,t))throw new Error(`${e}: array of strings expected`)}function X(e,t){if(!Z(!1,t))throw new Error(`${e}: array of numbers expected`)}function Q(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function ee(e){const t="string"==typeof e?e.split(""):e,n=t.length;Y("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(J(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(J(t),t.map(t=>{G("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function te(e=""){return G("join",e),{encode:t=>(Y("join.decode",t),t.join(e)),decode:t=>(G("join.decode",t),t.split(e))}}function ne(e,t="="){return H(e),G("padding",t),{encode(n){for(Y("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){Y("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--){if((r-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return n.slice(0,r)}}}function re(e){return W(e),{encode:e=>e,decode:t=>e(t)}}function se(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(J(e),!e.length)return[];let r=0;const s=[],i=Array.from(e,e=>{if(H(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e}),a=i.length;for(;;){let e=0,o=!0;for(let s=r;s<a;s++){const a=i[s],c=t*e,u=c+a;if(!Number.isSafeInteger(u)||c/t!==e||u-a!==c)throw new Error("convertRadix: carry overflow");const d=u/n;e=u%n;const l=Math.floor(d);if(i[s]=l,!Number.isSafeInteger(l)||l*n+e!==u)throw new Error("convertRadix: carry overflow");o&&(l?o=!1:r=s)}if(s.push(e),o)break}for(let t=0;t<e.length-1&&0===e[t];t++)s.push(0);return s.reverse()}N=new WeakMap,$=new WeakMap,R=new WeakMap,M=new WeakSet,D=function(){if(!F(this,R)){const e=F(this,$).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");K(this,R,new P(F(this,$).websocket?.url??F(this,$).url,{WebSocketConstructor:e,...F(this,$).websocket}))}return F(this,R)};const ie=(e,t)=>0===t?e:ie(t,e%t),ae=(e,t)=>e+(t-ie(e,t)),oe=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function ce(e,t,n,r){if(J(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ae(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ae(t,n)}`);let s=0,i=0;const a=oe[t],o=oe[n]-1,c=[];for(const r of e){if(H(r),r>=a)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(s=s<<t|r,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=n;i-=n)c.push((s>>i-n&o)>>>0);const e=oe[i];if(void 0===e)throw new Error("invalid carry");s&=e-1}if(s=s<<n-i&o,!r&&i>=t)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&c.push(s>>>0),c}function ue(e,t=!1){if(H(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ae(8,e)>32||ae(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!z(n))throw new Error("radix2.encode input should be Uint8Array");return ce(Array.from(n),8,e,!t)},decode:n=>(X("radix2.decode",n),Uint8Array.from(ce(n,e,8,t)))}}function de(e){return W(e),function(...t){try{return e.apply(null,t)}catch(e){}}}Q(ue(4),ee("0123456789ABCDEF"),te("")),Q(ue(5),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ne(5),te("")),Q(ue(5),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),te("")),Q(ue(5),ee("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ne(5),te("")),Q(ue(5),ee("0123456789ABCDEFGHIJKLMNOPQRSTUV"),te("")),Q(ue(5),ee("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),te(""),re(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const le=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();le||Q(ue(6),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ne(6),te("")),Q(ue(6),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),te("")),le||Q(ue(6),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ne(6),te("")),Q(ue(6),ee("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),te(""));const he=e=>{return Q((H(t=58),{encode:e=>{if(!z(e))throw new Error("radix.encode input should be Uint8Array");return se(Array.from(e),256,t)},decode:e=>(X("radix.decode",e),Uint8Array.from(se(e,t,256)))}),ee(e),te(""));var t},pe=he("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");he("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),he("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const fe=Q(ee("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),te("")),ge=[996825010,642813549,513874426,1027748829,705979059];function me(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<ge.length;e++)1==(t>>e&1)&&(n^=ge[e]);return n}function ye(e,t,n=1){const r=e.length;let s=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);s=me(s)^n>>5}s=me(s);for(let t=0;t<r;t++)s=me(s)^31&e.charCodeAt(t);for(let e of t)s=me(s)^e;for(let e=0;e<6;e++)s=me(s);return s^=n,fe.encode(ce([s%oe[30]],30,5,!1))}function be(e){const t="bech32"===e?1:734539939,n=ue(5),r=n.decode,s=n.encode,i=de(r);function a(e,n,r=90){G("bech32.encode prefix",e),z(n)&&(n=Array.from(n)),X("bech32.encode",n);const s=e.length;if(0===s)throw new TypeError(`Invalid prefix length ${s}`);const i=s+7+n.length;if(!1!==r&&i>r)throw new TypeError(`Length ${i} exceeds limit ${r}`);const a=e.toLowerCase(),o=ye(a,n,t);return`${a}1${fe.encode(n)}${o}`}function o(e,n=90){G("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const s=e.toLowerCase();if(e!==s&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=s.lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const a=s.slice(0,i),o=s.slice(i+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const c=fe.decode(o).slice(0,-6),u=ye(a,c,t);if(!o.endsWith(u))throw new Error(`Invalid checksum in ${e}: expected "${u}"`);return{prefix:a,words:c}}return{encode:a,decode:o,encodeFromBytes:function(e,t){return a(e,s(t))},decodeToBytes:function(e){const{prefix:t,words:n}=o(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:de(o),fromWords:r,fromWordsUnsafe:i,toWords:s}}const we=be("bech32");be("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||Q(ue(4),ee("0123456789abcdef"),te(""),re(e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const ve=e=>pe.encode(e),ke=e=>pe.decode(e);function Ee(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}const Se=8192;function xe(e){if(e.length<Se)return btoa(String.fromCharCode(...e));let t="";for(var n=0;n<e.length;n+=Se){const r=e.slice(n,n+Se);t+=String.fromCharCode(...r)}return btoa(t)}function Oe(e){const t=e.startsWith("0x")?e.slice(2):e,n=t.length%2==0?t:`0${t}`,r=n.match(/[0-9a-fA-F]{2}/g)?.map(e=>parseInt(e,16))??[];if(r.length!==n.length/2)throw new Error(`Invalid hex string ${e}`);return Uint8Array.from(r)}function Ie(e){return e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Te(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}class _e{constructor(e,t){if("function"!=typeof e)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=function(e){const t=!e||!1!==e.batch;if(!t)return 1;const n=e&&e.maxBatchSize;if(void 0===n)return 1/0;if("number"!=typeof n||n<1)throw new TypeError(`maxBatchSize must be a positive number: ${n}`);return n}(t),this._batchScheduleFn=function(e){const t=e&&e.batchScheduleFn;if(void 0===t)return Ae;if("function"!=typeof t)throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}(t),this._cacheKeyFn=function(e){const t=e&&e.cacheKeyFn;if(void 0===t)return e=>e;if("function"!=typeof t)throw new TypeError(`cacheKeyFn must be a function: ${t}`);return t}(t),this._cacheMap=function(e){const t=!e||!1!==e.cache;if(!t)return null;const n=e&&e.cacheMap;if(void 0===n)return new Map;if(null!==n){const e=["get","set","delete","clear"].filter(e=>n&&"function"!=typeof n[e]);if(0!==e.length)throw new TypeError("Custom cacheMap missing methods: "+e.join(", "))}return n}(t),this._batch=null,this.name=function(e){if(e&&e.name)return e.name;return null}(t)}load(e){if(null==e)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const t=function(e){const t=e._batch;if(null!==t&&!t.hasDispatched&&t.keys.length<e._maxBatchSize)return t;const n={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=n,e._batchScheduleFn(()=>{!function(e,t){if(t.hasDispatched=!0,0===t.keys.length)return void Pe(t);let n;try{n=e._batchLoadFn(t.keys)}catch(n){return Ce(e,t,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!n||"function"!=typeof n.then)return Ce(e,t,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(n)}.`));Promise.resolve(n).then(e=>{if(!Be(e))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(e)}.`);if(e.length!==t.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.\n\nKeys:\n${String(t.keys)}\n\nValues:\n${String(e)}`);Pe(t);for(let n=0;n<t.callbacks.length;n++){const r=e[n];r instanceof Error?t.callbacks[n].reject(r):t.callbacks[n].resolve(r)}}).catch(n=>{Ce(e,t,n)})}(e,n)}),n}(this),n=this._cacheMap;let r;if(n){r=this._cacheKeyFn(e);const s=n.get(r);if(s){const e=t.cacheHits||(t.cacheHits=[]);return new Promise(t=>{e.push(()=>{t(s)})})}}t.keys.push(e);const s=new Promise((e,n)=>{t.callbacks.push({resolve:e,reject:n})});return n&&n.set(r,s),s}loadMany(e){if(!Be(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const t=[];for(let n=0;n<e.length;n++)t.push(this.load(e[n]).catch(e=>e));return Promise.all(t)}clear(e){const t=this._cacheMap;if(t){const n=this._cacheKeyFn(e);t.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,t){const n=this._cacheMap;if(n){const r=this._cacheKeyFn(e);if(void 0===n.get(r)){let e;t instanceof Error?(e=Promise.reject(t),e.catch(()=>{})):e=Promise.resolve(t),n.set(r,e)}}return this}}const Ae="object"==typeof process&&"function"==typeof process.nextTick?function(e){je||(je=Promise.resolve()),je.then(()=>{process.nextTick(e)})}:"function"==typeof setImmediate?function(e){setImmediate(e)}:function(e){setTimeout(e)};let je;function Ce(e,t,n){Pe(t);for(let r=0;r<t.keys.length;r++)e.clear(t.keys[r]),t.callbacks[r].reject(n)}function Pe(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Be(e){return"object"==typeof e&&null!==e&&"length"in e&&"number"==typeof e.length&&(0===e.length||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}function Ne(e){let t=BigInt(e);const n=[];let r=0;if(0n===t)return[0];for(;t>0;)n[r]=Number(0x7fn&t),t>>=7n,t>0n&&(n[r]|=128),r+=1;return n}class $e{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),t=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+t).toString(10)}read128(){const e=BigInt(this.read64()),t=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+t).toString(10)}read256(){const e=BigInt(this.read128()),t=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+t).toString(10)}readBytes(e){const t=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,t,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,t=new Uint8Array(this.dataView.buffer,e),{value:n,length:r}=function(e){let t=0n,n=0n,r=0;for(;;){if(r>=e.length)throw new Error("ULEB decode error: buffer overflow");const s=e[r];if(r+=1,t+=BigInt(127&s)<<n,!(128&s))break;n+=7n}if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(t),length:r}}(t);return this.shift(r),n}readVec(e){const t=this.readULEB(),n=[];for(let r=0;r<t;r++)n.push(e(this,r,t));return n}}function Re(e,t=["<",">"]){const[n,r]=t,s=[];let i="",a=0;for(let t=0;t<e.length;t++){const o=e[t];o===n&&a++,o===r&&a--,0!==a||","!==o?i+=o:(s.push(i.trim()),i="")}return s.push(i.trim()),s}class Me{constructor({initialSize:e=1024,maxSize:t=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=t,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const t=this.bytePosition+e;if(t>this.size){const e=Math.min(this.maxSize,Math.max(this.size+t,this.size+this.allocateSize));if(t>e)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${t}`);this.size=e;const n=new ArrayBuffer(this.size);new Uint8Array(n).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(n)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}writeBytes(e){this.ensureSizeOrGrow(e.length);for(let t=0;t<e.length;t++)this.dataView.setUint8(this.bytePosition+t,e[t]);return this.shift(e.length)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return De(BigInt(e),8).forEach(e=>this.write8(e)),this}write128(e){return De(BigInt(e),16).forEach(e=>this.write8(e)),this}write256(e){return De(BigInt(e),32).forEach(e=>this.write8(e)),this}writeULEB(e){return Ne(e).forEach(e=>this.write8(e)),this}writeVec(e,t){return this.writeULEB(e.length),Array.from(e).forEach((n,r)=>t(this,n,r,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return function(e,t){switch(t){case"base58":return ve(e);case"base64":return xe(e);case"hex":return Ie(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}(this.toBytes(),e)}}function De(e,t){const n=new Uint8Array(t);let r=0;for(;e>0;)n[r]=Number(e%BigInt(256)),e/=BigInt(256),r+=1;return n}var Ue,Ve,Fe,Le,Ke=e=>{throw TypeError(e)},qe=(e,t,n)=>t.has(e)||Ke("Cannot "+n),ze=(e,t,n)=>(qe(e,t,"read from private field"),n?n.call(e):t.get(e)),Ze=(e,t,n)=>t.has(e)?Ke("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),We=(e,t,n,r)=>(qe(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);Ue=new WeakMap,Ve=new WeakMap;let Ge=class e{constructor(e){Ze(this,Ue),Ze(this,Ve),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),We(this,Ue,e.write),We(this,Ve,e.serialize??((e,t)=>{const n=new Me({initialSize:this.serializedSize(e)??void 0,...t});return ze(this,Ue).call(this,e,n),n.toBytes()})),this.validate=e.validate??(()=>{})}write(e,t){this.validate(e),ze(this,Ue).call(this,e,t)}serialize(e,t){return this.validate(e),new Ye(this,ze(this,Ve).call(this,e,t))}parse(e){const t=new $e(e);return this.read(t)}fromHex(e){return this.parse(Oe(e))}fromBase58(e){return this.parse(ke(e))}fromBase64(e){return this.parse(Ee(e))}transform({name:t,input:n,output:r,validate:s}){return new e({name:t??this.name,read:e=>r?r(this.read(e)):this.read(e),write:(e,t)=>ze(this,Ue).call(this,n?n(e):e,t),serializedSize:e=>this.serializedSize(n?n(e):e),serialize:(e,t)=>ze(this,Ve).call(this,n?n(e):e,t),validate:e=>{s?.(e),this.validate(n?n(e):e)}})}};const He=Symbol.for("@mysten/serialized-bcs");function Je(e){return!!e&&"object"==typeof e&&!0===e[He]}class Ye{constructor(e,t){Ze(this,Fe),Ze(this,Le),We(this,Fe,e),We(this,Le,t)}get[He](){return!0}toBytes(){return ze(this,Le)}toHex(){return Ie(ze(this,Le))}toBase64(){return xe(ze(this,Le))}toBase58(){return ve(ze(this,Le))}parse(){return ze(this,Fe).parse(ze(this,Le))}}function Xe({size:e,...t}){return new Ge({...t,serializedSize:()=>e})}function Qe({readMethod:e,writeMethod:t,...n}){return Xe({...n,read:t=>t[e](),write:(e,n)=>n[t](e),validate:e=>{if(e<0||e>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${e}. Expected value in range 0-${n.maxValue}`);n.validate?.(e)}})}function et({readMethod:e,writeMethod:t,...n}){return Xe({...n,read:t=>t[e](),write:(e,n)=>n[t](BigInt(e)),validate:e=>{const t=BigInt(e);if(t<0||t>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${t}. Expected value in range 0-${n.maxValue}`);n.validate?.(t)}})}Fe=new WeakMap,Le=new WeakMap;class tt extends Ge{constructor({name:e,fields:t,...n}){const r=Object.entries(t);super({name:e,serializedSize:e=>{let t=0;for(const[n,s]of r){const r=s.serializedSize(e[n]);if(null==r)return null;t+=r}return t},read:e=>{const t={};for(const[n,s]of r)t[n]=s.read(e);return t},write:(e,t)=>{for(const[n,s]of r)s.write(e[n],t)},...n,validate:e=>{if(n?.validate?.(e),"object"!=typeof e||null==e)throw new TypeError("Expected object, found "+typeof e)}})}}class nt extends Ge{constructor({fields:e,...t}){const n=Object.entries(e);super({read:e=>{const r=e.readULEB(),s=n[r];if(!s)throw new TypeError(`Unknown value ${r} for enum ${t.name}`);const[i,a]=s;return{[i]:a?.read(e)??!0,$kind:i}},write:(t,r)=>{const[s,i]=Object.entries(t).filter(([t])=>Object.hasOwn(e,t))[0];for(let e=0;e<n.length;e++){const[t,a]=n[e];if(t===s)return r.writeULEB(e),void a?.write(i,r)}},...t,validate:n=>{if(t?.validate?.(n),"object"!=typeof n||null==n)throw new TypeError("Expected object, found "+typeof n);const r=Object.keys(n).filter(t=>void 0!==n[t]&&Object.hasOwn(e,t));if(1!==r.length)throw new TypeError(`Expected object with one key, but found ${r.length} for type ${t.name}}`);const[s]=r;if(!Object.hasOwn(e,s))throw new TypeError(`Invalid enum variant ${s}`)}})}}class rt extends Ge{constructor({fields:e,name:t,...n}){super({name:t??`(${e.map(e=>e.name).join(", ")})`,serializedSize:t=>{let n=0;for(let r=0;r<e.length;r++){const s=e[r].serializedSize(t[r]);if(null==s)return null;n+=s}return n},read:t=>{const n=[];for(const r of e)n.push(r.read(t));return n},write:(t,n)=>{for(let r=0;r<e.length;r++)e[r].write(t[r],n)},...n,validate:t=>{if(n?.validate?.(t),!Array.isArray(t))throw new TypeError("Expected array, found "+typeof t);if(t.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${t.length}`)}})}}const st={u8:e=>Qe({readMethod:"read8",writeMethod:"write8",size:1,maxValue:255,...e,name:e?.name??"u8"}),u16:e=>Qe({readMethod:"read16",writeMethod:"write16",size:2,maxValue:65535,...e,name:e?.name??"u16"}),u32:e=>Qe({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:e?.name??"u32"}),u64:e=>et({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:e?.name??"u64"}),u128:e=>et({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:e?.name??"u128"}),u256:e=>et({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:e?.name??"u256"}),bool:e=>Xe({size:1,read:e=>1===e.read8(),write:(e,t)=>t.write8(e?1:0),...e,name:e?.name??"bool",validate:t=>{if(e?.validate?.(t),"boolean"!=typeof t)throw new TypeError("Expected boolean, found "+typeof t)}}),uleb128:e=>function({serialize:e,...t}){const n=new Ge({...t,serialize:e,write:(e,t)=>{for(const r of n.serialize(e).toBytes())t.write8(r)}});return n}({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(Ne(e)),...e,name:e?.name??"uleb128"}),bytes:(e,t)=>Xe({size:e,read:t=>t.readBytes(e),write:(e,t)=>{t.writeBytes(new Uint8Array(e))},...t,name:t?.name??`bytes[${e}]`,validate:n=>{if(t?.validate?.(n),!n||"object"!=typeof n||!("length"in n))throw new TypeError("Expected array, found "+typeof n);if(n.length!==e)throw new TypeError(`Expected array of length ${e}, found ${n.length}`)}}),byteVector:e=>new Ge({read:e=>{const t=e.readULEB();return e.readBytes(t)},write:(e,t)=>{const n=new Uint8Array(e);t.writeULEB(n.length),t.writeBytes(n)},...e,name:e?.name??"vector<u8>",serializedSize:e=>{const t="length"in e?e.length:null;return null==t?null:Ne(t).length+t},validate:t=>{if(e?.validate?.(t),!t||"object"!=typeof t||!("length"in t))throw new TypeError("Expected array, found "+typeof t)}}),string:e=>function({toBytes:e,fromBytes:t,...n}){return new Ge({...n,read:e=>{const n=e.readULEB(),r=e.readBytes(n);return t(r)},write:(t,n)=>{const r=e(t);n.writeULEB(r.length);for(let e=0;e<r.length;e++)n.write8(r[e])},serialize:t=>{const n=e(t),r=Ne(n.length),s=new Uint8Array(r.length+n.length);return s.set(r,0),s.set(n,r.length),s},validate:e=>{if("string"!=typeof e)throw new TypeError(`Invalid ${n.name} value: ${e}. Expected string`);n.validate?.(e)}})}({toBytes:e=>(new TextEncoder).encode(e),fromBytes:e=>(new TextDecoder).decode(e),...e,name:e?.name??"string"}),fixedArray:function(e,t,n){return new Ge({read:n=>{const r=new Array(e);for(let s=0;s<e;s++)r[s]=t.read(n);return r},write:(e,n)=>{for(const r of e)t.write(r,n)},...n,name:n?.name??`${t.name}[${e}]`,validate:t=>{if(n?.validate?.(t),!t||"object"!=typeof t||!("length"in t))throw new TypeError("Expected array, found "+typeof t);if(t.length!==e)throw new TypeError(`Expected array of length ${e}, found ${t.length}`)}})},option:function(e){return st.enum(`Option<${e.name}>`,{None:null,Some:e}).transform({input:e=>null==e?{None:!0}:{Some:e},output:e=>"Some"===e.$kind?e.Some:null})},vector:function(e,t){return new Ge({read:t=>{const n=t.readULEB(),r=new Array(n);for(let s=0;s<n;s++)r[s]=e.read(t);return r},write:(t,n)=>{n.writeULEB(t.length);for(const r of t)e.write(r,n)},...t,name:t?.name??`vector<${e.name}>`,validate:e=>{if(t?.validate?.(e),!e||"object"!=typeof e||!("length"in e))throw new TypeError("Expected array, found "+typeof e)}})},tuple:(e,t)=>new rt({fields:e,...t}),struct:(e,t,n)=>new tt({name:e,fields:t,...n}),enum:(e,t,n)=>new nt({name:e,fields:t,...n}),map:function(e,t){return st.vector(st.tuple([e,t])).transform({name:`Map<${e.name}, ${t.name}>`,input:e=>[...e.entries()],output:e=>{const t=new Map;for(const[n,r]of e)t.set(n,r);return t}})},lazy:e=>function(e){let t=null;function n(){return t||(t=e()),t}return new Ge({name:"lazy",read:e=>n().read(e),serializedSize:e=>n().serializedSize(e),write:(e,t)=>n().write(e,t),serialize:(e,t)=>n().serialize(e,t).toBytes()})}(e)};var it,at,ot=e=>{throw TypeError(e)},ct=(e,t,n)=>t.has(e)||ot("Cannot "+n),ut=(e,t,n)=>(ct(e,t,"read from private field"),n?n.call(e):t.get(e)),dt=(e,t,n)=>t.has(e)?ot("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),lt=(e,t,n,r)=>(ct(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);it=new WeakMap,at=new WeakMap;let ht=class e{constructor({prefix:e,cache:t}={}){dt(this,it),dt(this,at),lt(this,it,e??[]),lt(this,at,t??new Map)}read(e,t){const n=[ut(this,it),...e].join(":");if(ut(this,at).has(n))return ut(this,at).get(n);const r=t();return ut(this,at).set(n,r),"object"==typeof r&&null!==r&&"then"in r?Promise.resolve(r).then(e=>(ut(this,at).set(n,e),e)).catch(e=>{throw ut(this,at).delete(n),e}):r}readSync(e,t){const n=[ut(this,it),...e].join(":");if(ut(this,at).has(n))return ut(this,at).get(n);const r=t();return ut(this,at).set(n,r),r}clear(e){const t=[...ut(this,it),...e??[]].join(":");if(t)for(const e of ut(this,at).keys())e.startsWith(t)&&ut(this,at).delete(e);else ut(this,at).clear()}scope(t){return new e({prefix:[...ut(this,it),...Array.isArray(t)?t:[t]],cache:ut(this,at)})}};class pt{constructor({network:e,base:t,cache:n=t?.cache??new ht}){this.network=e,this.base=t??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(e=>[e.name,{value:e.register(this)}])))}}function ft(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function gt(e,t,n,r,s){const i=s&&"input"in s?s.input:n.value,a=s?.expected??e.expects??null,o=s?.received??ft(i),c={kind:e.kind,type:e.type,input:i,expected:a,received:o,message:`Invalid ${t}: ${a?`Expected ${a} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},u="schema"===e.kind,d=s?.message??e.message??(e.reference,void c.lang)??(u?void c.lang:null)??r.message??void c.lang;d&&(c.message="function"==typeof d?d(c):d),u&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function mt(e,t){return Object.hasOwn(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}var yt=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function bt(e,t){return{kind:"validation",type:"check",reference:bt,async:!1,expects:null,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement(e.value)&>(this,"input",e,t),e}}}function wt(e){return{kind:"validation",type:"integer",reference:wt,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(e,t){return e.typed&&!this.requirement(e.value)&>(this,"integer",e,t),e}}}function vt(e){return{kind:"transformation",type:"transform",reference:vt,async:!1,operation:e,_run(e){return e.value=this.operation(e.value),e}}}function kt(e,t,n){return"function"==typeof e.default?e.default(t,n):e.default}function Et(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function St(e,t){return{kind:"schema",type:"array",reference:St,expects:"Array",async:!1,item:e,message:t,_run(e,t){const n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){const s=n[r],i=this.item._run({typed:!1,value:s},t);if(i.issues){const a={type:"array",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.push(i.value)}}else gt(this,"type",e,t);return e}}}function xt(e){return{kind:"schema",type:"bigint",reference:xt,expects:"bigint",async:!1,message:e,_run(e,t){return"bigint"==typeof e.value?e.typed=!0:gt(this,"type",e,t),e}}}function Ot(e){return{kind:"schema",type:"boolean",reference:Ot,expects:"boolean",async:!1,message:e,_run(e,t){return"boolean"==typeof e.value?e.typed=!0:gt(this,"type",e,t),e}}}function It(e){return{kind:"schema",type:"lazy",reference:It,expects:"unknown",async:!1,getter:e,_run(e,t){return this.getter(e.value)._run(e,t)}}}function Tt(e,t){return{kind:"schema",type:"literal",reference:Tt,expects:ft(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:gt(this,"type",e,t),e}}}function _t(e,...t){const n={kind:"schema",type:"nullable",reference:_t,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(e,t){return null===e.value&&("default"in this&&(e.value=kt(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function At(e,...t){const n={kind:"schema",type:"nullish",reference:At,expects:`${e.expects} | null | undefined`,async:!1,wrapped:e,_run(e,t){return null!==e.value&&void 0!==e.value||("default"in this&&(e.value=kt(this,e,t)),null!==e.value&&void 0!==e.value)?this.wrapped._run(e,t):(e.typed=!0,e)}};return 0 in t&&(n.default=t[0]),n}function jt(e){return{kind:"schema",type:"number",reference:jt,expects:"number",async:!1,message:e,_run(e,t){return"number"!=typeof e.value||isNaN(e.value)?gt(this,"type",e,t):e.typed=!0,e}}}function Ct(e,t){return{kind:"schema",type:"object",reference:Ct,expects:"Object",async:!1,entries:e,message:t,_run(e,t){const n=e.value;if(n&&"object"==typeof n){e.typed=!0,e.value={};for(const r in this.entries){const s=n[r],i=this.entries[r]._run({typed:!1,value:s},t);if(i.issues){const a={type:"object",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),(void 0!==i.value||r in n)&&(e.value[r]=i.value)}}else gt(this,"type",e,t);return e}}}function Pt(e,...t){const n={kind:"schema",type:"optional",reference:Pt,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(e,t){return void 0===e.value&&("default"in this&&(e.value=kt(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function Bt(e,t,n){return{kind:"schema",type:"record",reference:Bt,expects:"Object",async:!1,key:e,value:t,message:n,_run(e,t){const n=e.value;if(n&&"object"==typeof n){e.typed=!0,e.value={};for(const r in n)if(mt(n,r)){const s=n[r],i=this.key._run({typed:!1,value:r},t);if(i.issues){const a={type:"object",origin:"key",input:n,key:r,value:s};for(const t of i.issues)t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}const a=this.value._run({typed:!1,value:s},t);if(a.issues){const i={type:"object",origin:"value",input:n,key:r,value:s};for(const t of a.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=a.issues),t.abortEarly){e.typed=!1;break}}i.typed&&a.typed||(e.typed=!1),i.typed&&(e.value[i.value]=a.value)}}else gt(this,"type",e,t);return e}}}function Nt(e){return{kind:"schema",type:"string",reference:Nt,expects:"string",async:!1,message:e,_run(e,t){return"string"==typeof e.value?e.typed=!0:gt(this,"type",e,t),e}}}function $t(e,t){return{kind:"schema",type:"tuple",reference:$t,expects:"Array",async:!1,items:e,message:t,_run(e,t){const n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<this.items.length;r++){const s=n[r],i=this.items[r]._run({typed:!1,value:s},t);if(i.issues){const a={type:"array",origin:"value",input:n,key:r,value:s};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value.push(i.value)}}else gt(this,"type",e,t);return e}}}function Rt(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function Mt(e,t){return{kind:"schema",type:"union",reference:Mt,expects:[...new Set(e.map(e=>e.expects))].join(" | ")||"never",async:!1,options:e,message:t,_run(e,t){let n,r,s;for(const i of this.options){const a=i._run({typed:!1,value:e.value},t);if(a.typed){if(!a.issues){n=a;break}r?r.push(a):r=[a]}else s?s.push(a):s=[a]}if(n)return n;if(r){if(1===r.length)return r[0];gt(this,"type",e,t,{issues:Rt(r)}),e.typed=!0}else{if(1===s?.length)return s[0];gt(this,"type",e,t,{issues:Rt(s)})}return e}}}function Dt(){return{kind:"schema",type:"unknown",reference:Dt,expects:"unknown",async:!1,_run:e=>(e.typed=!0,e)}}function Ut(e,t,n){const r=e._run({typed:!1,value:t},function(e){return{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}}(n));if(r.issues)throw new yt(r.issues);return r.value}function Vt(...e){return{...e[0],pipe:e,_run(t,n){for(let r=0;r<e.length;r++){if(t.issues&&("schema"===e[r].kind||"transformation"===e[r].kind)){t.typed=!1;break}t.issues&&(n.abortEarly||n.abortPipeEarly)||(t=e[r]._run(t,n))}return t}}}const Ft=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Lt=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i;const Kt=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,qt=/^\d+$/,zt=e=>{const t=e.split("/");if(t.length<2||t.length>3)return!1;const[n,r,s]=t;return!(void 0!==s&&!qt.test(s))&&(!!function(e){return!(e.length>235)&&(e.includes("@")?Ft.test(e):Lt.test(e))}(n)&&(Kt.test(r)&&r.length<64))},Zt=e=>{const t=e.split(/::|<|>|,/);for(const e of t)if(e.includes("/")&&!zt(e))return!1;return!0};function Wt(e){try{return 32===ke(e).length}catch{return!1}}const Gt=32;function Ht(e){return function(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2==0}(e)&&function(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}(e)===Gt}function Jt(e){return Ht(e)}function Yt(e){const[t,n]=e.split("::"),r=zt(t),s=e.slice(t.length+n.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?Re(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(e=>function(e){return e.includes("::")?Yt(e):e}(e.trim())):[];return{address:r?t:Qt(t),module:n,name:i,typeParams:a}}function Xt(e){const{address:t,module:n,name:r,typeParams:s}="string"==typeof e?Yt(e):e;return`${t}::${n}::${r}${s?.length>0?`<${s.map(e=>"string"==typeof e?e:Xt(e)).join(",")}>`:""}`}function Qt(e,t=!1){let n=e.toLowerCase();return!t&&n.startsWith("0x")&&(n=n.slice(2)),`0x${n.padStart(64,"0")}`}function en(e,t=!1){return Qt(e,t)}function tn(e){return Vt(Mt(Object.entries(e).map(([e,t])=>Ct({[e]:t}))),vt(e=>({...e,$kind:Object.keys(e)[0]})))}const nn=Vt(Nt(),vt(e=>Qt(e)),bt(Ht)),rn=nn,sn=Nt(),an=Vt(Mt([Nt(),Vt(jt(),wt())]),bt(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),on=Ct({objectId:nn,version:an,digest:Nt()}),cn=Vt(Mt([Ct({GasCoin:Tt(!0)}),Ct({Input:Vt(jt(),wt()),type:Pt(Tt("pure"))}),Ct({Input:Vt(jt(),wt()),type:Pt(Tt("object"))}),Ct({Result:Vt(jt(),wt())}),Ct({NestedResult:$t([Vt(jt(),wt()),Vt(jt(),wt())])})]),vt(e=>({...e,$kind:Object.keys(e)[0]}))),un=Ct({budget:_t(an),price:_t(an),owner:_t(nn),payment:_t(St(on))}),dn=Mt([Tt("address"),Tt("bool"),Tt("u8"),Tt("u16"),Tt("u32"),Tt("u64"),Tt("u128"),Tt("u256"),Ct({vector:It(()=>dn)}),Ct({datatype:Ct({package:Nt(),module:Nt(),type:Nt(),typeParameters:St(It(()=>dn))})}),Ct({typeParameter:Vt(jt(),wt())})]),ln=Ct({ref:_t(Mt([Tt("&"),Tt("&mut")])),body:dn}),hn=Ct({package:rn,module:Nt(),function:Nt(),typeArguments:St(Nt()),arguments:St(cn),_argumentTypes:Pt(_t(St(ln)))}),pn=Ct({name:Nt(),inputs:Bt(Nt(),Mt([cn,St(cn)])),data:Bt(Nt(),Dt())}),fn=tn({MoveCall:hn,TransferObjects:Ct({objects:St(cn),address:cn}),SplitCoins:Ct({coin:cn,amounts:St(cn)}),MergeCoins:Ct({destination:cn,sources:St(cn)}),Publish:Ct({modules:St(sn),dependencies:St(rn)}),MakeMoveVec:Ct({type:_t(Nt()),elements:St(cn)}),Upgrade:Ct({modules:St(sn),dependencies:St(rn),package:rn,ticket:cn}),$Intent:pn}),gn=tn({ImmOrOwnedObject:on,SharedObject:Ct({objectId:rn,initialSharedVersion:an,mutable:Ot()}),Receiving:on}),mn=tn({Object:gn,Pure:Ct({bytes:sn}),UnresolvedPure:Ct({value:Dt()}),UnresolvedObject:Ct({objectId:rn,version:Pt(_t(an)),digest:Pt(_t(Nt())),initialSharedVersion:Pt(_t(an)),mutable:Pt(_t(Ot()))})}),yn=tn({Object:gn,Pure:Ct({bytes:sn})}),bn=tn({None:Tt(!0),Epoch:an}),wn=Ct({version:Tt(2),sender:At(nn),expiration:At(bn),gasData:un,inputs:St(mn),commands:St(fn)}),vn={MoveCall(e){const[t,n="",r=""]="target"in e?e.target.split("::"):[e.package,e.module,e.function];return{$kind:"MoveCall",MoveCall:{package:t,module:n,function:r,typeArguments:e.typeArguments??[],arguments:e.arguments??[]}}},TransferObjects:(e,t)=>({$kind:"TransferObjects",TransferObjects:{objects:e.map(e=>Ut(cn,e)),address:Ut(cn,t)}}),SplitCoins:(e,t)=>({$kind:"SplitCoins",SplitCoins:{coin:Ut(cn,e),amounts:t.map(e=>Ut(cn,e))}}),MergeCoins:(e,t)=>({$kind:"MergeCoins",MergeCoins:{destination:Ut(cn,e),sources:t.map(e=>Ut(cn,e))}}),Publish:({modules:e,dependencies:t})=>({$kind:"Publish",Publish:{modules:e.map(e=>"string"==typeof e?e:xe(new Uint8Array(e))),dependencies:t.map(e=>en(e))}}),Upgrade:({modules:e,dependencies:t,package:n,ticket:r})=>({$kind:"Upgrade",Upgrade:{modules:e.map(e=>"string"==typeof e?e:xe(new Uint8Array(e))),dependencies:t.map(e=>en(e)),package:n,ticket:Ut(cn,r)}}),MakeMoveVec:({type:e,elements:t})=>({$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(e=>Ut(cn,e))}}),Intent:({name:e,inputs:t={},data:n={}})=>({$kind:"$Intent",$Intent:{name:e,inputs:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.map(e=>Ut(cn,e)):Ut(cn,t)])),data:n}})},kn=/^vector<(.+)>$/,En=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Sn{static parseFromStr(e,t=!1){if("address"===e)return{address:null};if("bool"===e)return{bool:null};if("u8"===e)return{u8:null};if("u16"===e)return{u16:null};if("u32"===e)return{u32:null};if("u64"===e)return{u64:null};if("u128"===e)return{u128:null};if("u256"===e)return{u256:null};if("signer"===e)return{signer:null};const n=e.match(kn);if(n)return{vector:Sn.parseFromStr(n[1],t)};const r=e.match(En);if(r){return{struct:{address:t?Qt(r[1]):r[1],module:r[2],name:r[3],typeParams:void 0===r[5]?[]:Sn.parseStructTypeArgs(r[5],t)}}}throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,t=!1){return Re(e).map(e=>Sn.parseFromStr(e,t))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Sn.tagToString(e.vector)}>`;if("struct"in e){const t=e.struct,n=t.typeParams.map(Sn.tagToString).join(", ");return`${t.address}::${t.module}::${t.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}const xn=st.bytes(Gt).transform({validate:e=>{const t="string"==typeof e?e:Ie(e);if(!t||!Ht(Qt(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>"string"==typeof e?Oe(Qt(e)):e,output:e=>Qt(Ie(e))}),On=st.byteVector().transform({name:"ObjectDigest",input:e=>ke(e),output:e=>ve(new Uint8Array(e)),validate:e=>{if(32!==ke(e).length)throw new Error("ObjectDigest must be 32 bytes")}}),In=st.struct("SuiObjectRef",{objectId:xn,version:st.u64(),digest:On}),Tn=st.struct("SharedObjectRef",{objectId:xn,initialSharedVersion:st.u64(),mutable:st.bool()}),_n=st.enum("ObjectArg",{ImmOrOwnedObject:In,SharedObject:Tn,Receiving:In}),An=st.enum("Owner",{AddressOwner:xn,ObjectOwner:xn,Shared:st.struct("Shared",{initialSharedVersion:st.u64()}),Immutable:null,ConsensusAddressOwner:st.struct("ConsensusAddressOwner",{owner:xn,startVersion:st.u64()})}),jn=st.enum("CallArg",{Pure:st.struct("Pure",{bytes:st.byteVector().transform({input:e=>"string"==typeof e?Ee(e):e,output:e=>xe(new Uint8Array(e))})}),Object:_n}),Cn=st.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:st.lazy(()=>Cn),struct:st.lazy(()=>Fn),u16:null,u32:null,u256:null}),Pn=Cn.transform({input:e=>"string"==typeof e?Sn.parseFromStr(e,!0):e,output:e=>Sn.tagToString(e)}),Bn=st.enum("Argument",{GasCoin:null,Input:st.u16(),Result:st.u16(),NestedResult:st.tuple([st.u16(),st.u16()])}),Nn=st.struct("ProgrammableMoveCall",{package:xn,module:st.string(),function:st.string(),typeArguments:st.vector(Pn),arguments:st.vector(Bn)}),$n=st.enum("Command",{MoveCall:Nn,TransferObjects:st.struct("TransferObjects",{objects:st.vector(Bn),address:Bn}),SplitCoins:st.struct("SplitCoins",{coin:Bn,amounts:st.vector(Bn)}),MergeCoins:st.struct("MergeCoins",{destination:Bn,sources:st.vector(Bn)}),Publish:st.struct("Publish",{modules:st.vector(st.byteVector().transform({input:e=>"string"==typeof e?Ee(e):e,output:e=>xe(new Uint8Array(e))})),dependencies:st.vector(xn)}),MakeMoveVec:st.struct("MakeMoveVec",{type:(Rn=Pn,st.enum("Option",{None:null,Some:Rn})).transform({input:e=>null===e?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:st.vector(Bn)}),Upgrade:st.struct("Upgrade",{modules:st.vector(st.byteVector().transform({input:e=>"string"==typeof e?Ee(e):e,output:e=>xe(new Uint8Array(e))})),dependencies:st.vector(xn),package:xn,ticket:Bn})});var Rn;const Mn=st.struct("ProgrammableTransaction",{inputs:st.vector(jn),commands:st.vector($n)}),Dn=st.enum("TransactionKind",{ProgrammableTransaction:Mn,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),Un=st.enum("TransactionExpiration",{None:null,Epoch:st.u64({name:"unsafe_u64",...Vn}).transform({input:e=>e,output:e=>Number(e)})});var Vn;const Fn=st.struct("StructTag",{address:xn,module:st.string(),name:st.string(),typeParams:st.vector(Cn)}),Ln=st.struct("GasData",{payment:st.vector(In),owner:xn,price:st.u64(),budget:st.u64()}),Kn=st.struct("TransactionDataV1",{kind:Dn,sender:xn,gasData:Ln,expiration:Un}),qn=st.enum("TransactionData",{V1:Kn}),zn=st.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Zn=st.enum("IntentVersion",{V0:null}),Wn=st.enum("AppId",{Sui:null}),Gn=st.struct("Intent",{scope:zn,version:Zn,appId:Wn});function Hn(e){return st.struct(`IntentMessage<${e.name}>`,{intent:Gn,value:e})}const Jn=st.enum("CompressedSignature",{ED25519:st.bytes(64),Secp256k1:st.bytes(64),Secp256r1:st.bytes(64),ZkLogin:st.byteVector(),Passkey:st.byteVector()}),Yn=st.enum("PublicKey",{ED25519:st.bytes(32),Secp256k1:st.bytes(33),Secp256r1:st.bytes(33),ZkLogin:st.byteVector(),Passkey:st.bytes(33)}),Xn=st.struct("MultiSigPkMap",{pubKey:Yn,weight:st.u8()}),Qn=st.struct("MultiSigPublicKey",{pk_map:st.vector(Xn),threshold:st.u16()}),er=st.struct("MultiSig",{sigs:st.vector(Jn),bitmap:st.u16(),multisig_pk:Qn}),tr=st.byteVector().transform({input:e=>"string"==typeof e?Ee(e):e,output:e=>xe(new Uint8Array(e))}),nr=st.struct("SenderSignedTransaction",{intentMessage:Hn(qn),txSignatures:st.vector(tr)}),rr=st.vector(nr,{name:"SenderSignedData"}),sr=st.struct("PasskeyAuthenticator",{authenticatorData:st.byteVector(),clientDataJson:st.string(),userSignature:st.byteVector()}),ir=st.enum("PackageUpgradeError",{UnableToFetchPackage:st.struct("UnableToFetchPackage",{packageId:xn}),NotAPackage:st.struct("NotAPackage",{objectId:xn}),IncompatibleUpgrade:null,DigestDoesNotMatch:st.struct("DigestDoesNotMatch",{digest:st.byteVector()}),UnknownUpgradePolicy:st.struct("UnknownUpgradePolicy",{policy:st.u8()}),PackageIDDoesNotMatch:st.struct("PackageIDDoesNotMatch",{packageId:xn,ticketId:xn})}),ar=st.struct("ModuleId",{address:xn,name:st.string()}),or=st.struct("MoveLocation",{module:ar,function:st.u16(),instruction:st.u16(),functionName:st.option(st.string())}),cr=st.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:st.struct("IndexOutOfBounds",{idx:st.u16()}),SecondaryIndexOutOfBounds:st.struct("SecondaryIndexOutOfBounds",{resultIdx:st.u16(),secondaryIdx:st.u16()}),InvalidResultArity:st.struct("InvalidResultArity",{resultIdx:st.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),ur=st.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),dr=st.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:st.struct("MoveObjectTooBig",{objectSize:st.u64(),maxObjectSize:st.u64()}),MovePackageTooBig:st.struct("MovePackageTooBig",{objectSize:st.u64(),maxObjectSize:st.u64()}),CircularObjectOwnership:st.struct("CircularObjectOwnership",{object:xn}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:st.option(or),MoveAbort:st.tuple([or,st.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:st.struct("CommandArgumentError",{argIdx:st.u16(),kind:cr}),TypeArgumentError:st.struct("TypeArgumentError",{argumentIdx:st.u16(),kind:ur}),UnusedValueWithoutDrop:st.struct("UnusedValueWithoutDrop",{resultIdx:st.u16(),secondaryIdx:st.u16()}),InvalidPublicFunctionReturnType:st.struct("InvalidPublicFunctionReturnType",{idx:st.u16()}),InvalidTransferObject:null,EffectsTooLarge:st.struct("EffectsTooLarge",{currentSize:st.u64(),maxSize:st.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:st.struct("PackageUpgradeError",{upgradeError:ir}),WrittenObjectsTooLarge:st.struct("WrittenObjectsTooLarge",{currentSize:st.u64(),maxSize:st.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:st.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:st.vector(xn)}),AddressDeniedForCoin:st.struct("AddressDeniedForCoin",{address:xn,coinType:st.string()}),CoinTypeGlobalPause:st.struct("CoinTypeGlobalPause",{coinType:st.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),lr=st.enum("ExecutionStatus",{Success:null,Failed:st.struct("ExecutionFailed",{error:dr,command:st.option(st.u64())})}),hr=st.struct("GasCostSummary",{computationCost:st.u64(),storageCost:st.u64(),storageRebate:st.u64(),nonRefundableStorageFee:st.u64()}),pr=st.struct("TransactionEffectsV1",{status:lr,executedEpoch:st.u64(),gasUsed:hr,modifiedAtVersions:st.vector(st.tuple([xn,st.u64()])),sharedObjects:st.vector(In),transactionDigest:On,created:st.vector(st.tuple([In,An])),mutated:st.vector(st.tuple([In,An])),unwrapped:st.vector(st.tuple([In,An])),deleted:st.vector(In),unwrappedThenDeleted:st.vector(In),wrapped:st.vector(In),gasObject:st.tuple([In,An]),eventsDigest:st.option(On),dependencies:st.vector(On)}),fr=st.tuple([st.u64(),On]),gr=st.enum("ObjectIn",{NotExist:null,Exist:st.tuple([fr,An])}),mr=st.enum("ObjectOut",{NotExist:null,ObjectWrite:st.tuple([On,An]),PackageWrite:fr}),yr=st.enum("IDOperation",{None:null,Created:null,Deleted:null}),br=st.struct("EffectsObjectChange",{inputState:gr,outputState:mr,idOperation:yr}),wr=st.enum("UnchangedSharedKind",{ReadOnlyRoot:fr,MutateDeleted:st.u64(),ReadDeleted:st.u64(),Cancelled:st.u64(),PerEpochConfig:null}),vr=st.struct("TransactionEffectsV2",{status:lr,executedEpoch:st.u64(),gasUsed:hr,transactionDigest:On,gasObjectIndex:st.option(st.u32()),eventsDigest:st.option(On),dependencies:st.vector(On),lamportVersion:st.u64(),changedObjects:st.vector(st.tuple([xn,br])),unchangedSharedObjects:st.vector(st.tuple([xn,wr])),auxDataDigest:st.option(On)}),kr=st.enum("TransactionEffects",{V1:pr,V2:vr});function Er(e){switch(e){case"u8":return st.u8();case"u16":return st.u16();case"u32":return st.u32();case"u64":return st.u64();case"u128":return st.u128();case"u256":return st.u256();case"bool":return st.bool();case"string":return st.string();case"id":case"address":return xn}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[e,n]=t.slice(1);return"vector"===e?st.vector(Er(n)):st.option(Er(n))}throw new Error(`Invalid Pure type name: ${e}`)}const Sr={...st,U8:st.u8(),U16:st.u16(),U32:st.u32(),U64:st.u64(),U128:st.u128(),U256:st.u256(),ULEB128:st.uleb128(),Bool:st.bool(),String:st.string(),Address:xn,AppId:Wn,Argument:Bn,CallArg:jn,Command:$n,CompressedSignature:Jn,GasData:Ln,Intent:Gn,IntentMessage:Hn,IntentScope:zn,IntentVersion:Zn,MultiSig:er,MultiSigPkMap:Xn,MultiSigPublicKey:Qn,ObjectArg:_n,ObjectDigest:On,Owner:An,PasskeyAuthenticator:sr,ProgrammableMoveCall:Nn,ProgrammableTransaction:Mn,PublicKey:Yn,SenderSignedData:rr,SenderSignedTransaction:nr,SharedObjectRef:Tn,StructTag:Fn,SuiObjectRef:In,TransactionData:qn,TransactionDataV1:Kn,TransactionEffects:kr,TransactionExpiration:Un,TransactionKind:Dn,TypeTag:Pn},xr=Ct({digest:Nt(),objectId:Nt(),version:Mt([Vt(jt(),wt()),Nt(),xt()])}),Or=tn({ImmOrOwned:xr,Shared:Ct({objectId:rn,initialSharedVersion:an,mutable:Ot()}),Receiving:xr}),Ir=tn({Object:Or,Pure:St(Vt(jt(),wt()))}),Tr=Mt([Ct({kind:Tt("Input"),index:Vt(jt(),wt()),value:Dt(),type:Pt(Tt("object"))}),Ct({kind:Tt("Input"),index:Vt(jt(),wt()),value:Dt(),type:Tt("pure")})]),_r=Mt([Ct({Epoch:Vt(jt(),wt())}),Ct({None:_t(Tt(!0))})]),Ar=Vt(Mt([jt(),Nt(),xt()]),bt(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),jr=Mt([Ct({bool:_t(Tt(!0))}),Ct({u8:_t(Tt(!0))}),Ct({u64:_t(Tt(!0))}),Ct({u128:_t(Tt(!0))}),Ct({address:_t(Tt(!0))}),Ct({signer:_t(Tt(!0))}),Ct({vector:It(()=>jr)}),Ct({struct:It(()=>Cr)}),Ct({u16:_t(Tt(!0))}),Ct({u32:_t(Tt(!0))}),Ct({u256:_t(Tt(!0))})]),Cr=Ct({address:Nt(),module:Nt(),name:Nt(),typeParams:St(jr)}),Pr=Ct({budget:Pt(Ar),price:Pt(Ar),payment:Pt(St(xr)),owner:Pt(Nt())}),Br=Mt([...[Tr,Ct({kind:Tt("GasCoin")}),Ct({kind:Tt("Result"),index:Vt(jt(),wt())}),Ct({kind:Tt("NestedResult"),index:Vt(jt(),wt()),resultIndex:Vt(jt(),wt())})]]),Nr=Ct({kind:Tt("MoveCall"),target:Vt(Nt(),bt(e=>3===e.split("::").length)),typeArguments:St(Nt()),arguments:St(Br)}),$r=Ct({kind:Tt("TransferObjects"),objects:St(Br),address:Br}),Rr=Ct({kind:Tt("SplitCoins"),coin:Br,amounts:St(Br)}),Mr=Ct({kind:Tt("MergeCoins"),destination:Br,sources:St(Br)}),Dr=Ct({kind:Tt("MakeMoveVec"),type:Mt([Ct({Some:jr}),Ct({None:_t(Tt(!0))})]),objects:St(Br)}),Ur=Mt([...[Nr,$r,Rr,Mr,Ct({kind:Tt("Publish"),modules:St(St(Vt(jt(),wt()))),dependencies:St(Nt())}),Ct({kind:Tt("Upgrade"),modules:St(St(Vt(jt(),wt()))),dependencies:St(Nt()),packageId:Nt(),ticket:Br}),Dr]]);function Vr(e){const t=e.inputs.map((e,t)=>{if(e.Object)return{kind:"Input",index:t,value:{Object:e.Object.ImmOrOwnedObject?{ImmOrOwned:e.Object.ImmOrOwnedObject}:e.Object.Receiving?{Receiving:{digest:e.Object.Receiving.digest,version:e.Object.Receiving.version,objectId:e.Object.Receiving.objectId}}:{Shared:{mutable:e.Object.SharedObject.mutable,initialSharedVersion:e.Object.SharedObject.initialSharedVersion,objectId:e.Object.SharedObject.objectId}}},type:"object"};if(e.Pure)return{kind:"Input",index:t,value:{Pure:Array.from(Ee(e.Pure.bytes))},type:"pure"};if(e.UnresolvedPure)return{kind:"Input",type:"pure",index:t,value:e.UnresolvedPure.value};if(e.UnresolvedObject)return{kind:"Input",type:"object",index:t,value:e.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:e.sender??void 0,expiration:"Epoch"===e.expiration?.$kind?{Epoch:Number(e.expiration.Epoch)}:e.expiration?{None:!0}:null,gasConfig:{owner:e.gasData.owner??void 0,budget:e.gasData.budget??void 0,price:e.gasData.price??void 0,payment:e.gasData.payment??void 0},inputs:t,transactions:e.commands.map(e=>{if(e.MakeMoveVec)return{kind:"MakeMoveVec",type:null===e.MakeMoveVec.type?{None:!0}:{Some:Sn.parseFromStr(e.MakeMoveVec.type)},objects:e.MakeMoveVec.elements.map(e=>Fr(e,t))};if(e.MergeCoins)return{kind:"MergeCoins",destination:Fr(e.MergeCoins.destination,t),sources:e.MergeCoins.sources.map(e=>Fr(e,t))};if(e.MoveCall)return{kind:"MoveCall",target:`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`,typeArguments:e.MoveCall.typeArguments,arguments:e.MoveCall.arguments.map(e=>Fr(e,t))};if(e.Publish)return{kind:"Publish",modules:e.Publish.modules.map(e=>Array.from(Ee(e))),dependencies:e.Publish.dependencies};if(e.SplitCoins)return{kind:"SplitCoins",coin:Fr(e.SplitCoins.coin,t),amounts:e.SplitCoins.amounts.map(e=>Fr(e,t))};if(e.TransferObjects)return{kind:"TransferObjects",objects:e.TransferObjects.objects.map(e=>Fr(e,t)),address:Fr(e.TransferObjects.address,t)};if(e.Upgrade)return{kind:"Upgrade",modules:e.Upgrade.modules.map(e=>Array.from(Ee(e))),dependencies:e.Upgrade.dependencies,packageId:e.Upgrade.package,ticket:Fr(e.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(e)}`)})}}function Fr(e,t){if("GasCoin"===e.$kind)return{kind:"GasCoin"};if("Result"===e.$kind)return{kind:"Result",index:e.Result};if("NestedResult"===e.$kind)return{kind:"NestedResult",index:e.NestedResult[0],resultIndex:e.NestedResult[1]};if("Input"===e.$kind)return t[e.Input];throw new Error(`Invalid argument ${Object.keys(e)}`)}function Lr(e){switch(e.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:e.index};case"NestedResult":return{NestedResult:[e.index,e.resultIndex]};case"Input":return{Input:e.index}}}function Kr(e){return Mt(Object.entries(e).map(([e,t])=>Ct({[e]:t})))}Ct({version:Tt(1),sender:Pt(Nt()),expiration:At(_r),gasConfig:Pr,inputs:St(Tr),transactions:St(Ur)});const qr=Kr({GasCoin:Tt(!0),Input:Vt(jt(),wt()),Result:Vt(jt(),wt()),NestedResult:$t([Vt(jt(),wt()),Vt(jt(),wt())])}),zr=Ct({budget:_t(an),price:_t(an),owner:_t(nn),payment:_t(St(on))}),Zr=Ct({package:rn,module:Nt(),function:Nt(),typeArguments:St(Nt()),arguments:St(qr)}),Wr=Ct({name:Nt(),inputs:Bt(Nt(),Mt([qr,St(qr)])),data:Bt(Nt(),Dt())}),Gr=Kr({MoveCall:Zr,TransferObjects:Ct({objects:St(qr),address:qr}),SplitCoins:Ct({coin:qr,amounts:St(qr)}),MergeCoins:Ct({destination:qr,sources:St(qr)}),Publish:Ct({modules:St(sn),dependencies:St(rn)}),MakeMoveVec:Ct({type:_t(Nt()),elements:St(qr)}),Upgrade:Ct({modules:St(sn),dependencies:St(rn),package:rn,ticket:qr}),$Intent:Wr}),Hr=Kr({ImmOrOwnedObject:on,SharedObject:Ct({objectId:rn,initialSharedVersion:an,mutable:Ot()}),Receiving:on}),Jr=Kr({Object:Hr,Pure:Ct({bytes:sn}),UnresolvedPure:Ct({value:Dt()}),UnresolvedObject:Ct({objectId:rn,version:Pt(_t(an)),digest:Pt(_t(Nt())),initialSharedVersion:Pt(_t(an)),mutable:Pt(_t(Ot()))})}),Yr=Kr({None:Tt(!0),Epoch:an}),Xr=Ct({version:Tt(2),sender:At(nn),expiration:At(Yr),gasData:zr,inputs:St(Jr),commands:St(Gr),digest:Pt(_t(Nt()))});const Qr={Pure:function(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?xe(e):e.toBase64()}}},ObjectRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:t,version:n,objectId:Qt(e)}}}),SharedObjectRef:({objectId:e,mutable:t,initialSharedVersion:n})=>({$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:t,initialSharedVersion:n,objectId:Qt(e)}}}),ReceivingRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:t,version:n,objectId:Qt(e)}}})};BigInt(1e9);const es=en("0x6"),ts="0x2::sui::SUI";en("0x5"),en("0x8");const ns="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function rs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ss(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function is(e,...t){if(!rs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function as(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ss(e.outputLen),ss(e.blockLen)}function os(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function cs(e,t){is(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function us(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ds(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ls(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hs(e,t){return e<<32-t|e>>>t}function ps(e,t){return e<<t|e>>>32-t>>>0}const fs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function gs(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const ms=fs?e=>e:e=>gs(e);const ys=fs?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=gs(e[t]);return e},bs=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),ws=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vs(e){if(is(e),bs)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ws[e[n]];return t}const ks=48,Es=57,Ss=65,xs=70,Os=97,Is=102;function Ts(e){return e>=ks&&e<=Es?e-ks:e>=Ss&&e<=xs?e-(Ss-10):e>=Os&&e<=Is?e-(Os-10):void 0}function _s(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(bs)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=Ts(e.charCodeAt(s)),i=Ts(e.charCodeAt(s+1));if(void 0===n||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+i}return r}function As(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function js(e){return"string"==typeof e&&(e=As(e)),is(e),e}function Cs(e){return"string"==typeof e&&(e=As(e)),is(e),e}function Ps(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];is(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}class Bs{}function Ns(e){const t=t=>e().update(js(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function $s(e){const t=(t,n)=>e(n).update(js(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}function Rs(e=32){if(ns&&"function"==typeof ns.getRandomValues)return ns.getRandomValues(new Uint8Array(e));if(ns&&"function"==typeof ns.randomBytes)return Uint8Array.from(ns.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Ms=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]);function Ds(e,t,n){return e&t^~e&n}function Us(e,t,n){return e&t^e&n^t&n}class Vs extends Bs{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ls(this.buffer)}update(e){os(this),is(e=js(e));const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(r-this.pos,s-i);if(a===r){const t=ls(e);for(;r<=s-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){os(this),cs(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,ds(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const s=BigInt(32),i=BigInt(4294967295),a=Number(n>>s&i),o=Number(n&i),c=r?4:0,u=r?0:4;e.setUint32(t+c,a,r),e.setUint32(t+u,o,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const a=ls(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)a.setUint32(4*e,u[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=a,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Fs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ls=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Ks=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),qs=BigInt(2**32-1),zs=BigInt(32);function Zs(e,t=!1){return t?{h:Number(e&qs),l:Number(e>>zs&qs)}:{h:0|Number(e>>zs&qs),l:0|Number(e&qs)}}const Ws=(e,t,n)=>e>>>n,Gs=(e,t,n)=>e<<32-n|t>>>n,Hs=(e,t,n)=>e>>>n|t<<32-n,Js=(e,t,n)=>e<<32-n|t>>>n,Ys=(e,t,n)=>e<<64-n|t>>>n-32,Xs=(e,t,n)=>e>>>n-32|t<<64-n,Qs=(e,t)=>t;function ei(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const ti=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ni=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,ri=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),si=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,ii=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),ai=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,oi=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ci=new Uint32Array(32);function ui(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=ci[2*e],u=ci[2*e+1],d=ci[2*t],l=ci[2*t+1],h=ci[2*n],p=ci[2*n+1],f=ci[2*r],g=ci[2*r+1],m=ti(c,d,a);var y;u=ni(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:Qs(0,f),Dl:(y=g,y)}),({h:p,l:h}=ei(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:Hs(l,d,24),Bl:Js(l,d,24)}),ci[2*e]=c,ci[2*e+1]=u,ci[2*t]=d,ci[2*t+1]=l,ci[2*n]=h,ci[2*n+1]=p,ci[2*r]=f,ci[2*r+1]=g}function di(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=ci[2*e],u=ci[2*e+1],d=ci[2*t],l=ci[2*t+1],h=ci[2*n],p=ci[2*n+1],f=ci[2*r],g=ci[2*r+1],m=ti(c,d,a);u=ni(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:Hs(g,f,16),Dl:Js(g,f,16)}),({h:p,l:h}=ei(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:Ys(l,d,63),Bl:Xs(l,d,63)}),ci[2*e]=c,ci[2*e+1]=u,ci[2*t]=d,ci[2*t+1]=l,ci[2*n]=h,ci[2*n+1]=p,ci[2*r]=f,ci[2*r+1]=g}class li extends Bs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ss(e),ss(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=us(this.buffer)}update(e){os(this),is(e=js(e));const{blockLen:t,buffer:n,buffer32:r}=this,s=e.length,i=e.byteOffset,a=e.buffer;for(let o=0;o<s;){this.pos===t&&(ys(r),this.compress(r,0,!1),ys(r),this.pos=0);const c=Math.min(t-this.pos,s-o),u=i+o;if(c===t&&!(u%4)&&o+c<s){const e=new Uint32Array(a,u,Math.floor((s-o)/4));ys(e);for(let n=0;o+t<s;n+=r.length,o+=t)this.length+=t,this.compress(e,n,!1);ys(e);continue}n.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c}return this}digestInto(e){os(this),cs(e,this);const{pos:t,buffer32:n}=this;this.finished=!0,ds(this.buffer.subarray(t)),ys(n),this.compress(n,0,!0),ys(n);const r=us(e);this.get().forEach((e,t)=>r[t]=ms(e))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){const{buffer:t,length:n,finished:r,destroyed:s,outputLen:i,pos:a}=this;return e||(e=new this.constructor({dkLen:i})),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=r,e.length=n,e.pos=a,e.outputLen=i,e}clone(){return this._cloneInto()}}class hi extends li{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|oi[0],this.v0h=0|oi[1],this.v1l=0|oi[2],this.v1h=0|oi[3],this.v2l=0|oi[4],this.v2h=0|oi[5],this.v3l=0|oi[6],this.v3h=0|oi[7],this.v4l=0|oi[8],this.v4h=0|oi[9],this.v5l=0|oi[10],this.v5h=0|oi[11],this.v6l=0|oi[12],this.v6h=0|oi[13],this.v7l=0|oi[14],this.v7h=0|oi[15],function(e,t={},n,r,s){if(ss(n),e<0||e>n)throw new Error("outputLen bigger than keyLen");const{key:i,salt:a,personalization:o}=t;if(void 0!==i&&(i.length<1||i.length>n))throw new Error("key length must be undefined or 1.."+n);if(void 0!==a&&a.length!==r)throw new Error("salt must be undefined or "+r);if(void 0!==o&&o.length!==s)throw new Error("personalization must be undefined or "+s)}(t,e,64,16,16);let{key:n,personalization:r,salt:s}=e,i=0;if(void 0!==n&&(n=js(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==s){s=js(s);const e=us(s);this.v4l^=ms(e[0]),this.v4h^=ms(e[1]),this.v5l^=ms(e[2]),this.v5h^=ms(e[3])}if(void 0!==r){r=js(r);const e=us(r);this.v6l^=ms(e[0]),this.v6h^=ms(e[1]),this.v7l^=ms(e[2]),this.v7h^=ms(e[3])}if(void 0!==n){const e=new Uint8Array(this.blockLen);e.set(n),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:n,v1h:r,v2l:s,v2h:i,v3l:a,v3h:o,v4l:c,v4h:u,v5l:d,v5h:l,v6l:h,v6h:p,v7l:f,v7h:g}=this;return[e,t,n,r,s,i,a,o,c,u,d,l,h,p,f,g]}set(e,t,n,r,s,i,a,o,c,u,d,l,h,p,f,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|n,this.v1h=0|r,this.v2l=0|s,this.v2h=0|i,this.v3l=0|a,this.v3h=0|o,this.v4l=0|c,this.v4h=0|u,this.v5l=0|d,this.v5h=0|l,this.v6l=0|h,this.v6h=0|p,this.v7l=0|f,this.v7h=0|g}compress(e,t,n){this.get().forEach((e,t)=>ci[t]=e),ci.set(oi,16);let{h:r,l:s}=Zs(BigInt(this.length));ci[24]=oi[8]^s,ci[25]=oi[9]^r,n&&(ci[28]=~ci[28],ci[29]=~ci[29]);let i=0;const a=Ms;for(let n=0;n<12;n++)ui(0,4,8,12,e,t+2*a[i++]),di(0,4,8,12,e,t+2*a[i++]),ui(1,5,9,13,e,t+2*a[i++]),di(1,5,9,13,e,t+2*a[i++]),ui(2,6,10,14,e,t+2*a[i++]),di(2,6,10,14,e,t+2*a[i++]),ui(3,7,11,15,e,t+2*a[i++]),di(3,7,11,15,e,t+2*a[i++]),ui(0,5,10,15,e,t+2*a[i++]),di(0,5,10,15,e,t+2*a[i++]),ui(1,6,11,12,e,t+2*a[i++]),di(1,6,11,12,e,t+2*a[i++]),ui(2,7,8,13,e,t+2*a[i++]),di(2,7,8,13,e,t+2*a[i++]),ui(3,4,9,14,e,t+2*a[i++]),di(3,4,9,14,e,t+2*a[i++]);this.v0l^=ci[0]^ci[16],this.v0h^=ci[1]^ci[17],this.v1l^=ci[2]^ci[18],this.v1h^=ci[3]^ci[19],this.v2l^=ci[4]^ci[20],this.v2h^=ci[5]^ci[21],this.v3l^=ci[6]^ci[22],this.v3h^=ci[7]^ci[23],this.v4l^=ci[8]^ci[24],this.v4h^=ci[9]^ci[25],this.v5l^=ci[10]^ci[26],this.v5h^=ci[11]^ci[27],this.v6l^=ci[12]^ci[28],this.v6h^=ci[13]^ci[29],this.v7l^=ci[14]^ci[30],this.v7h^=ci[15]^ci[31],ds(ci)}destroy(){this.destroyed=!0,ds(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const pi=$s(e=>new hi(e));function fi(e,t,n){const r=Sr.Address.serialize(e).toBytes(),s=Sr.TypeTag.serialize(t).toBytes(),i=Sr.u64().serialize(n.length).toBytes(),a=pi.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(r),a.update(i),a.update(n),a.update(s),`0x${Ie(a.digest().slice(0,32))}`}function gi(e){if("string"==typeof e)switch(e){case"address":return Sr.Address;case"bool":return Sr.Bool;case"u8":return Sr.U8;case"u16":return Sr.U16;case"u32":return Sr.U32;case"u64":return Sr.U64;case"u128":return Sr.U128;case"u256":return Sr.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if("u8"===e.vector)return Sr.byteVector().transform({input:e=>"string"==typeof e?(new TextEncoder).encode(e):e,output:e=>e});const t=gi(e.vector);return t?Sr.vector(t):null}if("datatype"in e){const t=Qt(e.datatype.package);if(t===Qt("0x1")){if("ascii"===e.datatype.module&&"String"===e.datatype.type)return Sr.String;if("string"===e.datatype.module&&"String"===e.datatype.type)return Sr.String;if("option"===e.datatype.module&&"Option"===e.datatype.type){const t=gi(e.datatype.typeParameters[0]);return t?Sr.vector(t):null}}if(t===Qt("0x2")&&"object"===e.datatype.module&&"ID"===e.datatype.type)return Sr.Address}return null}function mi(e){if("string"==typeof e)switch(e){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${e}`)}if("Vector"in e)return{vector:mi(e.Vector)};if("Struct"in e)return{datatype:{package:e.Struct.address,module:e.Struct.module,type:e.Struct.name,typeParameters:e.Struct.typeArguments.map(mi)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const yi=5e10;function bi(e){return async function(t,n,r){return await async function(e,t){const{inputs:n,commands:r}=e,s=[],i=new Set;r.forEach(t=>{if(t.MoveCall){if(t.MoveCall._argumentTypes)return;if(t.MoveCall.arguments.map(t=>"Input"===t.$kind?e.inputs[t.Input]:null).some(e=>e?.UnresolvedPure||e?.UnresolvedObject&&"boolean"!=typeof e?.UnresolvedObject.mutable)){const e=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;i.add(e),s.push(t.MoveCall)}}});const a=new Map;i.size>0&&await Promise.all([...i].map(async e=>{const[n,r,s]=e.split("::"),i=await t.getNormalizedMoveFunction({package:n,module:r,function:s});a.set(e,i.parameters.map(e=>function(e){return"object"==typeof e&&"Reference"in e?{ref:"&",body:mi(e.Reference)}:"object"==typeof e&&"MutableReference"in e?{ref:"&mut",body:mi(e.MutableReference)}:{ref:null,body:mi(e)}}(e)))}));s.length&&await Promise.all(s.map(async e=>{const t=a.get(`${e.package}::${e.module}::${e.function}`);if(!t)return;const n=t.length>0&&function(e){const t="object"==typeof e.body&&"datatype"in e.body?e.body.datatype:null;return!!t&&Qt(t.package)===Qt("0x2")&&"tx_context"===t.module&&"TxContext"===t.type}(t.at(-1))?t.slice(0,t.length-1):t;e._argumentTypes=n}));r.forEach(e=>{if(!e.MoveCall)return;const t=e.MoveCall,r=`${t.package}::${t.module}::${t.function}`,s=t._argumentTypes;if(s){if(s.length!==e.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${r}`);s.forEach((e,r)=>{const s=t.arguments[r];if("Input"!==s.$kind)return;const i=n[s.Input];if(!i.UnresolvedPure&&!i.UnresolvedObject)return;const a=i.UnresolvedPure?.value??i.UnresolvedObject?.objectId,o=gi(e.body);if(o)return s.type="pure",void(n[n.indexOf(i)]=Qr.Pure(o.serialize(a)));if("string"!=typeof a)throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(a,null,2)}`);s.type="object";const c=i.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:a}}:i;n[s.Input]=c})}})}(t,e),await async function(e,t){const n=e.inputs.filter(e=>e.UnresolvedObject&&!(e.UnresolvedObject.version||e.UnresolvedObject?.initialSharedVersion)),r=[...new Set(n.map(e=>en(e.UnresolvedObject.objectId)))],s=r.length?Te(r,50):[],i=(await Promise.all(s.map(e=>t.multiGetObjects({ids:e,options:{showOwner:!0}})))).flat(),a=new Map(r.map((e,t)=>[e,i[t]])),o=Array.from(a).filter(([e,t])=>t.error).map(([e,t])=>JSON.stringify(t.error));if(o.length)throw new Error(`The following input objects are invalid: ${o.join(", ")}`);const c=i.map(e=>{if(e.error||!e.data)throw new Error(`Failed to fetch object: ${e.error}`);const t=e.data.owner,n=t&&"object"==typeof t?"Shared"in t?t.Shared.initial_shared_version:"ConsensusAddressOwner"in t?t.ConsensusAddressOwner.start_version:null:null;return{objectId:e.data.objectId,digest:e.data.digest,version:e.data.version,initialSharedVersion:n}}),u=new Map(r.map((e,t)=>[e,c[t]]));for(const[t,n]of e.inputs.entries()){if(!n.UnresolvedObject)continue;let r;const s=Qt(n.UnresolvedObject.objectId),i=u.get(s);n.UnresolvedObject.initialSharedVersion??i?.initialSharedVersion?r=Qr.SharedObjectRef({objectId:s,initialSharedVersion:n.UnresolvedObject.initialSharedVersion||i?.initialSharedVersion,mutable:n.UnresolvedObject.mutable||wi(e,t)}):vi(e,t)&&(r=Qr.ReceivingRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})),e.inputs[e.inputs.indexOf(n)]=r??Qr.ObjectRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})}}(t,e),n.onlyTransactionKind||(await async function(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}(t,e),await async function(e,t){if(e.gasConfig.budget)return;const n=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(yi),payment:[]}}})});if("success"!==n.effects.status.status)throw new Error(`Dry run failed, could not automatically determine a budget: ${n.effects.status.error}`,{cause:n});const r=1000n*BigInt(e.gasConfig.price||1n),s=BigInt(n.effects.gasUsed.computationCost)+r,i=s+BigInt(n.effects.gasUsed.storageCost)-BigInt(n.effects.gasUsed.storageRebate);e.gasConfig.budget=String(i>s?i:s)}(t,e),await async function(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:ts})).data.filter(t=>!e.inputs.find(e=>!!e.Object?.ImmOrOwnedObject&&t.coinObjectId===e.Object.ImmOrOwnedObject.objectId)).map(e=>({objectId:e.coinObjectId,digest:e.digest,version:e.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");e.gasConfig.payment=n.map(e=>Ut(on,e))}}(t,e)),await r()}}function wi(e,t){let n=!1;return e.getInputUses(t,(e,t)=>{if(t.MoveCall&&t.MoveCall._argumentTypes){const r=t.MoveCall.arguments.indexOf(e);n="&"!==t.MoveCall._argumentTypes[r].ref||n}"MakeMoveVec"!==t.$kind&&"MergeCoins"!==t.$kind&&"SplitCoins"!==t.$kind&&"TransferObjects"!==t.$kind||(n=!0)}),n}function vi(e,t){let n=!1;return e.getInputUses(t,(e,t)=>{if(t.MoveCall&&t.MoveCall._argumentTypes){const r=t.MoveCall.arguments.indexOf(e);n=function(e){if("object"!=typeof e.body||!("datatype"in e.body))return!1;return"0x2"===e.body.datatype.package&&"transfer"===e.body.datatype.module&&"Receiving"===e.body.datatype.type}(t.MoveCall._argumentTypes[r])||n}}),n}function ki(e,t){return!!e.inputs.some(e=>e.UnresolvedObject||e.UnresolvedPure)||!(t.onlyTransactionKind||e.gasConfig.price&&e.gasConfig.budget&&e.gasConfig.payment)}async function Ei(e,t,n){if(function(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(t=>{xi(t,Sr.U64,e)});break;case"TransferObjects":xi(t.TransferObjects.address,Sr.Address,e)}}(e),!ki(e,t))return await Si(e),n();const r=function(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}(t);return(r.core?.resolveTransactionPlugin()??bi(r))(e,t,async()=>{await Si(e),await n()})}function Si(e){e.inputs.forEach((e,t)=>{if("Object"!==e.$kind&&"Pure"!==e.$kind)throw new Error(`Input at index ${t} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function xi(e,t,n){if("Input"!==e.$kind)return;const r=n.inputs[e.Input];"UnresolvedPure"===r.$kind&&(n.inputs[e.Input]=Qr.Pure(t.serialize(r.UnresolvedPure.value)))}function Oi(e){function t(t,n){if("string"==typeof t)return e(Er(t).serialize(n));if(t instanceof Uint8Array||Je(t))return e(t);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return t.u8=t=>e(Sr.U8.serialize(t)),t.u16=t=>e(Sr.U16.serialize(t)),t.u32=t=>e(Sr.U32.serialize(t)),t.u64=t=>e(Sr.U64.serialize(t)),t.u128=t=>e(Sr.U128.serialize(t)),t.u256=t=>e(Sr.U256.serialize(t)),t.bool=t=>e(Sr.Bool.serialize(t)),t.string=t=>e(Sr.String.serialize(t)),t.address=t=>e(Sr.Address.serialize(t)),t.id=t.address,t.vector=(t,n)=>e(Sr.vector(Er(t)).serialize(n)),t.option=(t,n)=>e(Sr.option(Er(t)).serialize(n)),t}function Ii(e){return"string"==typeof e?Qt(e):e.Object?e.Object.ImmOrOwnedObject?Qt(e.Object.ImmOrOwnedObject.objectId):e.Object.Receiving?Qt(e.Object.Receiving.objectId):Qt(e.Object.SharedObject.objectId):e.UnresolvedObject?Qt(e.UnresolvedObject.objectId):void 0}function Ti(e,t,n){const r=e=>{switch(e.$kind){case"Input":{const n=t.get(e.Input);if(void 0===n)throw new Error(`Input ${e.Input} not found in input mapping`);return{...e,Input:n}}case"Result":{const t=n.get(e.Result);return void 0!==t?{...e,Result:t}:e}case"NestedResult":{const t=n.get(e.NestedResult[0]);return void 0!==t?{...e,NestedResult:[t,e.NestedResult[1]]}:e}default:return e}};switch(e.$kind){case"MoveCall":e.MoveCall.arguments=e.MoveCall.arguments.map(r);break;case"TransferObjects":e.TransferObjects.objects=e.TransferObjects.objects.map(r),e.TransferObjects.address=r(e.TransferObjects.address);break;case"SplitCoins":e.SplitCoins.coin=r(e.SplitCoins.coin),e.SplitCoins.amounts=e.SplitCoins.amounts.map(r);break;case"MergeCoins":e.MergeCoins.destination=r(e.MergeCoins.destination),e.MergeCoins.sources=e.MergeCoins.sources.map(r);break;case"MakeMoveVec":e.MakeMoveVec.elements=e.MakeMoveVec.elements.map(r);break;case"Upgrade":e.Upgrade.ticket=r(e.Upgrade.ticket);break;case"$Intent":{const t=e.$Intent.inputs;e.$Intent.inputs={};for(const[n,s]of Object.entries(t))e.$Intent.inputs[n]=Array.isArray(s)?s.map(r):r(s);break}}}function _i(e){return Qt(e).replace("0x","")}class Ai{constructor(e){this.version=2,this.sender=e?.sender??null,this.expiration=e?.expiration??null,this.inputs=e?.inputs??[],this.commands=e?.commands??[],this.gasData=e?.gasData??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const t=Sr.TransactionKind.parse(e).ProgrammableTransaction;if(!t)throw new Error("Unable to deserialize from bytes.");return Ai.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:t.inputs,commands:t.commands})}static fromBytes(e){const t=Sr.TransactionData.parse(e),n=t?.V1,r=n.kind.ProgrammableTransaction;if(!n||!r)throw new Error("Unable to deserialize from bytes.");return Ai.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:r.inputs,commands:r.commands})}static restore(e){return 2===e.version?new Ai(Ut(wn,e)):new Ai(Ut(wn,function(e){return Ut(wn,{version:2,sender:e.sender??null,expiration:e.expiration?"Epoch"in e.expiration?{Epoch:e.expiration.Epoch}:{None:!0}:null,gasData:{owner:e.gasConfig.owner??null,budget:e.gasConfig.budget?.toString()??null,price:e.gasConfig.price?.toString()??null,payment:e.gasConfig.payment?.map(e=>({digest:e.digest,objectId:e.objectId,version:e.version.toString()}))??null},inputs:e.inputs.map(e=>{if("Input"===e.kind){if(Et(Ir,e.value)){const t=Ut(Ir,e.value);if(t.Object){if(t.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:t.Object.ImmOrOwned.objectId,version:String(t.Object.ImmOrOwned.version),digest:t.Object.ImmOrOwned.digest}}};if(t.Object.Shared)return{Object:{SharedObject:{mutable:t.Object.Shared.mutable??null,initialSharedVersion:t.Object.Shared.initialSharedVersion,objectId:t.Object.Shared.objectId}}};if(t.Object.Receiving)return{Object:{Receiving:{digest:t.Object.Receiving.digest,version:String(t.Object.Receiving.version),objectId:t.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:xe(new Uint8Array(t.Pure))}}}return"object"===e.type?{UnresolvedObject:{objectId:e.value}}:{UnresolvedPure:{value:e.value}}}throw new Error("Invalid input")}),commands:e.transactions.map(e=>{switch(e.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in e.type?Sn.tagToString(e.type.Some):null,elements:e.objects.map(e=>Lr(e))}};case"MergeCoins":return{MergeCoins:{destination:Lr(e.destination),sources:e.sources.map(e=>Lr(e))}};case"MoveCall":{const[t,n,r]=e.target.split("::");return{MoveCall:{package:t,module:n,function:r,typeArguments:e.typeArguments,arguments:e.arguments.map(e=>Lr(e))}}}case"Publish":return{Publish:{modules:e.modules.map(e=>xe(Uint8Array.from(e))),dependencies:e.dependencies}};case"SplitCoins":return{SplitCoins:{coin:Lr(e.coin),amounts:e.amounts.map(e=>Lr(e))}};case"TransferObjects":return{TransferObjects:{objects:e.objects.map(e=>Lr(e)),address:Lr(e.address)}};case"Upgrade":return{Upgrade:{modules:e.modules.map(e=>xe(Uint8Array.from(e))),dependencies:e.dependencies,package:e.packageId,ticket:Lr(e.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(e)}`)})})}(e)))}static getDigestFromBytes(e){const t=function(e,t){const n=Array.from(`${e}::`).map(e=>e.charCodeAt(0)),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),pi(r,{dkLen:32})}("TransactionData",e);return ve(t)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:t,onlyTransactionKind:n}={}){const r=this.inputs,s=this.commands,i={ProgrammableTransaction:{inputs:r,commands:s}};if(n)return Sr.TransactionKind.serialize(i,{maxSize:e}).toBytes();const a=t?.expiration??this.expiration,o=t?.sender??this.sender,c={...this.gasData,...t?.gasConfig,...t?.gasData};if(!o)throw new Error("Missing transaction sender");if(!c.budget)throw new Error("Missing gas budget");if(!c.payment)throw new Error("Missing gas payment");if(!c.price)throw new Error("Missing gas price");const u={sender:_i(o),expiration:a||{None:!0},gasData:{payment:c.payment,owner:_i(this.gasData.owner??o),price:BigInt(c.price),budget:BigInt(c.budget)},kind:{ProgrammableTransaction:{inputs:r,commands:s}}};return Sr.TransactionData.serialize({V1:u},{maxSize:e}).toBytes()}addInput(e,t){const n=this.inputs.length;return this.inputs.push(t),{Input:n,type:e,$kind:"Input"}}getInputUses(e,t){this.mapArguments((n,r)=>("Input"===n.$kind&&n.Input===e&&t(n,r),n))}mapCommandArguments(e,t){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(r=>t(r,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(r=>t(r,n,e)),n.TransferObjects.address=t(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=t(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(r=>t(r,n,e));break;case"MergeCoins":n.MergeCoins.destination=t(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(r=>t(r,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(r=>t(r,n,e));break;case"Upgrade":n.Upgrade.ticket=t(n.Upgrade.ticket,n,e);break;case"$Intent":const r=n.$Intent.inputs;n.$Intent.inputs={};for(const[s,i]of Object.entries(r))n.$Intent.inputs[s]=Array.isArray(i)?i.map(r=>t(r,n,e)):t(i,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const t of this.commands.keys())this.mapCommandArguments(t,e)}replaceCommand(e,t,n=e){if(!Array.isArray(t))return void(this.commands[e]=t);const r=t.length-1;this.commands.splice(e,1,...structuredClone(t)),this.mapArguments((s,i,a)=>{if(a<e+t.length)return s;if("number"!=typeof n&&("Result"===s.$kind&&s.Result===e||"NestedResult"===s.$kind&&s.NestedResult[0]===e)){if("NestedResult"in s&&0!==s.NestedResult[1])throw new Error(`Cannot replace command ${e} with a specific result type: NestedResult[${e}, ${s.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`);return Ut(cn,structuredClone(n))}switch(s.$kind){case"Result":s.Result===e&&"number"==typeof n&&(s.Result=n),s.Result>e&&(s.Result+=r);break;case"NestedResult":if(s.NestedResult[0]===e&&"number"==typeof n)return{$kind:"NestedResult",NestedResult:[n,s.NestedResult[1]]};s.NestedResult[0]>e&&(s.NestedResult[0]+=r)}return s})}replaceCommandWithTransaction(e,t,n){if("Result"!==n.$kind&&"NestedResult"!==n.$kind)throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(e,t),this.replaceCommand(e+t.commands.length,[],"Result"in n?{NestedResult:[n.Result+e,0]}:{NestedResult:[n.NestedResult[0]+e,n.NestedResult[1]]})}insertTransaction(e,t){const n=new Map,r=new Map;for(let e=0;e<t.inputs.length;e++){const r=t.inputs[e],s=Ii(r);let i=-1;if(void 0!==s&&(i=this.inputs.findIndex(e=>Ii(e)===s),-1!==i&&this.inputs[i].Object?.SharedObject&&r.Object?.SharedObject&&(this.inputs[i].Object.SharedObject.mutable=this.inputs[i].Object.SharedObject.mutable||r.Object.SharedObject.mutable)),-1!==i)n.set(e,i);else{const t=this.inputs.length;this.inputs.push(r),n.set(e,t)}}for(let n=0;n<t.commands.length;n++)r.set(n,e+n);const s=[];for(let e=0;e<t.commands.length;e++){const i=structuredClone(t.commands[e]);Ti(i,n,r),s.push(i)}this.commands.splice(e,0,...s);const i=s.length;i>0&&this.mapArguments((t,n,r)=>{if(r>=e&&r<e+s.length)return t;switch(t.$kind){case"Result":t.Result>=e&&(t.Result+=i);break;case"NestedResult":t.NestedResult[0]>=e&&(t.NestedResult[0]+=i)}return t})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Ai.getDigestFromBytes(e)}snapshot(){return Ut(wn,this)}shallowClone(){return new Ai({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(e){this.sender||(this.sender=e.sender??null),this.expiration||(this.expiration=e.expiration??null),this.gasData.budget||(this.gasData.budget=e.gasData.budget),this.gasData.owner||(this.gasData.owner=e.gasData.owner??null),this.gasData.payment||(this.gasData.payment=e.gasData.payment),this.gasData.price||(this.gasData.price=e.gasData.price);for(let t=0;t<this.inputs.length;t++){const n=this.inputs[t],r=e.inputs[t];switch(n.$kind){case"UnresolvedPure":if("Pure"!==r.$kind)throw new Error(`Expected input at index ${t} to resolve to a Pure argument, but got ${JSON.stringify(r)}`);this.inputs[t]=r;break;case"UnresolvedObject":if("Object"!==r.$kind)throw new Error(`Expected input at index ${t} to resolve to an Object argument, but got ${JSON.stringify(r)}`);if("ImmOrOwnedObject"===r.Object.$kind||"Receiving"===r.Object.$kind){const e=n.UnresolvedObject,s=r.Object.ImmOrOwnedObject??r.Object.Receiving;if(Qt(e.objectId)!==Qt(s.objectId)||null!=e.version&&e.version!==s.version||null!=e.digest&&e.digest!==s.digest||null!=e.mutable||null!=e.initialSharedVersion)throw new Error(`Input at index ${t} did not match unresolved object. ${JSON.stringify(e)} is not compatible with ${JSON.stringify(s)}`)}else{if("SharedObject"!==r.Object.$kind)throw new Error(`Input at index ${t} resolved to an unexpected Object kind: ${JSON.stringify(r.Object)}`);{const e=n.UnresolvedObject,s=r.Object.SharedObject;if(Qt(e.objectId)!==Qt(s.objectId)||null!=e.initialSharedVersion&&e.initialSharedVersion!==s.initialSharedVersion||null!=e.mutable&&e.mutable!==s.mutable||null!=e.version||null!=e.digest)throw new Error(`Input at index ${t} did not match unresolved object. ${JSON.stringify(e)} is not compatible with ${JSON.stringify(s)}`)}}this.inputs[t]=r}}}}var ji,Ci,Pi,Bi,Ni,$i,Ri,Mi,Di,Ui,Vi=e=>{throw TypeError(e)},Fi=(e,t,n)=>t.has(e)||Vi("Cannot "+n),Li=(e,t,n)=>(Fi(e,t,"read from private field"),n?n.call(e):t.get(e)),Ki=(e,t,n)=>t.has(e)?Vi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),qi=(e,t,n,r)=>(Fi(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),zi=(e,t,n)=>(Fi(e,t,"access private method"),n);const Zi={"Mvr-Source":`@mysten/sui@${l}`};class Wi{constructor({cache:e,url:t,pageSize:n=50,overrides:r}){Ki(this,Ni),Ki(this,ji),Ki(this,Ci),Ki(this,Pi),Ki(this,Bi),qi(this,ji,e),qi(this,Ci,t),qi(this,Pi,n),qi(this,Bi,{packages:r?.packages,types:r?.types}),function(e){if(e?.packages)for(const[t,n]of Object.entries(e.packages)){if(!zt(t))throw new Error(`Invalid package name: ${t}`);if(!Ht(Qt(n)))throw new Error(`Invalid package ID: ${n}`)}if(e?.types)for(const[t,n]of Object.entries(e.types)){if(Yt(t).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");if(!Ht(Yt(n).address))throw new Error(`Invalid type: ${n}`)}}(Li(this,Bi))}async resolvePackage({package:e}){if(!Ji(e))return{package:e};return{package:await Li(this,Ni,$i).load(e)}}async resolveType({type:e}){if(!Ji(e))return{type:e};const t=[...Gi(e)],n=await Li(this,Ni,Ri).loadMany(t),r={};for(let e=0;e<t.length;e++){const s=n[e];if(s instanceof Error)throw s;r[t[e]]=s}return{type:Hi(e,r)}}async resolve({types:e=[],packages:t=[]}){const n=new Set;for(const t of e??[])Gi(t,n);const r=[...n],[s,i]=await Promise.all([r.length>0?Li(this,Ni,Ri).loadMany(r):[],t.length>0?Li(this,Ni,$i).loadMany(t):[]]),a={...Li(this,Bi)?.types};for(const[e,t]of r.entries()){const n=s[e];if(n instanceof Error)throw n;a[t]=n}const o={};for(const t of e??[]){const e=Hi(t,a);o[t]={type:e}}const c={};for(const[e,n]of(t??[]).entries()){const t=Li(this,Bi)?.packages?.[n]??i[e];if(t instanceof Error)throw t;c[n]={package:t}}return{types:o,packages:c}}}function Gi(e,t=new Set){if("string"==typeof e&&!Ji(e))return t;const n=Yi(e)?e:Yt(e);Ji(n.address)&&t.add(`${n.address}::${n.module}::${n.name}`);for(const e of n.typeParams)Gi(e,t);return t}function Hi(e,t){const n=Yi(e)?e:Yt(e),r=`${n.address}::${n.module}::${n.name}`,s=t[r];return Xt({...n,address:s?s.split("::")[0]:n.address,typeParams:n.typeParams.map(e=>Hi(e,t))})}function Ji(e){return e.includes("/")||e.includes("@")||e.includes(".sui")}function Yi(e){return"object"==typeof e&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function Xi(e){const t=new Set;for(const n of e)if(Ji(n)){if(!Zt(n))throw new Error(`Invalid type with names: ${n}`);t.add(n)}return t}ji=new WeakMap,Ci=new WeakMap,Pi=new WeakMap,Bi=new WeakMap,Ni=new WeakSet,$i=function(){return Li(this,ji).readSync(["#mvrPackageDataLoader",Li(this,Ci)??""],()=>{const e=new _e(async e=>{if(!Li(this,Ci))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await zi(this,Ni,Mi).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve package: ${e}`))}),t=Li(this,Bi)?.packages;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Ri=function(){return Li(this,ji).readSync(["#mvrTypeDataLoader",Li(this,Ci)??""],()=>{const e=new _e(async e=>{if(!Li(this,Ci))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await zi(this,Ni,Di).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve type: ${e}`))}),t=Li(this,Bi)?.types;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Mi=async function(e){if(0===e.length)return{};const t=Te(e,Li(this,Pi)),n={};return await Promise.all(t.map(async e=>{const t=await zi(this,Ni,Ui).call(this,"/v1/resolution/bulk",{names:e});if(t?.resolution)for(const e of Object.keys(t?.resolution)){const r=t.resolution[e]?.package_id;r&&(n[e]=r)}})),n},Di=async function(e){if(0===e.length)return{};const t=Te(e,Li(this,Pi)),n={};return await Promise.all(t.map(async e=>{const t=await zi(this,Ni,Ui).call(this,"/v1/struct-definition/bulk",{types:e});if(t?.resolution)for(const e of Object.keys(t?.resolution)){const r=t.resolution[e]?.type_tag;r&&(n[e]=r)}})),n},Ui=async function(e,t){if(!Li(this,Ci))throw new Error("MVR Api URL is not set for the current client");const n=await fetch(`${Li(this,Ci)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...Zi},body:JSON.stringify(t)});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${e?.message}`)}return n.json()};const Qi=new WeakMap,ea=e=>{let t;if(e){const n=e.overrides??{packages:{},types:{}};Qi.has(n)||Qi.set(n,new ht),t=new Wi({cache:Qi.get(n),url:e.url,pageSize:e.pageSize,overrides:n})}return async(e,n,r)=>{const s=function(e){const t=new Set,n=new Set;for(const r of e.commands)switch(r.$kind){case"MakeMoveVec":r.MakeMoveVec.type&&Xi([r.MakeMoveVec.type]).forEach(e=>{n.add(e)});break;case"MoveCall":const e=r.MoveCall,s=e.package.split("::")[0];if(Ji(s)){if(!zt(s))throw new Error(`Invalid package name: ${s}`);t.add(s)}Xi(e.typeArguments??[]).forEach(e=>{n.add(e)})}return{packages:[...t],types:[...n]}}(e);if(0===s.types.length&&0===s.packages.length)return r();const i=await(t||function(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}(n).core.mvr).resolve({types:s.types,packages:s.packages});!function(e,t){for(const n of e.commands){if(n.MakeMoveVec?.type){if(!Ji(n.MakeMoveVec.type))continue;if(!t.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=t.types[n.MakeMoveVec.type].type}const e=n.MoveCall;if(!e)continue;const r=e.package.split("::"),s=r[0];if(Ji(s)&&!t.packages[s])throw new Error(`No address found for package: ${s}`);Ji(s)&&(r[0]=t.packages[s].package,e.package=r.join("::"));const i=e.typeArguments;if(i){for(let e=0;e<i.length;e++)if(Ji(i[e])){if(!t.types[i[e]])throw new Error(`No resolution found for type: ${i[e]}`);i[e]=t.types[i[e]].type}e.typeArguments=i}}}(e,i),await r()}};var ta,na,ra,sa,ia,aa,oa,ca,ua,da,la,ha,pa,fa,ga,ma,ya,ba,wa,va=e=>{throw TypeError(e)},ka=(e,t,n)=>t.has(e)||va("Cannot "+n),Ea=(e,t,n)=>(ka(e,t,"read from private field"),n?n.call(e):t.get(e)),Sa=(e,t,n)=>t.has(e)?va("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),xa=(e,t,n,r)=>(ka(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Oa=(e,t,n)=>(ka(e,t,"access private method"),n);function Ia(e,t=1/0){const n=[],r=t=>n[t]??(n[t]={$kind:"NestedResult",get NestedResult(){return["function"==typeof e?e():e,t]}});return new Proxy({$kind:"Result",get Result(){return"function"==typeof e?e():e}},{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);if(n===Symbol.iterator)return function*(){let e=0;for(;e<t;)yield r(e),e++};if("symbol"==typeof n)return;const s=parseInt(n,10);return Number.isNaN(s)||s<0?void 0:r(s)}})}const Ta=Symbol.for("@mysten/transaction");function _a(e){return!!e&&"object"==typeof e&&!0===e[Ta]}const Aa={buildPlugins:new Map,serializationPlugins:new Map},ja=Symbol.for("@mysten/transaction/registry");function Ca(){try{const e=globalThis;return e[ja]||(e[ja]=Aa),e[ja]}catch{return Aa}}const Pa=class e{constructor(){Sa(this,da),Sa(this,ta),Sa(this,na),Sa(this,ra,new Map),Sa(this,sa,[]),Sa(this,ia,[]),Sa(this,aa,new Set),Sa(this,oa,new Set),Sa(this,ca,new Map),Sa(this,ua),this.object=function(e){function t(t){return e(t)}return t.system=e=>{const n=e?.mutable;return t(void 0!==n?Qr.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},t.clock=()=>t(Qr.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),t.random=()=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),t.denyList=e=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:e?.mutable}}),t.option=({type:e,value:t})=>n=>n.moveCall({typeArguments:[e],target:"0x1::option::"+(null===t?"none":"some"),arguments:null===t?[]:[n.object(t)]}),t}(e=>{if("function"==typeof e)return this.object(this.add(e));if("object"==typeof e&&Et(cn,e))return e;const t=Ii(e),n=Ea(this,ua).inputs.find(e=>t===Ii(e));return n?.Object?.SharedObject&&"object"==typeof e&&e.Object?.SharedObject&&(n.Object.SharedObject.mutable=n.Object.SharedObject.mutable||e.Object.SharedObject.mutable),n?{$kind:"Input",Input:Ea(this,ua).inputs.indexOf(n),type:"object"}:Oa(this,da,pa).call(this,"object","string"==typeof e?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:Qt(e)}}:e)});const e=Ca();xa(this,ua,new Ai),xa(this,na,[...e.buildPlugins.values()]),xa(this,ta,[...e.serializationPlugins.values()])}static fromKind(t){const n=new e;return xa(n,ua,Ai.fromKindBytes("string"==typeof t?Ee(t):t)),xa(n,sa,Ea(n,ua).inputs.slice()),xa(n,ia,Ea(n,ua).commands.slice()),xa(n,aa,new Set(Ea(n,ia).map((e,t)=>t))),n}static from(t){const n=new e;return _a(t)?xa(n,ua,Ai.restore(t.getData())):"string"==typeof t&&t.startsWith("{")?xa(n,ua,Ai.restore(JSON.parse(t))):xa(n,ua,Ai.fromBytes("string"==typeof t?Ee(t):t)),xa(n,sa,Ea(n,ua).inputs.slice()),xa(n,ia,Ea(n,ua).commands.slice()),xa(n,aa,new Set(Ea(n,ia).map((e,t)=>t))),n}static registerGlobalSerializationPlugin(e,t){Ca().serializationPlugins.set(e,t??e)}static unregisterGlobalSerializationPlugin(e){Ca().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,t){Ca().buildPlugins.set(e,t??e)}static unregisterGlobalBuildPlugin(e){Ca().buildPlugins.delete(e)}addSerializationPlugin(e){Ea(this,ta).push(e)}addBuildPlugin(e){Ea(this,na).push(e)}addIntentResolver(e,t){if(Ea(this,ra).has(e)&&Ea(this,ra).get(e)!==t)throw new Error(`Intent resolver for ${e} already exists`);Ea(this,ra).set(e,t)}setSender(e){Ea(this,ua).sender=e}setSenderIfNotSet(e){Ea(this,ua).sender||(Ea(this,ua).sender=e)}setExpiration(e){Ea(this,ua).expiration=e?Ut(bn,e):null}setGasPrice(e){Ea(this,ua).gasConfig.price=String(e)}setGasBudget(e){Ea(this,ua).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){null==Ea(this,ua).gasData.budget&&(Ea(this,ua).gasConfig.budget=String(e))}setGasOwner(e){Ea(this,ua).gasConfig.owner=e}setGasPayment(e){Ea(this,ua).gasConfig.payment=e.map(e=>Ut(on,e))}get blockData(){return Vr(Ea(this,ua).snapshot())}getData(){return Ea(this,ua).snapshot()}get[Ta](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:Oi(e=>Je(e)?Oa(this,da,pa).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):Oa(this,da,pa).call(this,"pure",Et(yn,e)?Ut(yn,e):e instanceof Uint8Array?Qr.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(Qr.ObjectRef(...e))}receivingRef(...e){return this.object(Qr.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(Qr.SharedObjectRef(...e))}add(e){if("function"==typeof e){if(Ea(this,ca).has(e))return Ea(this,ca).get(e);const t=Oa(this,da,la).call(this),n=e(t);if(!n||"object"!=typeof n||!("then"in n))return xa(this,aa,Ea(t,aa)),Ea(this,ca).set(e,n),n;const r=Oa(this,da,ha).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Ea(this,ua).commands.length,result:null}}});Ea(this,oa).add(Promise.resolve(n).then(e=>{r.$Intent.data.result=e}));const s=Ia(()=>r.$Intent.data.resultIndex);return Ea(this,ca).set(e,s),s}return Oa(this,da,ha).call(this,e),Ia(Ea(this,ua).commands.length-1)}splitCoins(e,t){const n=vn.SplitCoins("string"==typeof e?this.object(e):Oa(this,da,ga).call(this,e),t.map(e=>"number"==typeof e||"bigint"==typeof e||"string"==typeof e?this.pure.u64(e):Oa(this,da,fa).call(this,e)));return Oa(this,da,ha).call(this,n),Ia(Ea(this,ua).commands.length-1,t.length)}mergeCoins(e,t){return this.add(vn.MergeCoins(this.object(e),t.map(e=>this.object(e))))}publish({modules:e,dependencies:t}){return this.add(vn.Publish({modules:e,dependencies:t}))}upgrade({modules:e,dependencies:t,package:n,ticket:r}){return this.add(vn.Upgrade({modules:e,dependencies:t,package:n,ticket:this.object(r)}))}moveCall({arguments:e,...t}){return this.add(vn.MoveCall({...t,arguments:e?.map(e=>Oa(this,da,fa).call(this,e))}))}transferObjects(e,t){return this.add(vn.TransferObjects(e.map(e=>this.object(e)),"string"==typeof t?this.pure.address(t):Oa(this,da,fa).call(this,t)))}makeMoveVec({type:e,elements:t}){return this.add(vn.MakeMoveVec({type:e,elements:t.map(e=>this.object(e))}))}serialize(){return JSON.stringify(Vr(Ea(this,ua).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const t=this.isFullyResolved();return JSON.stringify(Ut(Xr,t?{...Ea(this,ua).snapshot(),digest:Ea(this,ua).getDigest()}:Ea(this,ua).snapshot()),(e,t)=>"bigint"==typeof t?t.toString():t,2)}async sign(e){const{signer:t,...n}=e,r=await this.build(n);return t.signTransaction(r)}isFullyResolved(){return!!Ea(this,ua).sender&&(!(Ea(this,oa).size>0)&&(!Ea(this,ua).commands.some(e=>e.$Intent)&&!ki(Ea(this,ua),{})))}async build(e={}){return await this.prepareForSerialization(e),await Oa(this,da,ma).call(this,e),Ea(this,ua).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await Oa(this,da,ma).call(this,e),Ea(this,ua).getDigest()}async prepareForSerialization(e){await Oa(this,da,ba).call(this),Oa(this,da,wa).call(this);const t=new Set;for(const e of Ea(this,ua).commands)e.$Intent&&t.add(e.$Intent.name);const n=[...Ea(this,ta)];for(const r of t)if(!e.supportedIntents?.includes(r)){if(!Ea(this,ra).has(r))throw new Error(`Missing intent resolver for ${r}`);n.push(Ea(this,ra).get(r))}n.push(ea()),await Oa(this,da,ya).call(this,n,e)}};ta=new WeakMap,na=new WeakMap,ra=new WeakMap,sa=new WeakMap,ia=new WeakMap,aa=new WeakMap,oa=new WeakMap,ca=new WeakMap,ua=new WeakMap,da=new WeakSet,la=function(){const e=new Pa;return xa(e,ua,Ea(this,ua)),xa(e,ta,Ea(this,ta)),xa(e,na,Ea(this,na)),xa(e,ra,Ea(this,ra)),xa(e,oa,Ea(this,oa)),xa(e,aa,new Set(Ea(this,aa))),xa(e,ca,Ea(this,ca)),Ea(this,sa).push(Ea(e,sa)),Ea(this,ia).push(Ea(e,ia)),e},ha=function(e){const t=Ea(this,ua).commands.length;return Ea(this,ia).push(e),Ea(this,aa).add(t),Ea(this,ua).commands.push(e),Ea(this,ua).mapCommandArguments(t,e=>{if("Result"===e.$kind&&!Ea(this,aa).has(e.Result))throw new Error(`Result { Result: ${e.Result} } is not available to use in the current transaction`);if("NestedResult"===e.$kind&&!Ea(this,aa).has(e.NestedResult[0]))throw new Error(`Result { NestedResult: [${e.NestedResult[0]}, ${e.NestedResult[1]}] } is not available to use in the current transaction`);if("Input"===e.$kind&&e.Input>=Ea(this,ua).inputs.length)throw new Error(`Input { Input: ${e.Input} } references an input that does not exist in the current transaction`);return e}),e},pa=function(e,t){return Ea(this,sa).push(t),Ea(this,ua).addInput(e,t)},fa=function(e){return Je(e)?this.pure(e):Oa(this,da,ga).call(this,e)},ga=function(e){if("function"==typeof e){const t=this.add(e);return"function"==typeof t?Oa(this,da,ga).call(this,t):Ut(cn,t)}return Ut(cn,e)},ma=async function(e){if(!e.onlyTransactionKind&&!Ea(this,ua).sender)throw new Error("Missing transaction sender");await Oa(this,da,ya).call(this,[...Ea(this,na),Ei],e)},ya=async function(e,t){try{const n=r=>{if(r>=e.length)return()=>{};const s=e[r];return async()=>{const e=n(r+1);let i=!1,a=!1;if(await s(Ea(this,ua),t,async()=>{if(i)throw new Error(`next() was call multiple times in TransactionPlugin ${r}`);i=!0,await e(),a=!0}),!i)throw new Error(`next() was not called in TransactionPlugin ${r}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${r}`)}};await n(0)()}finally{xa(this,sa,Ea(this,ua).inputs.slice()),xa(this,ia,Ea(this,ua).commands.slice())}},ba=async function(){for(;Ea(this,oa).size>0;){const e=Promise.all(Ea(this,oa));Ea(this,oa).clear(),Ea(this,oa).add(e),await e,Ea(this,oa).delete(e)}},wa=function(){const e=Ea(this,ua).commands,t=Ea(this,ua).inputs,n=Ea(this,ia).flat(1/0),r=Ea(this,sa).flat(1/0);if(n.length!==e.length)throw new Error("Unexpected number of commands found in transaction data");if(r.length!==t.length)throw new Error("Unexpected number of inputs found in transaction data");const s=n.filter(e=>"AsyncTransactionThunk"!==e.$Intent?.name);function i(t){const n=e[t];if("AsyncTransactionThunk"===n.$Intent?.name){const e=n.$Intent.data.result;if(null==e)throw new Error("AsyncTransactionThunk has not been resolved");return i(e.Result)}const r=s.indexOf(n);if(-1===r)throw new Error("Unable to find original index for command");return r}Ea(this,ua).commands=s,Ea(this,ua).inputs=r,xa(this,ia,s),xa(this,sa,r),xa(this,aa,new Set(s.map((e,t)=>t))),Ea(this,ua).mapArguments(e=>{if("Input"===e.$kind){const n=r.indexOf(t[e.Input]);if(-1===n)throw new Error("Input has not been resolved");return{...e,Input:n}}if("Result"===e.$kind){const t=i(e.Result);return{...e,Result:t}}if("NestedResult"===e.$kind){const t=i(e.NestedResult[0]);return{...e,NestedResult:[t,e.NestedResult[1]]}}return e});for(const[t,n]of e.entries())if("AsyncTransactionThunk"===n.$Intent?.name)try{n.$Intent.data.resultIndex=i(t)}catch{}};let Ba=Pa;const Na={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class $a extends pt{constructor(e){super(e),this.core=this,this.mvr=new Wi({cache:this.cache.scope("core.mvr"),url:e.mvr?.url??Na[this.network],pageSize:e.mvr?.pageSize,overrides:e.mvr?.overrides})}async getObject(e){const{objectId:t}=e,{objects:[n]}=await this.getObjects({objectIds:[t],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const t=Sn.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=fi(e.parentId,t,e.name.bcs),{objects:[r]}=await this.getObjects({objectIds:[n],signal:e.signal});if(r instanceof Error)throw r;const s=Yt(r.type),i=await r.content;return{dynamicField:{id:r.id,digest:r.digest,version:r.version,type:r.type,previousTransaction:r.previousTransaction,name:{type:"string"==typeof s.typeParams[0]?s.typeParams[0]:Xt(s.typeParams[0]),bcs:e.name.bcs},value:{type:"string"==typeof s.typeParams[1]?s.typeParams[1]:Xt(s.typeParams[1]),bcs:i.slice(Gt+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:t=6e4,...n}){const r=e?AbortSignal.any([AbortSignal.timeout(t),e]):AbortSignal.timeout(t),s=new Promise((e,t)=>{r.addEventListener("abort",()=>t(r.reason))});for(s.catch(()=>{});;){r.throwIfAborted();try{return await this.getTransaction({...n,signal:r})}catch{await Promise.race([new Promise(e=>setTimeout(e,2e3)),s])}}}}class Ra extends Error{}class Ma extends Ra{constructor(e,t){super(t),this.code=e}static fromResponse(e,t){switch(e.code){case"notExists":return new Ma(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Ma(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Ma(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Ma(e.code,`Display error: ${e.error}`);default:return new Ma(e.code,"Unknown error while loading object"+(t?` ${t}`:""))}}}function Da(e){return{...Ai.fromBytes(e).snapshot(),bcs:e}}function Ua(e){const t=Sr.TransactionEffects.parse(e);switch(t.$kind){case"V1":return function(){throw new Error("V1 effects are not supported yet")}(t.V1);case"V2":return function({bytes:e,effects:t}){const n=t.changedObjects.map(([e,n])=>({id:e,inputState:"Exist"===n.inputState.$kind?"Exists":"DoesNotExist",inputVersion:n.inputState.Exist?.[0][0]??null,inputDigest:n.inputState.Exist?.[0][1]??null,inputOwner:n.inputState.Exist?.[1]??null,outputState:"NotExist"===n.outputState.$kind?"DoesNotExist":n.outputState.$kind,outputVersion:"PackageWrite"===n.outputState.$kind?n.outputState.PackageWrite?.[0]:n.outputState.ObjectWrite?t.lamportVersion:null,outputDigest:"PackageWrite"===n.outputState.$kind?n.outputState.PackageWrite?.[1]:n.outputState.ObjectWrite?.[0]??null,outputOwner:n.outputState.ObjectWrite?n.outputState.ObjectWrite[1]:null,idOperation:n.idOperation.$kind}));return{bcs:e,digest:t.transactionDigest,version:2,status:"Success"===t.status.$kind?{success:!0,error:null}:{success:!1,error:t.status.Failed.error.$kind},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:null===t.gasObjectIndex?null:n[t.gasObjectIndex]??null,eventsDigest:t.eventsDigest,dependencies:t.dependencies,lamportVersion:t.lamportVersion,changedObjects:n,unchangedConsensusObjects:t.unchangedSharedObjects.map(([e,t])=>({kind:"MutateDeleted"===t.$kind?"MutateConsensusStreamEnded":"ReadDeleted"===t.$kind?"ReadConsensusStreamEnded":t.$kind,objectId:e,version:"ReadOnlyRoot"===t.$kind?t.ReadOnlyRoot[0]:t[t.$kind],digest:"ReadOnlyRoot"===t.$kind?t.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:t.auxDataDigest}}({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}var Va,Fa=e=>{throw TypeError(e)},La=(e,t,n)=>t.has(e)||Fa("Cannot "+n),Ka=(e,t,n)=>(La(e,t,"read from private field"),n?n.call(e):t.get(e));class qa extends $a{constructor({jsonRpcClient:e,mvr:t}){var n,r,s;super({network:e.network,base:e,mvr:t}),n=this,(r=Va).has(n)?Fa("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(n):r.set(n,s),((e,t,n,r)=>{La(e,t,"write to private field"),r?r.call(e,n):t.set(e,n)})(this,Va,e)}async getObjects(e){const t=Te(e.objectIds,50),n=[];for(const r of t){const t=await Ka(this,Va).multiGetObjects({ids:r,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:e.signal});for(const[e,s]of t.entries())s.error?n.push(Ma.fromResponse(s.error,r[e])):n.push(za(s.data))}return{objects:n}}async getOwnedObjects(e){const t=await Ka(this,Va).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:t.data.map(e=>{if(e.error)throw Ma.fromResponse(e.error);return za(e.data)}),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getCoins(e){const t=await Ka(this,Va).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:t.data.map(t=>({id:t.coinObjectId,version:t.version,digest:t.digest,balance:t.balance,type:`0x2::coin::Coin<${t.coinType}>`,content:Promise.resolve(Ja.serialize({id:t.coinObjectId,balance:{value:t.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address},previousTransaction:t.previousTransaction})),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getBalance(e){const t=await Ka(this,Va).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:t.coinType,balance:t.totalBalance}}}async getAllBalances(e){return{balances:(await Ka(this,Va).getAllBalances({owner:e.address,signal:e.signal})).map(e=>({coinType:e.coinType,balance:e.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){return{transaction:Ga(await Ka(this,Va).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal}))}}async executeTransaction(e){return{transaction:Ga(await Ka(this,Va).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal}))}}async dryRunTransaction(e){const t=Ba.from(e.transaction),n=await Ka(this,Va).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:r,objectTypes:s}=function({bytes:e,effects:t,objectChanges:n}){const r=[],s=[],i={};return n?.forEach(e=>{switch(e.type){case"published":r.push({id:e.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:e.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:e.sender},outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Za(e.recipient),idOperation:"None"}),i[e.objectId]=e.objectType;break;case"mutated":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.previousVersion,inputDigest:null,inputOwner:Za(e.owner),outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Za(e.owner),idOperation:"None"}),i[e.objectId]=e.objectType;break;case"deleted":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:t.deleted?.find(t=>t.objectId===e.objectId)?.digest??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[e.objectId]=e.objectType;break;case"wrapped":r.push({id:e.objectId,inputState:"Exists",inputVersion:e.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:e.sender},outputState:"ObjectWrite",outputVersion:e.version,outputDigest:t.wrapped?.find(t=>t.objectId===e.objectId)?.digest??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:e.sender},idOperation:"None"}),i[e.objectId]=e.objectType;break;case"created":r.push({id:e.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Za(e.owner),idOperation:"Created"}),i[e.objectId]=e.objectType}}),{objectTypes:i,effects:{bcs:e??null,digest:t.transactionDigest,version:2,status:"success"===t.status.status?{success:!0,error:null}:{success:!1,error:t.status.error},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:{id:t.gasObject?.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:t.gasObject.reference.version,outputDigest:t.gasObject.reference.digest,outputOwner:Za(t.gasObject.owner),idOperation:"None"},eventsDigest:t.eventsDigest??null,dependencies:t.dependencies??[],lamportVersion:t.gasObject.reference.version,changedObjects:r,unchangedConsensusObjects:s,auxiliaryDataDigest:null}}}({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await t.getDigest(),epoch:null,effects:r,objectTypes:Promise.resolve(s),signatures:[],transaction:Da(e.transaction),balanceChanges:n.balanceChanges.map(e=>({coinType:e.coinType,address:Wa(e.owner),amount:e.amount}))}}}async getReferenceGasPrice(e){const t=await Ka(this,Va).getReferenceGasPrice({signal:e?.signal});return{referenceGasPrice:String(t)}}async getDynamicFields(e){const t=await Ka(this,Va).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:t.data.map(e=>({id:e.objectId,type:e.objectType,name:{type:e.name.type,bcs:Ee(e.bcsName)}})),hasNextPage:t.hasNextPage,cursor:t.nextCursor}}async verifyZkLoginSignature(e){const t=await Ka(this,Va).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:t.success,errors:t.errors}}async defaultNameServiceName(e){return{data:{name:(await Ka(this,Va).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return bi(Ka(this,Va))}async getMoveFunction(e){const t=await Ka(this,Va).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:Qt(e.packageId),moduleName:e.moduleName,name:e.name,visibility:Qa(t.visibility),isEntry:t.isEntry,typeParameters:t.typeParameters.map(e=>{return{isPhantom:!1,constraints:(t=e,t.abilities.map(e=>{switch(e){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}}))};var t}),parameters:t.parameters.map(e=>Ya(e)),returns:t.return.map(e=>Ya(e))}}}}function za(e){return{id:e.objectId,version:e.version,digest:e.digest,type:e.type,content:Promise.resolve("moveObject"===e.bcs?.dataType?Ee(e.bcs.bcsBytes):new Uint8Array),owner:Za(e.owner),previousTransaction:e.previousTransaction??null}}function Za(e){if("Immutable"===e)return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in e)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:e.ConsensusAddressOwner.owner,startVersion:e.ConsensusAddressOwner.start_version}};if("AddressOwner"in e)return{$kind:"AddressOwner",AddressOwner:e.AddressOwner};if("ObjectOwner"in e)return{$kind:"ObjectOwner",ObjectOwner:e.ObjectOwner};if("Shared"in e)return{$kind:"Shared",Shared:{initialSharedVersion:e.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function Wa(e){if("Immutable"===e)return null;if("ConsensusAddressOwner"in e)return e.ConsensusAddressOwner.owner;if("AddressOwner"in e)return e.AddressOwner;if("ObjectOwner"in e)return e.ObjectOwner;if("Shared"in e)return null;throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function Ga(e){const t=Sr.SenderSignedData.parse(Ee(e.rawTransaction))[0],n={};e.objectChanges?.forEach(e=>{"published"!==e.type&&(n[e.objectId]=e.objectType)});const r=Sr.TransactionData.serialize(t.intentMessage.value).toBytes(),s=Ai.restore({version:2,sender:t.intentMessage.value.V1.sender,expiration:t.intentMessage.value.V1.expiration,gasData:t.intentMessage.value.V1.gasData,inputs:t.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:t.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:e.digest,epoch:e.effects?.executedEpoch??null,effects:Ua(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(n),transaction:{...s,bcs:r},signatures:t.txSignatures,balanceChanges:e.balanceChanges?.map(e=>({coinType:e.coinType,address:Wa(e.owner),amount:e.amount}))??[]}}Va=new WeakMap;const Ha=Sr.struct("Balance",{value:Sr.u64()}),Ja=Sr.struct("Coin",{id:Sr.Address,balance:Ha});function Ya(e){if("string"!=typeof e){if("Reference"in e)return{reference:"immutable",body:Xa(e.Reference)};if("MutableReference"in e)return{reference:"mutable",body:Xa(e.MutableReference)}}return{reference:null,body:Xa(e)}}function Xa(e){switch(e){case"Address":return{$kind:"address"};case"Bool":return{$kind:"bool"};case"U8":return{$kind:"u8"};case"U16":return{$kind:"u16"};case"U32":return{$kind:"u32"};case"U64":return{$kind:"u64"};case"U128":return{$kind:"u128"};case"U256":return{$kind:"u256"}}if("string"==typeof e)throw new Error(`Unknown type: ${e}`);if("Vector"in e)return{$kind:"vector",vector:Xa(e.Vector)};if("Struct"in e)return{$kind:"datatype",datatype:{typeName:`${Qt(e.Struct.address)}::${e.Struct.module}::${e.Struct.name}`,typeParameters:e.Struct.typeArguments.map(e=>Xa(e))}};if("TypeParameter"in e)return{$kind:"typeParameter",index:e.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}function Qa(e){switch(e){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const eo=Symbol.for("@mysten/SuiClient");class to extends pt{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new q({url:e.url}),this.core=new qa({jsonRpcClient:this,mvr:e.mvr})}get[eo](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:t,cursor:n,limit:r,signal:s}){if(!t||!Ht(Qt(t)))throw new Error("Invalid Sui address");return e&&Ji(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[t,e,n,r],signal:s})}async getAllCoins(e){if(!e.owner||!Ht(Qt(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:t,signal:n}){if(!e||!Ht(Qt(e)))throw new Error("Invalid Sui address");return t&&Ji(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getBalance",params:[e,t],signal:n})}async getAllBalances(e){if(!e.owner||!Ht(Qt(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:t}){return e&&Ji(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:t})}async getTotalSupply({coinType:e,signal:t}){return e&&Ji(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:t})}async call(e,t,{signal:n}={}){return await this.transport.request({method:e,params:t,signal:n})}async getMoveFunctionArgTypes({package:e,module:t,function:n,signal:r}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,t,n],signal:r})}async getNormalizedMoveModulesByPackage({package:e,signal:t}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:t})}async getNormalizedMoveModule({package:e,module:t,signal:n}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,t],signal:n})}async getNormalizedMoveFunction({package:e,module:t,function:n,signal:r}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,t,n],signal:r})}async getNormalizedMoveStruct({package:e,module:t,struct:n,signal:r}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,t,n],signal:r})}async getOwnedObjects(e){if(!e.owner||!Ht(Qt(e.owner)))throw new Error("Invalid Sui address");const t=e.filter?{...e.filter}:void 0;return t&&"MoveModule"in t&&zt(t.MoveModule.package)?t.MoveModule={module:t.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveModule.package})).package}:t&&"StructType"in t&&Ji(t.StructType)&&(t.StructType=(await this.core.mvr.resolveType({type:t.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:t,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!Jt(en(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){e.ids.forEach(e=>{if(!e||!Jt(en(e)))throw new Error(`Invalid Sui Object id ${e}`)});if(e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:t,cursor:n,limit:r,order:s,signal:i}){return e&&"MoveFunction"in e&&zt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:t},n,r,"descending"===(s||"descending")],signal:i})}async getTransactionBlock(e){if(!Wt(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){e.digests.forEach(e=>{if(!Wt(e))throw new Error(`Invalid Transaction digest ${e}`)});if(e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:t,options:n,requestType:r,signal:s}){const i=await this.transport.request({method:"sui_executeTransactionBlock",params:["string"==typeof e?e:xe(e),Array.isArray(t)?t:[t],n],signal:s});if("WaitForLocalExecution"===r)try{await this.waitForTransaction({digest:i.digest})}catch{}return i}async signAndExecuteTransaction({transaction:e,signer:t,...n}){let r;e instanceof Uint8Array?r=e:(e.setSenderIfNotSet(t.toSuiAddress()),r=await e.build({client:this}));const{signature:s,bytes:i}=await t.signTransaction(r);return this.executeTransactionBlock({transactionBlock:i,signature:s,...n})}async getTotalTransactionBlocks({signal:e}={}){const t=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(t)}async getReferenceGasPrice({signal:e}={}){const t=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(t)}async getStakes(e){if(!e.owner||!Ht(Qt(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(e=>{if(!e||!Jt(en(e)))throw new Error(`Invalid Sui Stake id ${e}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:t,limit:n,order:r,signal:s}){return e&&"MoveEventType"in e&&Ji(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&zt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&zt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,t,n,"descending"===(r||"descending")],signal:s})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){let t;if(_a(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),t=xe(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if("string"==typeof e.transactionBlock)t=e.transactionBlock;else{if(!(e.transactionBlock instanceof Uint8Array))throw new Error("Unknown transaction block format.");t=xe(e.transactionBlock)}return e.signal?.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,t,e.gasPrice?.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:["string"==typeof e.transactionBlock?e.transactionBlock:xe(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!Jt(en(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const t=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(t)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e?.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e?.epoch],signal:e?.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e?.cursor,e?.limit,e?.descendingOrder],signal:e?.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e?.descendingOrder],signal:e?.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e?.cursor,e?.limit,e?.descendingOrder],signal:e?.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const t=await this.getCheckpoint({id:"0",signal:e});return Ie(ke(t.digest).slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...t}){const{nextCursor:n,hasNextPage:r,data:s}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[t.address,t.cursor,t.limit],signal:t.signal});return{hasNextPage:r,nextCursor:n,data:s.map(t=>function(e,t="at"){const n=e.toLowerCase();let r;if(n.includes("@")){if(!Ft.test(n))throw new Error(`Invalid SuiNS name ${e}`);const[t,s]=n.split("@");r=[...t?t.split("."):[],s]}else{if(!Lt.test(n))throw new Error(`Invalid SuiNS name ${e}`);r=n.split(".").slice(0,-1)}return"dot"===t?`${r.join(".")}.sui`:`${r.slice(0,-1).join(".")}@${r[r.length-1]}`}(t,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e?.version],signal:e?.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:t=6e4,pollInterval:n=2e3,...r}){const s=AbortSignal.timeout(t),i=new Promise((e,t)=>{s.addEventListener("abort",()=>t(s.reason))});for(i.catch(()=>{});!s.aborted;){e?.throwIfAborted();try{return await this.getTransactionBlock(r)}catch{await Promise.race([new Promise(e=>setTimeout(e,n)),i])}}throw s.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class no extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function ro(e){}function so(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ro,onError:n=ro,onRetry:r=ro,onComment:s}=e;let i,a="",o=!0,c="",u="";function d(e){if(""===e)return c.length>0&&t({id:i,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),i=void 0,c="",void(u="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1!==n){const t=e.slice(0,n),r=" "===e[n+1]?2:1;return void l(t,e.slice(n+r),e)}l(e,"",e)}function l(e,t,s){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new no(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:n(new no(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:s}))}}return{feed:function(e){const t=o?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const s=e.indexOf("\r",r),i=e.indexOf("\n",r);let a=-1;if(-1!==s&&-1!==i?a=Math.min(s,i):-1!==s?a=s===e.length-1?-1:s:-1!==i&&(a=i),-1===a){n=e.slice(r);break}{const n=e.slice(r,a);t.push(n),r=a+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${a}${t}`);for(const e of n)d(e);a=r,o=!1},reset:function(e={}){a&&e.consume&&d(a),o=!0,i=void 0,c="",u="",a=""}}}class io extends Event{constructor(e,t){var n,r;super(e),this.code=null!=(n=null==t?void 0:t.code)?n:void 0,this.message=null!=(r=null==t?void 0:t.message)?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return n(oo(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(oo(this),t)}}function ao(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(ao).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${ao(e.cause)}`:e.message:`${e}`}function oo(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var co,uo,lo,ho,po,fo,go,mo,yo,bo,wo,vo,ko,Eo,So,xo,Oo,Io,To,_o,Ao,jo,Co,Po,Bo,No=e=>{throw TypeError(e)},$o=(e,t,n)=>t.has(e)||No("Cannot "+n),Ro=(e,t,n)=>($o(e,t,"read from private field"),n?n.call(e):t.get(e)),Mo=(e,t,n)=>t.has(e)?No("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Do=(e,t,n,r)=>($o(e,t,"write to private field"),t.set(e,n),n),Uo=(e,t,n)=>($o(e,t,"access private method"),n);class Vo extends EventTarget{constructor(e,t){var n,r;super(),Mo(this,Eo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Mo(this,co),Mo(this,uo),Mo(this,lo),Mo(this,ho),Mo(this,po),Mo(this,fo),Mo(this,go),Mo(this,mo,null),Mo(this,yo),Mo(this,bo),Mo(this,wo,null),Mo(this,vo,null),Mo(this,ko,null),Mo(this,xo,async e=>{var t;Ro(this,bo).reset();const{body:n,redirected:r,status:s,headers:i}=e;if(204===s)return Uo(this,Eo,Ao).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(Do(this,lo,r?new URL(e.url):void 0),200!==s)return void Uo(this,Eo,Ao).call(this,`Non-200 status code (${s})`,s);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void Uo(this,Eo,Ao).call(this,'Invalid content type, expected "text/event-stream"',s);if(Ro(this,co)===this.CLOSED)return;Do(this,co,this.OPEN);const a=new Event("open");if(null==(t=Ro(this,ko))||t.call(this,a),this.dispatchEvent(a),"object"!=typeof n||!n||!("getReader"in n))return Uo(this,Eo,Ao).call(this,"Invalid response body, expected a web ReadableStream",s),void this.close();const o=new TextDecoder,c=n.getReader();let u=!0;do{const{done:e,value:t}=await c.read();t&&Ro(this,bo).feed(o.decode(t,{stream:!e})),e&&(u=!1,Ro(this,bo).reset(),Uo(this,Eo,jo).call(this))}while(u)}),Mo(this,Oo,e=>{Do(this,yo,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&Uo(this,Eo,jo).call(this,ao(e))}),Mo(this,To,e=>{"string"==typeof e.id&&Do(this,mo,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Ro(this,lo)?Ro(this,lo).origin:Ro(this,uo).origin,lastEventId:e.id||""});Ro(this,vo)&&(!e.event||"message"===e.event)&&Ro(this,vo).call(this,t),this.dispatchEvent(t)}),Mo(this,_o,e=>{Do(this,fo,e)}),Mo(this,Co,()=>{Do(this,go,void 0),Ro(this,co)===this.CONNECTING&&Uo(this,Eo,So).call(this)});try{if(e instanceof URL)Do(this,uo,e);else{if("string"!=typeof e)throw new Error("Invalid URL");Do(this,uo,new URL(e,function(){const e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()))}}catch{throw function(e){const t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):new SyntaxError(e)}("An invalid or illegal string was specified")}Do(this,bo,so({onEvent:Ro(this,To),onRetry:Ro(this,_o)})),Do(this,co,this.CONNECTING),Do(this,fo,3e3),Do(this,po,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),Do(this,ho,null!=(r=null==t?void 0:t.withCredentials)&&r),Uo(this,Eo,So).call(this)}get readyState(){return Ro(this,co)}get url(){return Ro(this,uo).href}get withCredentials(){return Ro(this,ho)}get onerror(){return Ro(this,wo)}set onerror(e){Do(this,wo,e)}get onmessage(){return Ro(this,vo)}set onmessage(e){Do(this,vo,e)}get onopen(){return Ro(this,ko)}set onopen(e){Do(this,ko,e)}addEventListener(e,t,n){const r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){const r=t;super.removeEventListener(e,r,n)}close(){Ro(this,go)&&clearTimeout(Ro(this,go)),Ro(this,co)!==this.CLOSED&&(Ro(this,yo)&&Ro(this,yo).abort(),Do(this,co,this.CLOSED),Do(this,yo,void 0))}}function Fo(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Lo(e){const t={};for(const n of Object.keys(e)){const r=Fo(n),s=e[n];t[r]=s}return t}co=new WeakMap,uo=new WeakMap,lo=new WeakMap,ho=new WeakMap,po=new WeakMap,fo=new WeakMap,go=new WeakMap,mo=new WeakMap,yo=new WeakMap,bo=new WeakMap,wo=new WeakMap,vo=new WeakMap,ko=new WeakMap,Eo=new WeakSet,So=function(){Do(this,co,this.CONNECTING),Do(this,yo,new AbortController),Ro(this,po)(Ro(this,uo),Uo(this,Eo,Io).call(this)).then(Ro(this,xo)).catch(Ro(this,Oo))},xo=new WeakMap,Oo=new WeakMap,Io=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ro(this,mo)?{"Last-Event-ID":Ro(this,mo)}:void 0},cache:"no-store",signal:null==(e=Ro(this,yo))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},To=new WeakMap,_o=new WeakMap,Ao=function(e,t){var n;Ro(this,co)!==this.CLOSED&&Do(this,co,this.CLOSED);const r=new io("error",{code:t,message:e});null==(n=Ro(this,wo))||n.call(this,r),this.dispatchEvent(r)},jo=function(e,t){var n;if(Ro(this,co)===this.CLOSED)return;Do(this,co,this.CONNECTING);const r=new io("error",{code:t,message:e});null==(n=Ro(this,wo))||n.call(this,r),this.dispatchEvent(r),Do(this,go,setTimeout(Ro(this,Co),Ro(this,fo)))},Co=new WeakMap,Vo.CONNECTING=0,Vo.OPEN=1,Vo.CLOSED=2,function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Po||(Po={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Bo||(Bo={}));const Ko=Po.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qo=e=>{switch(typeof e){case"undefined":return Ko.undefined;case"string":return Ko.string;case"number":return Number.isNaN(e)?Ko.nan:Ko.number;case"boolean":return Ko.boolean;case"function":return Ko.function;case"bigint":return Ko.bigint;case"symbol":return Ko.symbol;case"object":return Array.isArray(e)?Ko.array:null===e?Ko.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Ko.promise:"undefined"!=typeof Map&&e instanceof Map?Ko.map:"undefined"!=typeof Set&&e instanceof Set?Ko.set:"undefined"!=typeof Date&&e instanceof Date?Ko.date:Ko.object;default:return Ko.unknown}},zo=Po.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Zo extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof Zo))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Po.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Zo.create=e=>new Zo(e);var Wo=(e,t)=>{let n;switch(e.code){case zo.invalid_type:n=e.received===Ko.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case zo.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Po.jsonStringifyReplacer)}`;break;case zo.unrecognized_keys:n=`Unrecognized key(s) in object: ${Po.joinValues(e.keys,", ")}`;break;case zo.invalid_union:n="Invalid input";break;case zo.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Po.joinValues(e.options)}`;break;case zo.invalid_enum_value:n=`Invalid enum value. Expected ${Po.joinValues(e.options)}, received '${e.received}'`;break;case zo.invalid_arguments:n="Invalid function arguments";break;case zo.invalid_return_type:n="Invalid function return type";break;case zo.invalid_date:n="Invalid date";break;case zo.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Po.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case zo.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case zo.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case zo.custom:n="Invalid input";break;case zo.invalid_intersection_types:n="Intersection results could not be merged";break;case zo.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case zo.not_finite:n="Number must be finite";break;default:n=t.defaultError,Po.assertNever(e)}return{message:n}};let Go=Wo;function Ho(e,t){const n=Go,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Wo?void 0:Wo].filter(e=>!!e)});e.common.issues.push(r)}class Jo{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return Yo;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return Jo.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return Yo;if("aborted"===s.status)return Yo;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const Yo=Object.freeze({status:"aborted"}),Xo=e=>({status:"dirty",value:e}),Qo=e=>({status:"valid",value:e}),ec=e=>"aborted"===e.status,tc=e=>"dirty"===e.status,nc=e=>"valid"===e.status,rc=e=>"undefined"!=typeof Promise&&e instanceof Promise;var sc;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(sc||(sc={}));class ic{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ac=(e,t)=>{if(nc(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Zo(e.common.issues);return this._error=t,this._error}}};function oc(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??n??s.defaultError}},description:s}}class cc{get description(){return this._def.description}_getType(e){return qo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:qo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Jo,ctx:{common:e.parent.common,data:e.data,parsedType:qo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(rc(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qo(e)},r=this._parseSync({data:e,path:n.path,parent:n});return ac(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qo(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return nc(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>nc(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qo(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(rc(r)?r:Promise.resolve(r));return ac(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),i=()=>r.addIssue({code:zo.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new ou({schema:this,typeName:mu.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return cu.create(this,this._def)}nullable(){return uu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zc.create(this)}promise(){return au.create(this,this._def)}or(e){return Gc.create([this,e],this._def)}and(e){return Jc.create(this,e,this._def)}transform(e){return new ou({...oc(this._def),schema:this,typeName:mu.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new du({...oc(this._def),innerType:this,defaultValue:t,typeName:mu.ZodDefault})}brand(){return new pu({typeName:mu.ZodBranded,type:this,...oc(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new lu({...oc(this._def),innerType:this,catchValue:t,typeName:mu.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return fu.create(this,e)}readonly(){return gu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const uc=/^c[^\s-]{8,}$/i,dc=/^[0-9a-z]+$/,lc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pc=/^[a-z0-9_-]{21}$/i,fc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gc=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let yc;const bc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,vc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,kc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ec=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Oc=new RegExp(`^${xc}$`);function Ic(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Tc(e){return new RegExp(`^${Ic(e)}$`)}function _c(e){let t=`${xc}T${Ic(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Ac(e,t){return!("v4"!==t&&t||!bc.test(e))||!("v6"!==t&&t||!vc.test(e))}function jc(e,t){if(!fc.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function Cc(e,t){return!("v4"!==t&&t||!wc.test(e))||!("v6"!==t&&t||!kc.test(e))}class Pc extends cc{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Ko.string){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.string,received:t.parsedType}),Yo}const t=new Jo;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,i=e.data.length<r.value;(s||i)&&(n=this._getOrReturnCtx(e,n),s?Ho(n,{code:zo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):i&&Ho(n,{code:zo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)mc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"email",code:zo.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)yc||(yc=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"emoji",code:zo.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)hc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"uuid",code:zo.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)pc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"nanoid",code:zo.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)uc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"cuid",code:zo.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)dc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"cuid2",code:zo.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)lc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"ulid",code:zo.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),Ho(n,{validation:"url",code:zo.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"regex",code:zo.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){_c(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Oc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Tc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?gc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"duration",code:zo.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?Ac(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"ip",code:zo.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?jc(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"jwt",code:zo.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Cc(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"cidr",code:zo.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Ec.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"base64",code:zo.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?Sc.test(e.data)||(n=this._getOrReturnCtx(e,n),Ho(n,{validation:"base64url",code:zo.invalid_string,message:r.message}),t.dirty()):Po.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:zo.invalid_string,...sc.errToObj(n)})}_addCheck(e){return new Pc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...sc.errToObj(e)})}url(e){return this._addCheck({kind:"url",...sc.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...sc.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...sc.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...sc.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...sc.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...sc.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...sc.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...sc.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...sc.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...sc.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...sc.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...sc.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...sc.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...sc.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...sc.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...sc.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...sc.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...sc.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...sc.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...sc.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...sc.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...sc.errToObj(t)})}nonempty(e){return this.min(1,sc.errToObj(e))}trim(){return new Pc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Pc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Pc({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Bc(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Pc.create=e=>new Pc({checks:[],typeName:mu.ZodString,coerce:e?.coerce??!1,...oc(e)});class Nc extends cc{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==Ko.number){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.number,received:t.parsedType}),Yo}let t;const n=new Jo;for(const r of this._def.checks)if("int"===r.kind)Po.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==Bc(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.not_finite,message:r.message}),n.dirty()):Po.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,sc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,sc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,sc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,sc.toString(t))}setLimit(e,t,n,r){return new Nc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:sc.toString(r)}]})}_addCheck(e){return new Nc({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:sc.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:sc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:sc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:sc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:sc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:sc.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:sc.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:sc.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:sc.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Po.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Nc.create=e=>new Nc({checks:[],typeName:mu.ZodNumber,coerce:e?.coerce||!1,...oc(e)});class $c extends cc{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ko.bigint)return this._getInvalidInput(e);let t;const n=new Jo;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Ho(t,{code:zo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Po.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.bigint,received:t.parsedType}),Yo}gte(e,t){return this.setLimit("min",e,!0,sc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,sc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,sc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,sc.toString(t))}setLimit(e,t,n,r){return new $c({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:sc.toString(r)}]})}_addCheck(e){return new $c({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:sc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:sc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:sc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:sc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:sc.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}$c.create=e=>new $c({checks:[],typeName:mu.ZodBigInt,coerce:e?.coerce??!1,...oc(e)});class Rc extends cc{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Ko.boolean){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.boolean,received:t.parsedType}),Yo}return Qo(e.data)}}Rc.create=e=>new Rc({typeName:mu.ZodBoolean,coerce:e?.coerce||!1,...oc(e)});class Mc extends cc{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Ko.date){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.date,received:t.parsedType}),Yo}if(Number.isNaN(e.data.getTime())){return Ho(this._getOrReturnCtx(e),{code:zo.invalid_date}),Yo}const t=new Jo;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),Ho(n,{code:zo.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Po.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Mc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:sc.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:sc.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Mc.create=e=>new Mc({checks:[],coerce:e?.coerce||!1,typeName:mu.ZodDate,...oc(e)});class Dc extends cc{_parse(e){if(this._getType(e)!==Ko.symbol){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.symbol,received:t.parsedType}),Yo}return Qo(e.data)}}Dc.create=e=>new Dc({typeName:mu.ZodSymbol,...oc(e)});class Uc extends cc{_parse(e){if(this._getType(e)!==Ko.undefined){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.undefined,received:t.parsedType}),Yo}return Qo(e.data)}}Uc.create=e=>new Uc({typeName:mu.ZodUndefined,...oc(e)});class Vc extends cc{_parse(e){if(this._getType(e)!==Ko.null){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.null,received:t.parsedType}),Yo}return Qo(e.data)}}Vc.create=e=>new Vc({typeName:mu.ZodNull,...oc(e)});class Fc extends cc{constructor(){super(...arguments),this._any=!0}_parse(e){return Qo(e.data)}}Fc.create=e=>new Fc({typeName:mu.ZodAny,...oc(e)});class Lc extends cc{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Qo(e.data)}}Lc.create=e=>new Lc({typeName:mu.ZodUnknown,...oc(e)});class Kc extends cc{_parse(e){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.never,received:t.parsedType}),Yo}}Kc.create=e=>new Kc({typeName:mu.ZodNever,...oc(e)});class qc extends cc{_parse(e){if(this._getType(e)!==Ko.undefined){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.void,received:t.parsedType}),Yo}return Qo(e.data)}}qc.create=e=>new qc({typeName:mu.ZodVoid,...oc(e)});class zc extends cc{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==Ko.array)return Ho(t,{code:zo.invalid_type,expected:Ko.array,received:t.parsedType}),Yo;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(Ho(t,{code:e?zo.too_big:zo.too_small,minimum:s?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(Ho(t,{code:zo.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(Ho(t,{code:zo.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new ic(t,e,t.path,n)))).then(e=>Jo.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new ic(t,e,t.path,n)));return Jo.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new zc({...this._def,minLength:{value:e,message:sc.toString(t)}})}max(e,t){return new zc({...this._def,maxLength:{value:e,message:sc.toString(t)}})}length(e,t){return new zc({...this._def,exactLength:{value:e,message:sc.toString(t)}})}nonempty(e){return this.min(1,e)}}function Zc(e){if(e instanceof Wc){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=cu.create(Zc(r))}return new Wc({...e._def,shape:()=>t})}return e instanceof zc?new zc({...e._def,type:Zc(e.element)}):e instanceof cu?cu.create(Zc(e.unwrap())):e instanceof uu?uu.create(Zc(e.unwrap())):e instanceof Yc?Yc.create(e.items.map(e=>Zc(e))):e}zc.create=(e,t)=>new zc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:mu.ZodArray,...oc(t)});class Wc extends cc{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Po.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Ko.object){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.object,received:t.parsedType}),Yo}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Kc&&"strip"===this._def.unknownKeys))for(const e in n.data)s.includes(e)||i.push(e);const a=[];for(const e of s){const t=r[e],s=n.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new ic(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Kc){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)i.length>0&&(Ho(n,{code:zo.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const r=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new ic(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Jo.mergeObjectSync(t,e)):Jo.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return sc.errToObj,new Wc({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:sc.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new Wc({...this._def,unknownKeys:"strip"})}passthrough(){return new Wc({...this._def,unknownKeys:"passthrough"})}extend(e){return new Wc({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Wc({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:mu.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Wc({...this._def,catchall:e})}pick(e){const t={};for(const n of Po.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Wc({...this._def,shape:()=>t})}omit(e){const t={};for(const n of Po.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Wc({...this._def,shape:()=>t})}deepPartial(){return Zc(this)}partial(e){const t={};for(const n of Po.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new Wc({...this._def,shape:()=>t})}required(e){const t={};for(const n of Po.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof cu;)e=e._def.innerType;t[n]=e}return new Wc({...this._def,shape:()=>t})}keyof(){return ru(Po.objectKeys(this.shape))}}Wc.create=(e,t)=>new Wc({shape:()=>e,unknownKeys:"strip",catchall:Kc.create(),typeName:mu.ZodObject,...oc(t)}),Wc.strictCreate=(e,t)=>new Wc({shape:()=>e,unknownKeys:"strict",catchall:Kc.create(),typeName:mu.ZodObject,...oc(t)}),Wc.lazycreate=(e,t)=>new Wc({shape:e,unknownKeys:"strip",catchall:Kc.create(),typeName:mu.ZodObject,...oc(t)});class Gc extends cc{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new Zo(e.ctx.common.issues));return Ho(t,{code:zo.invalid_union,unionErrors:n}),Yo});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new Zo(e));return Ho(t,{code:zo.invalid_union,unionErrors:s}),Yo}}get options(){return this._def.options}}function Hc(e,t){const n=qo(e),r=qo(t);if(e===t)return{valid:!0,data:e};if(n===Ko.object&&r===Ko.object){const n=Po.objectKeys(t),r=Po.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=Hc(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===Ko.array&&r===Ko.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=Hc(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===Ko.date&&r===Ko.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Gc.create=(e,t)=>new Gc({options:e,typeName:mu.ZodUnion,...oc(t)});class Jc extends cc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ec(e)||ec(r))return Yo;const s=Hc(e.value,r.value);return s.valid?((tc(e)||tc(r))&&t.dirty(),{status:t.value,value:s.data}):(Ho(n,{code:zo.invalid_intersection_types}),Yo)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Jc.create=(e,t,n)=>new Jc({left:e,right:t,typeName:mu.ZodIntersection,...oc(n)});class Yc extends cc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ko.array)return Ho(n,{code:zo.invalid_type,expected:Ko.array,received:n.parsedType}),Yo;if(n.data.length<this._def.items.length)return Ho(n,{code:zo.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Yo;!this._def.rest&&n.data.length>this._def.items.length&&(Ho(n,{code:zo.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new ic(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Jo.mergeArray(t,e)):Jo.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Yc({...this._def,rest:e})}}Yc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Yc({items:e,typeName:mu.ZodTuple,rest:null,...oc(t)})};class Xc extends cc{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ko.object)return Ho(n,{code:zo.invalid_type,expected:Ko.object,received:n.parsedType}),Yo;const r=[],s=this._def.keyType,i=this._def.valueType;for(const e in n.data)r.push({key:s._parse(new ic(n,e,n.path,e)),value:i._parse(new ic(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Jo.mergeObjectAsync(t,r):Jo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new Xc(t instanceof cc?{keyType:e,valueType:t,typeName:mu.ZodRecord,...oc(n)}:{keyType:Pc.create(),valueType:e,typeName:mu.ZodRecord,...oc(t)})}}class Qc extends cc{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ko.map)return Ho(n,{code:zo.invalid_type,expected:Ko.map,received:n.parsedType}),Yo;const r=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([e,t],i)=>({key:r._parse(new ic(n,e,n.path,[i,"key"])),value:s._parse(new ic(n,t,n.path,[i,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of i){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return Yo;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of i){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return Yo;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}Qc.create=(e,t,n)=>new Qc({valueType:t,keyType:e,typeName:mu.ZodMap,...oc(n)});class eu extends cc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ko.set)return Ho(n,{code:zo.invalid_type,expected:Ko.set,received:n.parsedType}),Yo;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(Ho(n,{code:zo.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(Ho(n,{code:zo.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const n=new Set;for(const r of e){if("aborted"===r.status)return Yo;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>s._parse(new ic(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new eu({...this._def,minSize:{value:e,message:sc.toString(t)}})}max(e,t){return new eu({...this._def,maxSize:{value:e,message:sc.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}eu.create=(e,t)=>new eu({valueType:e,minSize:null,maxSize:null,typeName:mu.ZodSet,...oc(t)});class tu extends cc{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}tu.create=(e,t)=>new tu({getter:e,typeName:mu.ZodLazy,...oc(t)});class nu extends cc{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Ho(t,{received:t.data,code:zo.invalid_literal,expected:this._def.value}),Yo}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ru(e,t){return new su({values:e,typeName:mu.ZodEnum,...oc(t)})}nu.create=(e,t)=>new nu({value:e,typeName:mu.ZodLiteral,...oc(t)});class su extends cc{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return Ho(t,{expected:Po.joinValues(n),received:t.parsedType,code:zo.invalid_type}),Yo}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return Ho(t,{received:t.data,code:zo.invalid_enum_value,options:n}),Yo}return Qo(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return su.create(e,{...this._def,...t})}exclude(e,t=this._def){return su.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}su.create=ru;class iu extends cc{_parse(e){const t=Po.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Ko.string&&n.parsedType!==Ko.number){const e=Po.objectValues(t);return Ho(n,{expected:Po.joinValues(e),received:n.parsedType,code:zo.invalid_type}),Yo}if(this._cache||(this._cache=new Set(Po.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Po.objectValues(t);return Ho(n,{received:n.data,code:zo.invalid_enum_value,options:e}),Yo}return Qo(e.data)}get enum(){return this._def.values}}iu.create=(e,t)=>new iu({values:e,typeName:mu.ZodNativeEnum,...oc(t)});class au extends cc{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Ko.promise&&!1===t.common.async)return Ho(t,{code:zo.invalid_type,expected:Ko.promise,received:t.parsedType}),Yo;const n=t.parsedType===Ko.promise?t.data:Promise.resolve(t.data);return Qo(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}au.create=(e,t)=>new au({type:e,typeName:mu.ZodPromise,...oc(t)});class ou extends cc{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===mu.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:e=>{Ho(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===r.type){const e=r.transform(n.data,s);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Yo;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?Yo:"dirty"===r.status||"dirty"===t.value?Xo(r.value):r});{if("aborted"===t.value)return Yo;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?Yo:"dirty"===r.status||"dirty"===t.value?Xo(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,s);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?Yo:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Yo:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!nc(e))return Yo;const i=r.transform(e.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>nc(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):Yo)}Po.assertNever(r)}}ou.create=(e,t,n)=>new ou({schema:e,typeName:mu.ZodEffects,effect:t,...oc(n)}),ou.createWithPreprocess=(e,t,n)=>new ou({schema:t,effect:{type:"preprocess",transform:e},typeName:mu.ZodEffects,...oc(n)});class cu extends cc{_parse(e){return this._getType(e)===Ko.undefined?Qo(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}cu.create=(e,t)=>new cu({innerType:e,typeName:mu.ZodOptional,...oc(t)});class uu extends cc{_parse(e){return this._getType(e)===Ko.null?Qo(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}uu.create=(e,t)=>new uu({innerType:e,typeName:mu.ZodNullable,...oc(t)});class du extends cc{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Ko.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}du.create=(e,t)=>new du({innerType:e,typeName:mu.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...oc(t)});class lu extends cc{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return rc(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Zo(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Zo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}lu.create=(e,t)=>new lu({innerType:e,typeName:mu.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...oc(t)});class hu extends cc{_parse(e){if(this._getType(e)!==Ko.nan){const t=this._getOrReturnCtx(e);return Ho(t,{code:zo.invalid_type,expected:Ko.nan,received:t.parsedType}),Yo}return{status:"valid",value:e.data}}}hu.create=e=>new hu({typeName:mu.ZodNaN,...oc(e)});class pu extends cc{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class fu extends cc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Yo:"dirty"===e.status?(t.dirty(),Xo(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Yo:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new fu({in:e,out:t,typeName:mu.ZodPipeline})}}class gu extends cc{_parse(e){const t=this._def.innerType._parse(e),n=e=>(nc(e)&&(e.value=Object.freeze(e.value)),e);return rc(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var mu;gu.create=(e,t)=>new gu({innerType:e,typeName:mu.ZodReadonly,...oc(t)}),Wc.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(mu||(mu={}));const yu=Pc.create,bu=Nc.create;hu.create,$c.create;const wu=Rc.create;Mc.create,Dc.create,Uc.create,Vc.create,Fc.create,Lc.create,Kc.create;const vu=qc.create,ku=zc.create,Eu=Wc.create;Wc.strictCreate,Gc.create,Jc.create,Yc.create;const Su=Xc.create;Qc.create,eu.create,tu.create,nu.create;const xu=su.create;function Ou(e,t){let n={...e};for(let e of t)delete n[e];return n}iu.create,au.create,ou.create,cu.create,uu.create,ou.createWithPreprocess;var Iu=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;function Tu(e){let t=e.url,n=e.params;return n&&(t=t.replace(Iu,(e,t)=>t in n?`${n[t]}`:e)),t}function _u(e,t,n){return e.find(e=>e.method===t&&e.path===n)}var Au=class extends Error{constructor(e,t,n,r){super(e),this.config=t,this.data=n,this.cause=r}},ju={name:"form-data",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new Au("Zodios: multipart/form-data body must be an object",t);let n=function(e){let t=new FormData;for(let n in e)t.append(n,e[n]);return{data:t}}(t.data);return{...t,data:n.data,headers:{...t.headers,...n.headers}}}};var Cu={name:"form-url",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new Au("Zodios: application/x-www-form-urlencoded body must be an object",t);return{...t,data:new URLSearchParams(t.data).toString(),headers:{...t.headers,"Content-Type":"application/x-www-form-urlencoded"}}}};function Pu(e,t){return{request:async(n,r)=>({...r,headers:{...r.headers,[e]:t}})}}function Bu(e){return[!0,"response","all"].includes(e)}function Nu(e){return[!0,"request","all"].includes(e)}var $u=class{constructor(e,t){this.plugins=[],this.key=`${e}-${t}`}indexOf(e){return this.plugins.findIndex(t=>(null==t?void 0:t.name)===e)}use(e){if(e.name){let t=this.indexOf(e.name);if(-1!==t)return this.plugins[t]=e,{key:this.key,value:t}}return this.plugins.push(e),{key:this.key,value:this.plugins.length-1}}eject(e){if("string"==typeof e){let t=this.indexOf(e);if(-1===t)throw new Error(`Plugin with name '${e}' not found`);this.plugins[t]=void 0}else{if(e.key!==this.key)throw new Error(`Plugin with key '${e.key}' is not registered for endpoint '${this.key}'`);this.plugins[e.value]=void 0}}async interceptRequest(e,t){let n=t;for(let t of this.plugins)null!=t&&t.request&&(n=await t.request(e,n));return n}async interceptResponse(e,t,n){let r=n;for(let n=this.plugins.length-1;n>=0;n--){let s=this.plugins[n];s&&(r=r.then(null!=s&&s.response?n=>s.response(e,t,n):void 0,null!=s&&s.error?n=>s.error(e,t,n):void 0))}return r}count(){return this.plugins.reduce((e,t)=>t?e+1:e,0)}};function Ru(e){let t=new Set;for(let n of e){let e=`${n.method} ${n.path}`;if(t.has(e))throw new Error(`Zodios: Duplicate path '${e}'`);t.add(e)}let n=new Set;for(let t of e)if(t.alias){if(n.has(t.alias))throw new Error(`Zodios: Duplicate alias '${t.alias}'`);n.add(t.alias)}for(let t of e)if(t.parameters&&t.parameters.filter(e=>"Body"===e.type).length>1)throw new Error(`Zodios: Multiple body parameters in endpoint '${t.path}'`)}var Mu=class{constructor(e,t,r){let s,i;if(this.endpointPlugins=new Map,!e)throw Array.isArray(t)?new Error("Zodios: missing base url"):new Error("Zodios: missing api description");if("string"==typeof e&&Array.isArray(t))i=e,this.api=t,s=r||{};else{if(!Array.isArray(e)||Array.isArray(t))throw new Error("Zodios: api must be an array");this.api=e,s=t||{}}Ru(this.api),this.options={validate:!0,transform:!0,sendDefaults:!1,...s},this.options.axiosInstance?this.axiosInstance=this.options.axiosInstance:this.axiosInstance=n.create({...this.options.axiosConfig}),i&&(this.axiosInstance.defaults.baseURL=i),this.injectAliasEndpoints(),this.initPlugins(),[!0,"all","request","response"].includes(this.options.validate)&&this.use(function({validate:e,transform:t,sendDefaults:n}){return{name:"zod-validation",request:Nu(e)?async(e,r)=>{let s=_u(e,r.method,r.url);if(!s)throw new Error(`No endpoint found for ${r.method} ${r.url}`);let{parameters:i}=s;if(!i)return r;let a={...r,queries:{...r.queries},headers:{...r.headers},params:{...r.params}},o={Query:e=>{var t;return null==(t=a.queries)?void 0:t[e]},Body:e=>a.data,Header:e=>{var t;return null==(t=a.headers)?void 0:t[e]},Path:e=>{var t;return null==(t=a.params)?void 0:t[e]}},c={Query:(e,t)=>a.queries[e]=t,Body:(e,t)=>a.data=t,Header:(e,t)=>a.headers[e]=t,Path:(e,t)=>a.params[e]=t},u=Nu(t);for(let e of i){let{name:t,schema:s,type:i}=e,a=o[i](t);if(n||void 0!==a){let e=await s.safeParseAsync(a);if(!e.success)throw new Au(`Zodios: Invalid ${i} parameter '${t}'`,r,a,e.error);u&&c[i](t,e.data)}}return a}:void 0,response:Bu(e)?async(e,n,r)=>{var s,i,a,o;let c=_u(e,n.method,n.url);if(!c)throw new Error(`No endpoint found for ${n.method} ${n.url}`);if((null==(i=null==(s=r.headers)?void 0:s["content-type"])?void 0:i.includes("application/json"))||(null==(o=null==(a=r.headers)?void 0:a["content-type"])?void 0:o.includes("application/vnd.api+json"))){let e=await c.response.safeParseAsync(r.data);if(!e.success)throw new Au(`Zodios: Invalid response from endpoint '${c.method} ${c.path}'\nstatus: ${r.status} ${r.statusText}\ncause:\n${e.error.message}\nreceived:\n${JSON.stringify(r.data,null,2)}`,n,r.data,e.error);Bu(t)&&(r.data=e.data)}return r}:void 0}}(this.options))}initPlugins(){this.endpointPlugins.set("any-any",new $u("any","any")),this.api.forEach(e=>{let t=new $u(e.method,e.path);switch(e.requestFormat){case"binary":t.use(Pu("Content-Type","application/octet-stream"));break;case"form-data":t.use(ju);break;case"form-url":t.use(Cu);break;case"text":t.use(Pu("Content-Type","text/plain"))}this.endpointPlugins.set(`${e.method}-${e.path}`,t)})}getAnyEndpointPlugins(){return this.endpointPlugins.get("any-any")}findAliasEndpointPlugins(e){let t=this.api.find(t=>t.alias===e);if(t)return this.endpointPlugins.get(`${t.method}-${t.path}`)}findEnpointPlugins(e,t){return this.endpointPlugins.get(`${e}-${t}`)}get baseURL(){return this.axiosInstance.defaults.baseURL}get axios(){return this.axiosInstance}use(...e){if("object"==typeof e[0])return this.getAnyEndpointPlugins().use(e[0]);if("string"==typeof e[0]&&"object"==typeof e[1]){let t=this.findAliasEndpointPlugins(e[0]);if(!t)throw new Error(`Zodios: no alias '${e[0]}' found to register plugin`);return t.use(e[1])}if("string"==typeof e[0]&&"string"==typeof e[1]&&"object"==typeof e[2]){let t=this.findEnpointPlugins(e[0],e[1]);if(!t)throw new Error(`Zodios: no endpoint '${e[0]} ${e[1]}' found to register plugin`);return t.use(e[2])}throw new Error("Zodios: invalid plugin registration")}eject(e){var t;"string"!=typeof e?null==(t=this.endpointPlugins.get(e.key))||t.eject(e):this.getAnyEndpointPlugins().eject(e)}injectAliasEndpoints(){this.api.forEach(e=>{e.alias&&(["post","put","patch","delete"].includes(e.method)?this[e.alias]=(t,n)=>this.request({...n,method:e.method,url:e.path,data:t}):this[e.alias]=t=>this.request({...t,method:e.method,url:e.path}))})}async request(e){let t=e,n=this.getAnyEndpointPlugins(),r=this.findEnpointPlugins(t.method,t.url);t=await n.interceptRequest(this.api,t),r&&(t=await r.interceptRequest(this.api,t));let s=this.axiosInstance.request({...Ou(t,["params","queries"]),url:Tu(t),params:t.queries});return r&&(s=r.interceptResponse(this.api,t,s)),s=n.interceptResponse(this.api,t,s),(await s).data}async get(e,...[t]){return this.request({...t,method:"get",url:e})}async post(e,t,...[n]){return this.request({...n,method:"post",url:e,data:t})}async put(e,t,...[n]){return this.request({...n,method:"put",url:e,data:t})}async patch(e,t,...[n]){return this.request({...n,method:"patch",url:e,data:t})}async delete(e,t,...[n]){return this.request({...n,method:"delete",url:e,data:t})}};const Du=xu(["crypto","fx","equity","metal","rates","crypto_redemption_rate","commodities","crypto_index","crypto_nav"]),Uu=Du.nullish(),Vu=yu(),Fu=Eu({attributes:Su(yu()),id:Vu}).passthrough(),Lu=yu(),Ku=xu(["hex","base64"]),qu=Eu({data:ku(yu()),encoding:Ku}).passthrough(),zu=Eu({conf:yu(),expo:bu().int(),price:yu(),publish_time:bu().int()}).passthrough(),Zu=Eu({prev_publish_time:bu().int().nullable(),proof_available_time:bu().int().nullable(),slot:bu().int().gte(0).nullable()}).partial().passthrough(),Wu=Eu({ema_price:zu,id:Vu,metadata:Zu,price:zu}).passthrough(),Gu=Eu({binary:qu,parsed:ku(Wu).nullish()}).passthrough(),Hu=Eu({cap:bu().int().gte(0),publisher:yu()}).passthrough(),Ju=Eu({publisher_stake_caps:ku(Hu)}).passthrough(),Yu=Eu({binary:qu,parsed:ku(Ju).nullish()}).passthrough(),Xu=Eu({down_slots_ratio:yu(),end_timestamp:bu().int(),id:Vu,start_timestamp:bu().int(),twap:zu}).passthrough(),Qu=Eu({binary:qu,parsed:ku(Xu).nullish()}).passthrough(),ed={AssetType:Du,asset_type:Uu,RpcPriceIdentifier:Vu,PriceFeedMetadata:Fu,PriceIdInput:Lu,EncodingType:Ku,BinaryUpdate:qu,RpcPrice:zu,RpcPriceFeedMetadataV2:Zu,ParsedPriceUpdate:Wu,PriceUpdate:Gu,ParsedPublisherStakeCap:Hu,ParsedPublisherStakeCapsUpdate:Ju,LatestPublisherStakeCapsUpdateDataResponse:Yu,ParsedPriceFeedTwap:Xu,TwapsResponse:Qu};var td;new Mu((Ru(td=[{method:"get",path:"/v2/price_feeds",alias:"price_feeds_metadata",description:"Get the set of price feeds.\n\nThis endpoint fetches all price feeds from the Pyth network. It can be filtered by asset type\nand query string.",requestFormat:"json",parameters:[{name:"query",type:"Query",schema:yu().nullish()},{name:"asset_type",type:"Query",schema:Uu}],response:ku(Fu)},{method:"get",path:"/v2/updates/price/:publish_time",alias:"timestamp_price_updates",description:"Get the latest price updates by price feed id.\n\nGiven a collection of price feed ids, retrieve the latest Pyth price for each price feed.",requestFormat:"json",parameters:[{name:"publish_time",type:"Path",schema:bu().int()},{name:"ids[]",type:"Query",schema:ku(Lu)},{name:"encoding",type:"Query",schema:xu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:wu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:wu().optional()}],response:Gu,errors:[{status:404,description:"Price ids not found",schema:vu()}]},{method:"get",path:"/v2/updates/price/latest",alias:"latest_price_updates",description:"Get the latest price updates by price feed id.\n\nGiven a collection of price feed ids, retrieve the latest Pyth price for each price feed.",requestFormat:"json",parameters:[{name:"ids[]",type:"Query",schema:ku(Lu)},{name:"encoding",type:"Query",schema:xu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:wu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:wu().optional()}],response:Gu,errors:[{status:404,description:"Price ids not found",schema:vu()}]},{method:"get",path:"/v2/updates/price/stream",alias:"price_stream_sse_handler",description:"SSE route handler for streaming price updates.\n\nThe connection will automatically close after 24 hours to prevent resource leaks.\nClients should implement reconnection logic to maintain continuous price updates.",requestFormat:"json",parameters:[{name:"ids[]",type:"Query",schema:ku(Lu)},{name:"encoding",type:"Query",schema:xu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:wu().optional()},{name:"allow_unordered",type:"Query",schema:wu().optional()},{name:"benchmarks_only",type:"Query",schema:wu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:wu().optional()}],response:Gu,errors:[{status:404,description:"Price ids not found",schema:vu()}]},{method:"get",path:"/v2/updates/publisher_stake_caps/latest",alias:"latest_publisher_stake_caps",description:"Get the most recent publisher stake caps update data.",requestFormat:"json",parameters:[{name:"encoding",type:"Query",schema:xu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:wu().optional()}],response:Yu},{method:"get",path:"/v2/updates/twap/:window_seconds/latest",alias:"latest_twaps",description:"Get the latest TWAP by price feed id with a custom time window.\n\nGiven a collection of price feed ids, retrieve the latest Pyth TWAP price for each price feed.",requestFormat:"json",parameters:[{name:"window_seconds",type:"Path",schema:bu().int().gte(0)},{name:"ids[]",type:"Query",schema:ku(Lu)},{name:"encoding",type:"Query",schema:xu(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:wu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:wu().optional()}],response:Qu,errors:[{status:404,description:"Price ids not found",schema:vu()}]}]),td));class nd{baseURL;timeout;httpRetries;headers;constructor(e,t){this.baseURL=e,this.timeout=t?.timeout??5e3,this.httpRetries=t?.httpRetries??3,this.headers=t?.headers??{}}async httpRequest(e,t,n,r=this.httpRetries,s=100+Math.floor(100*Math.random())){try{const r=await fetch(e,{...n,signal:AbortSignal.any([...n?.signal?[n.signal]:[],AbortSignal.timeout(this.timeout)]),headers:{...this.headers,...n?.headers}});if(!r.ok){const e=await r.text();throw new Error(`HTTP error! status: ${r.status.toString()}${e?`, body: ${e}`:""}`)}const s=await r.json();return t.parse(s)}catch(i){if(r>0&&!(i instanceof Error&&"AbortError"===i.name))return await new Promise(e=>setTimeout(e,s)),this.httpRequest(e,t,n,r-1,2*s);throw i}}async getPriceFeeds({fetchOptions:e,...t}={}){const n=this.buildURL("price_feeds");if(t){const e=Lo(t);this.appendUrlSearchParams(n,e)}return await this.httpRequest(n.toString(),ed.PriceFeedMetadata.array(),e)}async getLatestPublisherCaps({fetchOptions:e,...t}={}){const n=this.buildURL("updates/publisher_stake_caps/latest");return t&&this.appendUrlSearchParams(n,t),await this.httpRequest(n.toString(),ed.LatestPublisherStakeCapsUpdateDataResponse,e)}async getLatestPriceUpdates(e,t,n){const r=this.buildURL("updates/price/latest");for(const t of e)r.searchParams.append("ids[]",t);if(t){const e=Lo(t);this.appendUrlSearchParams(r,e)}return this.httpRequest(r.toString(),ed.PriceUpdate,n)}async getPriceUpdatesAtTimestamp(e,t,n,r){const s=this.buildURL(`updates/price/${e.toString()}`);for(const e of t)s.searchParams.append("ids[]",e);if(n){const e=Lo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),ed.PriceUpdate,r)}async getPriceUpdatesStream(e,t){const n=this.buildURL("updates/price/stream");for(const t of e)n.searchParams.append("ids[]",t);if(t){const e=Lo(t);this.appendUrlSearchParams(n,e)}return new Vo(n.toString(),{fetch:(e,t)=>fetch(e,{...t,headers:{...t?.headers,...this.headers}})})}async getLatestTwaps(e,t,n,r){const s=this.buildURL(`updates/twap/${t.toString()}/latest`);for(const t of e)s.searchParams.append("ids[]",t);if(n){const e=Lo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),ed.TwapsResponse,r)}appendUrlSearchParams(e,t){for(const[n,r]of Object.entries(t))void 0!==r&&e.searchParams.append(n,String(r))}buildURL(e){return new URL(`./v2/${e}`,`${this.baseURL}${this.baseURL.endsWith("/")?"":"/"}`)}}class rd extends nd{async getPriceFeedsUpdateData(e){return(await this.getLatestPriceUpdates(e,{encoding:"base64",parsed:!1})).binary.data.map(e=>t.from(e,"base64"))}}const sd=16384;class id{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(e,t,n){this.provider=e,this.pythStateId=t,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(void 0===this.baseUpdateFee){const e=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!e.data?.content||"moveObject"!==e.data.content.dataType)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=e.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(e){const t=await this.provider.getObject({id:e,options:{showContent:!0}}).then(t=>{if("moveObject"==t.data?.content?.dataType)return t.data.content.fields;throw new Error(`Cannot fetch package id for object ${e}`)});if("upgrade_cap"in t)return t.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(e,t){const n=await this.getWormholePackageId(),r=[];for(const s of e){const[e]=t.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[t.object(this.wormholeStateId),t.pure(Sr.vector(Sr.U8).serialize([...s],{maxSize:sd}).toBytes()),t.object(es)]});r.push(e)}return r}async verifyVaasAndGetHotPotato(e,t,n){if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");const r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e),[i]=e.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[e.object(this.pythStateId),e.pure(Sr.vector(Sr.U8).serialize([...t[0]],{maxSize:sd}).toBytes()),s[0],e.object(es)]});return i}async executePriceFeedUpdates(e,t,n,r,s){const i=[];let a=0;for(const o of n){const n=await this.getPriceFeedObjectId(o);if(!n)throw new Error(`Price feed ${o} not found, please create it first`);i.push(n),[r]=e.moveCall({target:`${t}::pyth::update_single_price_feed`,arguments:[e.object(this.pythStateId),r,e.object(n),s[a],e.object(es)]}),a++}return e.moveCall({target:`${t}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${t}::price_info::PriceInfo`]}),i}async updatePriceFeeds(e,t,n){const r=await this.getPythPackageId(),s=await this.verifyVaasAndGetHotPotato(e,t,r),i=await this.getBaseUpdateFee(),a=e.splitCoins(e.gas,n.map(()=>e.pure.u64(i)));return await this.executePriceFeedUpdates(e,r,n,s,a)}async updatePriceFeedsWithCoins(e,t,n,r){const s=await this.getPythPackageId(),i=await this.verifyVaasAndGetHotPotato(e,t,s);return await this.executePriceFeedUpdates(e,s,n,i,r)}async createPriceFeed(e,t){const n=await this.getPythPackageId();if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");const r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e);e.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[e.object(this.pythStateId),e.pure(Sr.vector(Sr.U8).serialize([...t[0]],{maxSize:sd}).toBytes()),s[0],e.object(es)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(e){const n=e.replace("0x","");if(!this.priceFeedObjectIdCache.has(n)){const{id:e,fieldType:r}=await this.getPriceTableInfo(),s=await this.provider.getDynamicFieldObject({parentId:e,name:{type:`${r}::price_identifier::PriceIdentifier`,value:{bytes:[...t.from(n,"hex")]}}});if(!s.data?.content)return;if("moveObject"!==s.data.content.dataType)throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(n,s.data.content.fields.value)}return this.priceFeedObjectIdCache.get(n)}async getPriceTableInfo(){if(void 0===this.priceTableInfo){const e=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!e.data?.type)throw new Error("Price Table not found, contract may not be initialized");let t=e.data.type.replace("0x2::table::Table<","");t=t.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:e.data.objectId,fieldType:t}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(e){const t=7+e.readUint8(6)+1,n=e.readUint16BE(t),r=t+2;return e.subarray(r,r+n)}}const ad=.05,od={AUTHORIZE:"/api/authorize",PLACE_ORDER:"/api/perp-trade-api/trade/placeorder",CANCEL_ORDER:"/api/perp-trade-api/trade/cancelorder",PLAN_CLOSE_ORDER:"/api/perp-trade-api/plan/batch/plancloseorder",CANCEL_PLAN_ORDER:"/api/perp-trade-api/plan/cancelplanorder",ADJUST_LEVERAGE:"/api/perp-trade-api/user-config/adjust-leverage",GET_USER_CONFIG:"/api/perp-trade-api/user-config/config",GET_ACCOUNT_INFO:"/api/perp-trade-api/curr-info/account",GET_POSITIONS:"/api/perp-trade-api/curr-info/positions",GET_OPEN_ORDERS:"/api/perp-trade-api/curr-info/orders",GET_TRADING_PAIRS:"/api/perp-market-api/list",GET_ORDER_BOOK:"/api/perp-market-api/orderBook",GET_TICKER:"/api/perp-market-api/ticker",GET_POSITION_TPSL:"/api/perp-trade-api/plan/position/tpsl",HISTORY_ORDERS:"/api/perp-trade-api/history/orders",FUNDING_SETTLEMENTS:"/api/perp-trade-api/history/funding-settlements",BALANCE_CHANGES:"/api/perp-trade-api/history/balance-changes",ORACLE:"/api/perp-market-api/oracle",VAULTS_BY_CREATOR:"/api/perp-vault-api/public/vaults/by-creator"},cd='{"onboardingUrl":"dipcoin.io"}',ud={USDC:6,SUI:9,DEFAULT:18},dd={mainnet:{wormholeStateId:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pythStateId:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",priceServiceUrl:"https://hermes.pyth.network/"},testnet:{wormholeStateId:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",pythStateId:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",priceServiceUrl:"https://hermes-beta.pyth.network"}};class ld{baseURL;walletAddress;authToken;timeout=30;constructor(e){this.baseURL=e}isPerpTradeApiUrl(e){return e?.startsWith("/api/perp-trade-api")??!1}isPublicEndpoint(e){return e?.includes("/public/")??!1}buildHeaders(e,t="application/json"){const n={"Content-Type":t};return this.isPerpTradeApiUrl(e)&&(this.walletAddress&&(n["X-Wallet-Address"]=this.walletAddress),this.authToken&&!this.isPublicEndpoint(e)&&(n.Authorization=`Bearer ${this.authToken}`)),n}curlRequest(e,t,n,s){return new Promise((i,a)=>{const o=`${this.baseURL}${t}`,c=["-s","-X",e,o,"--max-time",String(this.timeout)];for(const[e,t]of Object.entries(n))c.push("-H",`${e}: ${t}`);s&&c.push("-d",s);const u=r("curl",c);let d="",l="";u.stdout.on("data",e=>{d+=e}),u.stderr.on("data",e=>{l+=e}),u.on("close",e=>{if(!d)return a(new Error(l||`curl exited with code ${e}`));try{i(JSON.parse(d))}catch{a(new Error(`Invalid JSON response: ${d.slice(0,200)}`))}}),u.on("error",e=>a(e))})}setWalletAddress(e){this.walletAddress=e}setAuthToken(e){this.authToken=e}async get(e,t){let n=e;if(t?.params){const e=new URLSearchParams;for(const[n,r]of Object.entries(t.params))null!=r&&e.append(n,String(r));const r=e.toString();r&&(n+=`?${r}`)}return this.curlRequest("GET",n,this.buildHeaders(e))}async post(e,t){const n=t?JSON.stringify(t):void 0;return this.curlRequest("POST",e,this.buildHeaders(e),n)}async postForm(e,t){const n=new URLSearchParams;for(const[e,r]of Object.entries(t))null!=r&&n.append(e,"object"==typeof r?JSON.stringify(r):String(r));return this.curlRequest("POST",e,this.buildHeaders(e,"application/x-www-form-urlencoded"),n.toString())}}function hd(e){const t=function(e){let t=0;return e.ioc&&(t+=1),e.postOnly&&(t+=2),e.reduceOnly&&(t+=4),e.isLong&&(t+=8),e.orderbookOnly&&(t+=16),t}(e);return function(e){let t="{\n";for(const[n,r]of e)t+=`"${n}":"${r}",\n`;return t+='"domain":"dipcoin.io"\n',t+="}",t}([["market",`${e.market}`],["creator",`${e.creator}`],["isLong",`${e.isLong}`],["reduceOnly",`${e.reduceOnly}`],["postOnly",`${e.postOnly}`],["orderbookOnly",`${e.orderbookOnly}`],["ioc",`${e.ioc||!1}`],["quantity",`${e.quantity.toFixed(0)}`],["price",`${e.price.toFixed(0)}`],["leverage",`${e.leverage.toFixed(0)}`],["expiration",`${e.expiration.toFixed(0)}`],["salt",`${e.salt.toFixed(0)}`],["orderFlag",`${t}`]])}const pd="0x6";function fd(e){const t=e?.packages;if(!t||!t.length)throw new Error("Deployment config missing packages array");return t[t.length-1]}function gd(e){const t=e?.objects?.ProtocolConfig?.id;if(!t)throw new Error("Deployment config missing ProtocolConfig id");return t}function md(e){const t=e?.objects?.Bank?.id;if(!t)throw new Error("Deployment config missing Bank id");return t}function yd(e){const t=e?.objects?.SubAccounts?.id;if(!t)throw new Error("Deployment config missing SubAccounts id");return t}function bd(e){const t=e?.objects?.TxIndexer?.id;if(!t)throw new Error("Deployment config missing TxIndexer id");return t}function wd(e){const t=e?.objects?.Currency?.dataType;if(!t)throw new Error("Deployment config missing Currency dataType");return t}function vd(e,t){const n=t?.toUpperCase(),r=e?.markets?.[n]?.Objects?.Perpetual?.id;if(!r)throw new Error(`Deployment config missing Perpetual id for ${n}`);return r}function kd(e,t){const n=t?.toUpperCase()||"ETH-PERP",r=e?.markets?.[n]?.Objects?.PriceInfoObject?.id;if(!r)throw new Error(`Deployment config missing PriceInfoObject id for ${n}`);return r}function Ed(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=fd(e);return i.moveCall({target:`${a}::exchange::add_margin_v2`,arguments:[i.object(gd(e)),i.object(pd),i.object(t.perpID||vd(e,t.market)),i.object(md(e)),i.object(t.subAccountsMapID||yd(e)),i.object(bd(e)),i.object(kd(e,t.market)),i.pure.address(t.account||s||""),i.pure.u128(t.amount.toString())],typeArguments:[wd(e)]}),i}function Sd(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=fd(e);return i.moveCall({target:`${a}::exchange::remove_margin_v2`,arguments:[i.object(gd(e)),i.object(pd),i.object(t.perpID||vd(e,t.market)),i.object(md(e)),i.object(t.subAccountsMapID||yd(e)),i.object(bd(e)),i.object(kd(e,t.market)),i.pure.address(t.account||s||""),i.pure.u128(t.amount.toString())],typeArguments:[wd(e)]}),i}function xd(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=function(e,t){const n=t?.toUpperCase()||"ETH-PERP",r=e?.markets?.[n]?.Objects?.PriceInfoObject?.dataType;if(!r)throw new Error(`Deployment config missing PriceInfoObject dataType for ${n}`);return r.split("::")[0]}(e,t.market),o=kd(e,t.market),c=function(e,t){const n=t?.toUpperCase()||"ETH-PERP",r=e?.markets?.[n]?.Config?.priceInfoFeedId;if(!r)throw new Error(`Deployment config missing priceInfoFeedId for ${n}`);return r}(e,t.market),u=function(e){const t=e.startsWith("0x")?e.slice(2):e,n=[];for(let e=0;e<t.length;e+=2)n.push(parseInt(t.substr(e,2),16));return n}(c),d=function(e,t){const n=Math.pow(10,t);return Math.round(e*n).toString()}(t.price,6);return i.moveCall({target:`${a}::price_info::update_price_info_object_for_test`,arguments:[i.object(o),i.object(pd),i.pure.u64(d),i.pure.u64(t.confidence||"10"),i.pure(Sr.vector(Sr.u8()).serialize(new Uint8Array(u)))],typeArguments:[]}),i}async function Od(e,t,n){return e.signAndExecuteTransaction({signer:n,transaction:t,options:{showObjectChanges:!0,showEffects:!0,showEvents:!0,showInput:!0}})}async function Id(e,t,n){const r=kd(t,n),s=await e.getObject({id:r,options:{showContent:!0}}),i=s.data?.content?.fields?.price_info?.fields?.price_feed?.fields?.price?.fields;if(!i)throw new Error(`Failed to read oracle price for ${n}`);return Number(i.price.fields.magnitude)/Math.pow(10,Number(i.expo.fields.magnitude))}async function Td(e,t,n,r){const s=function(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=wd(e),o=i.splitCoins(i.gas,[BigInt(t.amount)]),c=fd(e);return i.moveCall({target:`${c}::bank::deposit_v2`,arguments:[i.object(gd(e)),i.object(t.bankID||md(e)),i.object(bd(e)),i.pure.address(t.accountAddress||s||""),i.pure.u64(t.amount),o],typeArguments:[a]}),i}(t,n,void 0,n.gasBudget,r.getPublicKey().toSuiAddress());return Od(e,s,r)}async function _d(e,t,n,r){const s=function(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=fd(e);return i.moveCall({target:`${a}::bank::withdraw_v2`,arguments:[i.object(gd(e)),i.object(t.bankID||md(e)),i.object(bd(e)),i.pure.address(t.accountAddress||s||""),i.pure.u128(t.amount)],typeArguments:[wd(e)]}),i}(t,n,void 0,n.gasBudget,r.getPublicKey().toSuiAddress());return Od(e,s,r)}async function Ad(e,t,n,r){const s=function(e,t,n,r,s){const i=n||new Ba;r&&i.setGasBudget(r),s&&i.setSender(s);const a=fd(e);return i.moveCall({target:`${a}::sub_accounts::set_sub_account`,arguments:[i.object(gd(e)),i.object(t.subAccountsMapID||yd(e)),i.pure.address(t.account),i.pure.bool(t.status)],typeArguments:[]}),i}(t,n,void 0,n.gasBudget,r.getPublicKey().toSuiAddress());return Od(e,s,r)}var jd,Cd;!function(e){e.BUY="BUY",e.SELL="SELL"}(jd||(jd={})),function(e){e.MARKET="MARKET",e.LIMIT="LIMIT"}(Cd||(Cd={}));const Pd=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Bd=new Uint32Array(64);class Nd extends Vs{constructor(e=32){super(64,e,8,!1),this.A=0|Fs[0],this.B=0|Fs[1],this.C=0|Fs[2],this.D=0|Fs[3],this.E=0|Fs[4],this.F=0|Fs[5],this.G=0|Fs[6],this.H=0|Fs[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:a,H:o}=this;return[e,t,n,r,s,i,a,o]}set(e,t,n,r,s,i,a,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)Bd[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Bd[e-15],n=Bd[e-2],r=hs(t,7)^hs(t,18)^t>>>3,s=hs(n,17)^hs(n,19)^n>>>10;Bd[e]=s+Bd[e-7]+r+Bd[e-16]|0}let{A:n,B:r,C:s,D:i,E:a,F:o,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(hs(a,6)^hs(a,11)^hs(a,25))+Ds(a,o,c)+Pd[e]+Bd[e]|0,d=(hs(n,2)^hs(n,13)^hs(n,22))+Us(n,r,s)|0;u=c,c=o,o=a,a=i+t|0,i=s,s=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,s,i,a,o,c,u)}roundClean(){ds(Bd)}destroy(){this.set(0,0,0,0,0,0,0,0),ds(this.buffer)}}const $d=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:a}=Zs(e[i],t);[r[i],s[i]]=[n,a]}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Rd=(()=>$d[0])(),Md=(()=>$d[1])(),Dd=new Uint32Array(80),Ud=new Uint32Array(80);class Vd extends Vs{constructor(e=64){super(128,e,16,!1),this.Ah=0|Ks[0],this.Al=0|Ks[1],this.Bh=0|Ks[2],this.Bl=0|Ks[3],this.Ch=0|Ks[4],this.Cl=0|Ks[5],this.Dh=0|Ks[6],this.Dl=0|Ks[7],this.Eh=0|Ks[8],this.El=0|Ks[9],this.Fh=0|Ks[10],this.Fl=0|Ks[11],this.Gh=0|Ks[12],this.Gl=0|Ks[13],this.Hh=0|Ks[14],this.Hl=0|Ks[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:i,Dh:a,Dl:o,Eh:c,El:u,Fh:d,Fl:l,Gh:h,Gl:p,Hh:f,Hl:g}=this;return[e,t,n,r,s,i,a,o,c,u,d,l,h,p,f,g]}set(e,t,n,r,s,i,a,o,c,u,d,l,h,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|d,this.Fl=0|l,this.Gh=0|h,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)Dd[n]=e.getUint32(t),Ud[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Dd[e-15],n=0|Ud[e-15],r=Hs(t,n,1)^Hs(t,n,8)^Ws(t,0,7),s=Js(t,n,1)^Js(t,n,8)^Gs(t,n,7),i=0|Dd[e-2],a=0|Ud[e-2],o=Hs(i,a,19)^Ys(i,a,61)^Ws(i,0,6),c=Js(i,a,19)^Xs(i,a,61)^Gs(i,a,6),u=ri(s,c,Ud[e-7],Ud[e-16]),d=si(u,r,o,Dd[e-7],Dd[e-16]);Dd[e]=0|d,Ud[e]=0|u}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:a,Cl:o,Dh:c,Dl:u,Eh:d,El:l,Fh:h,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Hs(d,l,14)^Hs(d,l,18)^Ys(d,l,41),b=Js(d,l,14)^Js(d,l,18)^Xs(d,l,41),w=d&h^~d&f,v=ii(y,b,l&p^~l&g,Md[e],Ud[e]),k=ai(v,m,t,w,Rd[e],Dd[e]),E=0|v,S=Hs(n,r,28)^Ys(n,r,34)^Ys(n,r,39),x=Js(n,r,28)^Xs(n,r,34)^Xs(n,r,39),O=n&s^n&a^s&a,I=r&i^r&o^i&o;m=0|f,y=0|g,f=0|h,g=0|p,h=0|d,p=0|l,({h:d,l:l}=ei(0|c,0|u,0|k,0|E)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|n,i=0|r;const T=ti(E,x,I);n=ni(T,k,S,O),r=0|T}({h:n,l:r}=ei(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=ei(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=ei(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=ei(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l:l}=ei(0|this.Eh,0|this.El,0|d,0|l)),({h:h,l:p}=ei(0|this.Fh,0|this.Fl,0|h,0|p)),({h:f,l:g}=ei(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=ei(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,a,o,c,u,d,l,h,p,f,g,m,y)}roundClean(){ds(Dd,Ud)}destroy(){ds(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Fd extends Vd{constructor(){super(48),this.Ah=0|Ls[0],this.Al=0|Ls[1],this.Bh=0|Ls[2],this.Bl=0|Ls[3],this.Ch=0|Ls[4],this.Cl=0|Ls[5],this.Dh=0|Ls[6],this.Dl=0|Ls[7],this.Eh=0|Ls[8],this.El=0|Ls[9],this.Fh=0|Ls[10],this.Fl=0|Ls[11],this.Gh=0|Ls[12],this.Gl=0|Ls[13],this.Hh=0|Ls[14],this.Hl=0|Ls[15]}}const Ld=Ns(()=>new Nd),Kd=Ns(()=>new Vd),qd=Ns(()=>new Fd),zd=BigInt(0),Zd=BigInt(1);function Wd(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Gd(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Hd(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?zd:BigInt("0x"+e)}function Jd(e){return Hd(vs(e))}function Yd(e){return is(e),Hd(vs(Uint8Array.from(e).reverse()))}function Xd(e,t){return _s(e.toString(16).padStart(2*t,"0"))}function Qd(e,t){return Xd(e,t).reverse()}function el(e,t,n){let r;if("string"==typeof t)try{r=_s(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!rs(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}const tl=e=>"bigint"==typeof e&&zd<=e;function nl(e,t,n,r){if(!function(e,t,n){return tl(e)&&tl(t)&&tl(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function rl(e){let t;for(t=0;e>zd;e>>=Zd,t+=1);return t}const sl=e=>(Zd<<BigInt(e))-Zd;function il(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const s=e[t];if(r&&void 0===s)return;const i=typeof s;if(i!==n||null===s)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function al(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(void 0!==s)return s;const i=e(n,...r);return t.set(n,i),i}}const ol=BigInt(0),cl=BigInt(1),ul=BigInt(2),dl=BigInt(3),ll=BigInt(4),hl=BigInt(5),pl=BigInt(7),fl=BigInt(8),gl=BigInt(9),ml=BigInt(16);function yl(e,t){const n=e%t;return n>=ol?n:t+n}function bl(e,t,n){let r=e;for(;t-- >ol;)r*=r,r%=n;return r}function wl(e,t){if(e===ol)throw new Error("invert: expected non-zero number");if(t<=ol)throw new Error("invert: expected positive modulus, got "+t);let n=yl(e,t),r=t,s=ol,i=cl;for(;n!==ol;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==cl)throw new Error("invert: does not exist");return yl(s,t)}function vl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function kl(e,t){const n=(e.ORDER+cl)/ll,r=e.pow(t,n);return vl(e,r,t),r}function El(e,t){const n=(e.ORDER-hl)/fl,r=e.mul(t,ul),s=e.pow(r,n),i=e.mul(t,s),a=e.mul(e.mul(i,ul),s),o=e.mul(i,e.sub(a,e.ONE));return vl(e,o,t),o}function Sl(e){if(e<dl)throw new Error("sqrt is not defined for small field");let t=e-cl,n=0;for(;t%ul===ol;)t/=ul,n++;let r=ul;const s=Al(e);for(;1===_l(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return kl;let i=s.pow(r,t);const a=(t+cl)/ul;return function(e,r){if(e.is0(r))return r;if(1!==_l(e,r))throw new Error("Cannot find square root");let s=n,o=e.mul(e.ONE,i),c=e.pow(r,t),u=e.pow(r,a);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===s)throw new Error("Cannot find square root");const r=cl<<BigInt(s-t-1),i=e.pow(o,r);s=t,o=e.sqr(i),c=e.mul(c,o),u=e.mul(u,i)}return u}}function xl(e){return e%ll===dl?kl:e%fl===hl?El:e%ml===gl?function(e){const t=Al(e),n=Sl(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),a=(e+pl)/ml;return(e,t)=>{let n=e.pow(t,a),o=e.mul(n,r);const c=e.mul(n,s),u=e.mul(n,i),d=e.eql(e.sqr(o),t),l=e.eql(e.sqr(c),t);n=e.cmov(n,o,d),o=e.cmov(u,c,l);const h=e.eql(e.sqr(o),t),p=e.cmov(n,o,h);return vl(e,p,t),p}}(e):Sl(e)}const Ol=(e,t)=>(yl(e,t)&cl)===cl,Il=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Tl(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n)),e.ONE),i=e.inv(s);return t.reduceRight((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n)),i),r}function _l(e,t){const n=(e.ORDER-cl)/ul,r=e.pow(t,n),s=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),a=e.eql(r,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Al(e,t,n=!1,r={}){if(e<=ol)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,a,o=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modOnDecode&&(o=e.modOnDecode),a=e.allowedLengths}else"number"==typeof t&&(s=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:u}=function(e,t){void 0!==t&&ss(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const l=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:sl(c),ZERO:ol,ONE:cl,allowedLengths:a,create:t=>yl(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return ol<=t&&t<e},is0:e=>e===ol,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&cl)===cl,neg:t=>yl(-t,e),eql:(e,t)=>e===t,sqr:t=>yl(t*t,e),add:(t,n)=>yl(t+n,e),sub:(t,n)=>yl(t-n,e),mul:(t,n)=>yl(t*n,e),pow:(e,t)=>function(e,t,n){if(n<ol)throw new Error("invalid exponent, negatives unsupported");if(n===ol)return e.ONE;if(n===cl)return t;let r=e.ONE,s=t;for(;n>ol;)n&cl&&(r=e.mul(r,s)),s=e.sqr(s),n>>=cl;return r}(l,e,t),div:(t,n)=>yl(t*wl(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>wl(t,e),sqrt:i||(t=>(d||(d=xl(e)),d(l,t))),toBytes:e=>n?Qd(e,u):Xd(e,u),fromBytes:(t,r=!0)=>{if(a){if(!a.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let s=n?Yd(t):Jd(t);if(o&&(s=yl(s,e)),!r&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Tl(l,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(l)}function jl(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Cl(e){const t=jl(e);return t+Math.ceil(t/2)}const Pl=BigInt(0),Bl=BigInt(1);function Nl(e,t){const n=t.negate();return e?n:t}function $l(e,t){const n=Tl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Rl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ml(e,t){Rl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:sl(e),maxNumber:n,shiftBy:BigInt(e)}}function Dl(e,t,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:a}=n;let o=Number(e&s),c=e>>a;o>r&&(o-=i,c+=Bl);const u=t*r;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:u}}const Ul=new WeakMap,Vl=new WeakMap;function Fl(e){return Vl.get(e)||1}function Ll(e){if(e!==Pl)throw new Error("invalid wNAF")}class Kl{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Pl;)t&Bl&&(n=n.add(r)),r=r.double(),t>>=Bl;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ml(t,this.bits),s=[];let i=e,a=i;for(let e=0;e<n;e++){a=i,s.push(a);for(let e=1;e<r;e++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const i=Ml(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=Dl(n,e,i);n=a,c?s=s.add(Nl(d,t[l])):r=r.add(Nl(u,t[o]))}return Ll(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Ml(e,this.bits);for(let e=0;e<s.windows&&n!==Pl;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=Dl(n,e,s);if(n=i,!o){const e=t[a];r=r.add(c?e.negate():e)}}return Ll(n),r}getPrecomputes(e,t,n){let r=Ul.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Ul.set(t,r))),r}cached(e,t,n){const r=Fl(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=Fl(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Rl(t,this.bits),Vl.set(e,t),Ul.delete(e)}hasCache(e){return 1!==Fl(e)}}function ql(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,o=rl(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=sl(c),d=new Array(Number(u)+1).fill(a);let l=a;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(a);for(let t=0;t<i;t++){const s=r[t],i=Number(s>>BigInt(e)&u);d[i]=d[i].add(n[t])}let t=a;for(let e=d.length-1,n=a;e>0;e--)n=n.add(d[e]),t=t.add(n);if(l=l.add(t),0!==e)for(let e=0;e<c;e++)l=l.double()}return l}function zl(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=Il.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});il(e,t)}(t),t}return Al(e)}function Zl(e,t,n={}){if(!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Pl))throw new Error(`CURVE.${e} must be positive bigint`)}const r=zl(t.p,n.Fp),s=zl(t.n,n.Fn),i=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of i)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}const Wl=BigInt(0),Gl=BigInt(1),Hl=BigInt(2),Jl=BigInt(8);class Yl{constructor(e){this.ep=e}static fromBytes(e){throw new Error("fromBytes must be implemented by subclass")}static fromHex(e){throw new Error("fromHex must be implemented by subclass")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toRawBytes(){return this.toBytes()}toHex(){return vs(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}}function Xl(e,t,n){if("function"!=typeof t)throw new Error('"hash" function param is required');il(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:i,Fn:a}=e,o=a.ORDER,c=n.randomBytes||Rs,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Wd("phflag",n),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return a.create(e)}function h(e){return l(Yd(e))}function p(e){const{head:n,prefix:r,scalar:a}=function(e){const n=i.BYTES;e=el("private key",e,n);const r=el("hashed private key",t(e),2*n),s=u(r.slice(0,n));return{head:s,prefix:r.slice(n,2*n),scalar:h(s)}}(e),o=s.multiply(a),c=o.toBytes();return{head:n,prefix:r,scalar:a,point:o,pointBytes:c}}function f(e){return p(e).pointBytes}function g(e=Uint8Array.of(),...n){const s=Ps(...n);return h(t(d(s,el("context",e),!!r)))}const m={zip215:!0};s.precompute(8);const y=i.BYTES,b={secret:y,public:y,signature:2*y,seed:y};function w(e=c(b.seed)){return e}const v={getExtendedPublicKey:p,randomSecretKey:w,isValidSecretKey:function(e){try{return!!a.fromBytes(e,!1)}catch(e){return!1}},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},randomPrivateKey:w,toMontgomery(t){const{y:n}=e.fromBytes(t),r=32===y;if(!r&&57!==y)throw new Error("only defined for 25519 and 448");const s=r?i.div(Gl+n,Gl-n):i.div(n-Gl,n+Gl);return i.toBytes(s)},toMontgomeryPriv(e){is(e,y);const n=t(e.subarray(0,y));return u(n).subarray(0,y)},precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:f(t)}},getPublicKey:f,sign:function(e,t,n={}){e=el("message",e),r&&(e=r(e));const{prefix:a,scalar:c,pointBytes:u}=p(t),d=g(n.context,a,e),h=s.multiply(d).toBytes(),f=l(d+g(n.context,h,u,e)*c);nl("signature.s",f,Wl,o);const m=i.BYTES;return el("result",Ps(h,Qd(f,m)),2*m)},verify:function(t,n,a,o=m){const{context:c,zip215:u}=o,d=i.BYTES;t=el("signature",t,2*d),n=el("message",n),a=el("publicKey",a,d),void 0!==u&&Wd("zip215",u),r&&(n=r(n));const l=Yd(t.slice(d,2*d));let h,p,f;try{h=e.fromHex(a,u),p=e.fromHex(t.slice(0,d),u),f=s.multiplyUnsafe(l)}catch(e){return!1}if(!u&&h.isSmallOrder())return!1;const y=g(c,p.toBytes(),h.toBytes(),n);return p.add(h.multiplyUnsafe(y)).subtract(f).clearCofactor().is0()},utils:v,Point:e,info:{type:"edwards",lengths:b}})}function Ql(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:Al(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const{Fp:n,Fn:r}=Zl("edwards",e,t),{h:s,n:i}=e;il(t,{},{uvRatio:"function"});const a=Hl<<BigInt(8*r.BYTES)-Gl,o=e=>n.create(e),c=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:Wl}}});if(!function(e,t,n,r){const s=e.sqr(n),i=e.sqr(r),a=e.add(e.mul(t.a,s),i),o=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(a,o)}(n,e,e.Gx,e.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return nl("coordinate "+e,t,n?Gl:Wl,a),t}function d(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const l=al((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?Jl:n.inv(i));const c=o(r*t),u=o(s*t),d=n.mul(i,t);if(a)return{x:Wl,y:Gl};if(d!==Gl)throw new Error("invZ was invalid");return{x:c,y:u}}),h=al(t=>{const{a:n,d:r}=e;if(t.is0())throw new Error("bad point: ZERO");const{X:s,Y:i,Z:a,T:c}=t,u=o(s*s),d=o(i*i),l=o(a*a),h=o(l*l),p=o(u*n);if(o(l*o(p+d))!==o(h+o(r*o(u*d))))throw new Error("bad point: equation left != right (1)");if(o(s*i)!==o(a*c))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return $l(p,e)}static msm(e,t){return ql(p,r,e,t)}_setWindowSize(e){this.precompute(e)}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new p(t,n,Gl,o(t*n))}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(Hl),this}assertValidity(){h(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:s,Y:i,Z:a}=e,c=o(t*a),u=o(s*r),l=o(n*a),h=o(i*r);return c===u&&l===h}is0(){return this.equals(p.ZERO)}negate(){return new p(o(-this.X),this.Y,this.Z,o(-this.T))}double(){const{a:t}=e,{X:n,Y:r,Z:s}=this,i=o(n*n),a=o(r*r),c=o(Hl*o(s*s)),u=o(t*i),d=n+r,l=o(o(d*d)-i-a),h=u+a,f=h-c,g=u-a,m=o(l*f),y=o(h*g),b=o(l*g),w=o(f*h);return new p(m,y,w,b)}add(t){d(t);const{a:n,d:r}=e,{X:s,Y:i,Z:a,T:c}=this,{X:u,Y:l,Z:h,T:f}=t,g=o(s*u),m=o(i*l),y=o(c*r*f),b=o(a*h),w=o((s+i)*(u+l)-g-m),v=b-y,k=b+y,E=o(m-n*g),S=o(w*v),x=o(k*E),O=o(w*E),I=o(v*k);return new p(S,x,I,O)}subtract(e){return this.add(e.negate())}multiply(e){const t=e;nl("scalar",t,Gl,i);const{p:n,f:r}=f.cached(this,t,e=>$l(p,e));return $l(p,[n,r])[0]}multiplyUnsafe(e,t=p.ZERO){const n=e;return nl("scalar",n,Wl,i),n===Wl?p.ZERO:this.is0()||n===Gl?this:f.unsafe(this,n,e=>$l(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return f.unsafe(this,i).is0()}toAffine(e){return l(this,e)}clearCofactor(){return s===Gl?this:this.multiplyUnsafe(s)}static fromBytes(e,t=!1){return is(e),p.fromHex(e,t)}static fromHex(t,r=!1){const{d:s,a:i}=e,u=n.BYTES;t=el("pointHex",t,u),Wd("zip215",r);const d=t.slice(),l=t[u-1];d[u-1]=-129&l;const h=Yd(d),f=r?a:n.ORDER;nl("pointHex.y",h,Wl,f);const g=o(h*h),m=o(g-Gl),y=o(s*g-i);let{isValid:b,value:w}=c(m,y);if(!b)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&Gl)===Gl,k=!!(128&l);if(!r&&w===Wl&&k)throw new Error("Point.fromHex: x=0 and x_0=1");return k!==v&&(w=o(-w)),p.fromAffine({x:w,y:h})}toBytes(){const{x:e,y:t}=this.toAffine(),r=Qd(t,n.BYTES);return r[r.length-1]|=e&Gl?128:0,r}toRawBytes(){return this.toBytes()}toHex(){return vs(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}p.BASE=new p(e.Gx,e.Gy,Gl,o(e.Gx*e.Gy)),p.ZERO=new p(Wl,Gl,Gl,Wl),p.Fp=n,p.Fn=r;const f=new Kl(p,8*r.BYTES);return p}(t,n);return function(e,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:e})}(e,Xl(i,r,s))}const eh=BigInt(0),th=BigInt(1),nh=BigInt(2);BigInt(3);const rh=BigInt(5),sh=BigInt(8),ih={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:sh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ah(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const oh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ch(e,t){const n=ih.p,r=yl(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=ih.p,a=e*e%i*e%i,o=bl(a,nh,i)*a%i,c=bl(o,th,i)*e%i,u=bl(c,rh,i)*c%i,d=bl(u,t,i)*u%i,l=bl(d,n,i)*d%i,h=bl(l,r,i)*l%i,p=bl(h,s,i)*h%i,f=bl(p,s,i)*h%i,g=bl(f,t,i)*u%i;return{pow_p_5_8:bl(g,nh,i)*e%i,b2:a}}(e*yl(r*r*t,n)).pow_p_5_8;let i=yl(e*r*s,n);const a=yl(t*i*i,n),o=i,c=yl(i*oh,n),u=a===e,d=a===yl(-e,n),l=a===yl(-e*oh,n);return u&&(i=o),(d||l)&&(i=c),Ol(i,n)&&(i=yl(-i,n)),{isValid:u||d,value:i}}const uh=(()=>Al(ih.p,{isLE:!0}))(),dh=(()=>Al(ih.n,{isLE:!0}))(),lh=(()=>({...ih,Fp:uh,hash:Kd,adjustScalarBytes:ah,uvRatio:ch}))(),hh=(()=>Ql(lh))(),ph=oh,fh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),gh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),mh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),yh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),bh=e=>ch(th,e),wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),vh=e=>hh.CURVE.Fp.create(Yd(e)&wh);function kh(e){const{d:t}=hh.CURVE,n=hh.CURVE.Fp.ORDER,r=hh.CURVE.Fp.create,s=r(ph*e*e),i=r((s+th)*mh);let a=BigInt(-1);const o=r((a-t*s)*r(s+t));let{isValid:c,value:u}=ch(i,o),d=r(u*e);Ol(d,n)||(d=r(-d)),c||(u=d),c||(a=s);const l=r(a*(s-th)*yh-o),h=u*u,p=r((u+u)*o),f=r(l*fh),g=r(th-h),m=r(th+h);return new hh.Point(r(p*m),r(g*f),r(f*m),r(p*g))}class Eh extends Yl{constructor(e){super(e)}static fromAffine(e){return new Eh(hh.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Eh))throw new Error("RistrettoPoint expected")}init(e){return new Eh(e)}static hashToCurve(e){return function(e){is(e,64);const t=kh(vh(e.subarray(0,32))),n=kh(vh(e.subarray(32,64)));return new Eh(t.add(n))}(el("ristrettoHash",e,64))}static fromBytes(e){is(e,32);const{a:t,d:n}=hh.CURVE,r=uh.ORDER,s=uh.create,i=vh(e);if(!function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(Qd(i,32),e)||Ol(i,r))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(th+t*a),c=s(th-t*a),u=s(o*o),d=s(c*c),l=s(t*n*u-d),{isValid:h,value:p}=bh(s(l*d)),f=s(p*c),g=s(p*f*l);let m=s((i+i)*f);Ol(m,r)&&(m=s(-m));const y=s(o*g),b=s(m*y);if(!h||Ol(b,r)||y===eh)throw new Error("invalid ristretto255 encoding 2");return new Eh(new hh.Point(m,y,th,b))}static fromHex(e){return Eh.fromBytes(el("ristrettoHex",e,32))}static msm(e,t){return ql(Eh,hh.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep;const s=uh.ORDER,i=uh.create,a=i(i(n+t)*i(n-t)),o=i(e*t),c=i(o*o),{value:u}=bh(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*r);let p;if(Ol(r*h,s)){let n=i(t*ph),r=i(e*ph);e=n,t=r,p=i(d*gh)}else p=l;Ol(e*h,s)&&(t=i(-t));let f=i((n-t)*p);return Ol(f,s)&&(f=i(-f)),Qd(f,32)}equals(e){this.assertSame(e);const{X:t,Y:n}=this.ep,{X:r,Y:s}=e.ep,i=uh.create,a=i(t*s)===i(n*r),o=i(n*s)===i(t*r);return a||o}is0(){return this.equals(Eh.ZERO)}}function Sh(e,t){return Sr.IntentMessage(Sr.bytes(t.length)).serialize({intent:{scope:{[e]:!0},version:{V0:!0},appId:{Sui:!0}},value:t}).toBytes()}Eh.BASE=(()=>new Eh(hh.Point.BASE))(),Eh.ZERO=(()=>new Eh(hh.Point.ZERO))(),Eh.Fp=uh,Eh.Fn=dh;const xh={ED25519:0,Secp256k1:1,Secp256r1:2,MultiSig:3,ZkLogin:5,Passkey:6},Oh={ED25519:32,Secp256k1:33,Secp256r1:33,Passkey:33},Ih={0:"ED25519",1:"Secp256k1",2:"Secp256r1",3:"MultiSig",5:"ZkLogin",6:"Passkey"};class Th extends Bs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,as(e);const n=js(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),ds(s)}update(e){return os(this),this.iHash.update(e),this}digestInto(e){os(this),is(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:a}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _h=(e,t,n)=>new Th(e,t).update(n).digest();_h.create=(e,t)=>new Th(e,t);const Ah=(e,t)=>(e+(e>=0?t:-t)/$h)/t;function jh(e){void 0!==e.lowS&&Wd("lowS",e.lowS),void 0!==e.prehash&&Wd("prehash",e.prehash)}class Ch extends Error{constructor(e=""){super(e)}}const Ph={Err:Ch,_tlv:{encode:(e,t)=>{const{Err:n}=Ph;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=Gd(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Gd(s.length/2|128):"";return Gd(e)+i+s+t},decode(e,t){const{Err:n}=Ph;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++];let i=0;if(!!(128&s)){const e=127&s;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const a=t.subarray(r,r+e);if(a.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===a[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of a)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=s;const a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Ph;if(e<Bh)throw new t("integer: negative integers are not allowed");let n=Gd(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Ph;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Jd(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ph,s=el("signature",e),{v:i,l:a}=r.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=r.decode(2,i),{v:u,l:d}=r.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(o),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Ph,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Bh=BigInt(0),Nh=BigInt(1),$h=BigInt(2),Rh=BigInt(3),Mh=BigInt(4);function Dh(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=el("private key",t);try{r=e.fromBytes(s)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Uh(e,t={}){const{Fp:n,Fn:r}=Zl("weierstrass",e,t),{h:s,n:i}=e;il(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:a}=t;if(a&&(!n.is0(e.a)||"bigint"!=typeof a.beta||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function o(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const c=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),a=n.toBytes(s);if(Wd("isCompressed",r),r){o();return Ps(Vh(!n.isOdd(i)),a)}return Ps(Uint8Array.of(4),a,n.toBytes(i))},u=t.fromBytes||function(e){is(e);const t=n.BYTES,r=t+1,s=2*t+1,i=e.length,a=e[0],c=e.subarray(1);if(i!==r||2!==a&&3!==a){if(i===s&&4===a){const e=n.fromBytes(c.subarray(0*t,1*t)),r=n.fromBytes(c.subarray(1*t,2*t));if(!l(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${r} or uncompressed=${s}`)}{const e=n.fromBytes(c);if(!n.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=d(e);let r;try{r=n.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}o();return!(1&~a)!==n.isOdd(r)&&(r=n.neg(r)),{x:e,y:r}}},d=function(e,t,n){return function(r){const s=e.sqr(r),i=e.mul(s,r);return e.add(e.add(i,e.mul(r,t)),n)}}(n,e.a,e.b);function l(e,t){const r=n.sqr(t),s=d(e);return n.eql(r,s)}if(!l(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const h=n.mul(n.pow(e.a,Rh),Mh),p=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(h,p)))throw new Error("bad curve params: a or b");function f(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof v))throw new Error("ProjectivePoint expected")}function m(e){if(!a||!a.basises)throw new Error("no endo");return function(e,t,n){const[[r,s],[i,a]]=t,o=Ah(a*e,n),c=Ah(-s*e,n);let u=e-o*r-c*i,d=-o*s-c*a;const l=u<Bh,h=d<Bh;l&&(u=-u),h&&(d=-d);const p=sl(Math.ceil(rl(n)/2))+Nh;if(u<Bh||u>=p||d<Bh||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:h,k2:d}}(e,a.basises,r.ORDER)}const y=al((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const a=e.is0();null==t&&(t=a?n.ONE:n.inv(i));const o=n.mul(r,t),c=n.mul(s,t),u=n.mul(i,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:o,y:c}}),b=al(e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw new Error("bad point: x or y not field elements");if(!l(r,s))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function w(e,t,r,s,i){return r=new v(n.mul(r.X,e),r.Y,r.Z),t=Nl(s,t),r=Nl(i,r),t.add(r)}class v{constructor(e,t,n){this.X=f("x",e),this.Y=f("y",t,!0),this.Z=f("z",n),Object.freeze(this)}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof v)throw new Error("projective point not allowed");return n.is0(t)&&n.is0(r)?v.ZERO:new v(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ(e){return $l(v,e)}static fromBytes(e){return is(e),v.fromHex(e)}static fromHex(e){const t=v.fromAffine(u(el("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(Dh(r,e))}static msm(e,t){return ql(v,r,e,t)}_setWindowSize(e){this.precompute(e)}precompute(e=8,t=!0){return E.createCache(this,e),t||this.multiply(Rh),this}assertValidity(){b(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){g(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:a,Z:o}=e,c=n.eql(n.mul(t,o),n.mul(i,s)),u=n.eql(n.mul(r,o),n.mul(a,s));return c&&u}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:r}=e,s=n.mul(r,Rh),{X:i,Y:a,Z:o}=this;let c=n.ZERO,u=n.ZERO,d=n.ZERO,l=n.mul(i,i),h=n.mul(a,a),p=n.mul(o,o),f=n.mul(i,a);return f=n.add(f,f),d=n.mul(i,o),d=n.add(d,d),c=n.mul(t,d),u=n.mul(s,p),u=n.add(c,u),c=n.sub(h,u),u=n.add(h,u),u=n.mul(c,u),c=n.mul(f,c),d=n.mul(s,d),p=n.mul(t,p),f=n.sub(l,p),f=n.mul(t,f),f=n.add(f,d),d=n.add(l,l),l=n.add(d,l),l=n.add(l,p),l=n.mul(l,f),u=n.add(u,l),p=n.mul(a,o),p=n.add(p,p),l=n.mul(p,f),c=n.sub(c,l),d=n.mul(p,h),d=n.add(d,d),d=n.add(d,d),new v(c,u,d)}add(t){g(t);const{X:r,Y:s,Z:i}=this,{X:a,Y:o,Z:c}=t;let u=n.ZERO,d=n.ZERO,l=n.ZERO;const h=e.a,p=n.mul(e.b,Rh);let f=n.mul(r,a),m=n.mul(s,o),y=n.mul(i,c),b=n.add(r,s),w=n.add(a,o);b=n.mul(b,w),w=n.add(f,m),b=n.sub(b,w),w=n.add(r,i);let k=n.add(a,c);return w=n.mul(w,k),k=n.add(f,y),w=n.sub(w,k),k=n.add(s,i),u=n.add(o,c),k=n.mul(k,u),u=n.add(m,y),k=n.sub(k,u),l=n.mul(h,w),u=n.mul(p,y),l=n.add(u,l),u=n.sub(m,l),l=n.add(m,l),d=n.mul(u,l),m=n.add(f,f),m=n.add(m,f),y=n.mul(h,y),w=n.mul(p,w),m=n.add(m,y),y=n.sub(f,y),y=n.mul(h,y),w=n.add(w,y),f=n.mul(m,w),d=n.add(d,f),f=n.mul(k,w),u=n.mul(b,u),u=n.sub(u,f),f=n.mul(b,m),l=n.mul(k,l),l=n.add(l,f),new v(u,d,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(v.ZERO)}multiply(e){const{endo:n}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,i;const a=e=>E.cached(this,e,e=>$l(v,e));if(n){const{k1neg:t,k1:r,k2neg:o,k2:c}=m(e),{p:u,f:d}=a(r),{p:l,f:h}=a(c);i=d.add(h),s=w(n.beta,u,l,t,o)}else{const{p:t,f:n}=a(e);s=t,i=n}return $l(v,[s,i])[0]}multiplyUnsafe(e){const{endo:n}=t,s=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===Bh||s.is0())return v.ZERO;if(e===Nh)return s;if(E.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:r,k2neg:i,k2:a}=m(e),{p1:o,p2:c}=function(e,t,n,r){let s=t,i=e.ZERO,a=e.ZERO;for(;n>Pl||r>Pl;)n&Bl&&(i=i.add(s)),r&Bl&&(a=a.add(s)),s=s.double(),n>>=Bl,r>>=Bl;return{p1:i,p2:a}}(v,s,r,a);return w(n.beta,o,c,t,i)}return E.unsafe(s,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return y(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Nh||(e?e(v,this):E.unsafe(this,i).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Nh?this:e?e(v,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Wd("isCompressed",e),this.assertValidity(),c(v,this,e)}toRawBytes(e=!0){return this.toBytes(e)}toHex(e=!0){return vs(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}v.BASE=new v(e.Gx,e.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=r;const k=r.BITS,E=new Kl(v,t.endo?Math.ceil(k/2):k);return v}function Vh(e){return Uint8Array.of(e?2:3)}function Fh(e,t,n={}){as(t),il(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Rs,s=n.hmac||((e,...n)=>_h(t,e,Ps(...n))),{Fp:i,Fn:a}=e,{ORDER:o,BITS:c}=a,u=Cl(o),d={secret:a.BYTES,public:1+i.BYTES,publicUncompressed:1+2*i.BYTES,signature:2*a.BYTES,seed:u};function l(e){return e>o>>Nh}function h(e,t){if(!a.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..CURVE.n`)}class p{constructor(e,t,n){h("r",e),h("s",t),this.r=e,this.s=t,null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t="compact"){if("compact"===t){const t=a.BYTES;is(e,2*t);const n=e.subarray(0,t),r=e.subarray(t,2*t);return new p(a.fromBytes(n),a.fromBytes(r))}if("der"===t){is(e);const{r:t,s:n}=Ph.toSig(e);return new p(t,n)}throw new Error("invalid format")}static fromHex(e,t){return this.fromBytes(_s(e),t)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(o*$h<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+o:r;if(!i.isValid(u))throw new Error("recovery id 2 or 3 invalid");const d=i.toBytes(u),l=e.fromHex(Ps(Vh(!(1&c)),d)),h=a.inv(u),p=v(el("msgHash",t)),f=a.create(-p*h),g=a.create(s*h),m=e.BASE.multiplyUnsafe(f).add(l.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,a.neg(this.s),this.recovery):this}toBytes(e="compact"){if("compact"===e)return Ps(a.toBytes(this.r),a.toBytes(this.s));if("der"===e)return _s(Ph.hexFromSig(this));throw new Error("invalid format")}toHex(e){return vs(this.toBytes(e))}assertValidity(){}static fromCompact(e){return p.fromBytes(el("sig",e),"compact")}static fromDER(e){return p.fromBytes(el("sig",e),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return vs(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return vs(this.toBytes("compact"))}}function f(e){try{return!!Dh(a,e)}catch(e){return!1}}function g(e=r(u)){return function(e,t,n=!1){const r=e.length,s=jl(t),i=Cl(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=yl(n?Yd(e):Jd(e),t-cl)+cl;return n?Qd(a,s):Xd(a,s)}(e,o)}const m={isValidSecretKey:f,isValidPublicKey:function(t,n){try{const r=t.length;return(!0!==n||r===d.public)&&((!1!==n||r===d.publicUncompressed)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:g,isValidPrivateKey:f,randomPrivateKey:g,normPrivateKeyToScalar:e=>Dh(a,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};function y(t,n=!0){return e.BASE.multiply(Dh(a,t)).toBytes(n)}function b(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;if(a.allowedLengths||d.secret===d.public)return;const n=el("key",t).length;return n===d.public||n===d.publicUncompressed}const w=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Jd(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},v=n.bits2int_modN||function(e){return a.create(w(e))},k=sl(c);function E(e){return nl("num < 2^"+c,e,Bh,k),a.toBytes(e)}function S(n,s,i=x){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");let{lowS:o,prehash:c,extraEntropy:u}=i;null==o&&(o=!0),n=el("msgHash",n),jh(i),c&&(n=el("prehashed msgHash",t(n)));const h=v(n),f=Dh(a,s),g=[E(f),E(h)];if(null!=u&&!1!==u){const e=!0===u?r(d.secret):u;g.push(el("extraEntropy",e))}const m=Ps(...g),y=h;return{seed:m,k2sig:function(t){const n=w(t);if(!a.isValidNot0(n))return;const r=a.inv(n),s=e.BASE.multiply(n).toAffine(),i=a.create(s.x);if(i===Bh)return;const c=a.create(r*a.create(y+i*f));if(c===Bh)return;let u=(s.x===i?0:2)|Number(s.y&Nh),d=c;return o&&l(c)&&(d=function(e){return l(e)?a.neg(e):e}(c),u^=1),new p(i,d,u)}}}const x={lowS:n.lowS,prehash:!1},O={lowS:n.lowS,prehash:!1};return e.BASE.precompute(8),Object.freeze({keygen:function(e){const t=m.randomSecretKey(e);return{secretKey:t,publicKey:y(t)}},getPublicKey:y,sign:function(e,n,r=x){const{seed:i,k2sig:o}=S(e,n,r);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=r(e),a=r(e),o=0;const c=()=>{i.fill(1),a.fill(0),o=0},u=(...e)=>n(a,i,...e),d=(e=r(0))=>{a=u(s(0),e),i=u(),0!==e.length&&(a=u(s(1),e),i=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=u();const t=i.slice();n.push(t),e+=i.length}return Ps(...n)};return(e,t)=>{let n;for(c(),d(e);!(n=t(l()));)d();return c(),n}}(t.outputLen,a.BYTES,s)(i,o)},verify:function(n,r,s,i=O){const o=n;r=el("msgHash",r),s=el("publicKey",s),jh(i);const{lowS:c,prehash:u,format:d}=i;if("strict"in i)throw new Error("options.strict was renamed to lowS");let l,h;if(void 0===d){const e="string"==typeof o||rs(o),t=!e&&null!==o&&"object"==typeof o&&"bigint"==typeof o.r&&"bigint"==typeof o.s;if(!e&&!t)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(t)l=new p(o.r,o.s);else if(e){try{l=p.fromDER(o)}catch(e){if(!(e instanceof Ph.Err))throw e}if(!l)try{l=p.fromCompact(o)}catch(e){return!1}}}else if("compact"===d||"der"===d){if("string"!=typeof o&&!rs(o))throw new Error('"der" / "compact" format expects Uint8Array signature');l=p.fromBytes(el("sig",o),d)}else{if("js"!==d)throw new Error('format must be "compact", "der" or "js"');if(!(o instanceof p))throw new Error('"js" format expects Signature instance');l=o}if(!l)return!1;try{if(h=e.fromHex(s),c&&l.hasHighS())return!1;u&&(r=t(r));const{r:n,s:i}=l,o=v(r),d=a.inv(i),p=a.create(o*d),f=a.create(n*d),g=e.BASE.multiplyUnsafe(p).add(h.multiplyUnsafe(f));if(g.is0())return!1;return a.create(g.x)===n}catch(e){return!1}},getSharedSecret:function(t,n,r=!0){if(!0===b(t))throw new Error("first arg must be private key");if(!1===b(n))throw new Error("second arg must be public key");const s=Dh(a,t);return e.fromHex(n).multiply(s).toBytes(r)},utils:m,Point:e,Signature:p,info:{type:"weierstrass",lengths:d,publicKeyHasPrefix:!0}})}function Lh(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Al(t.n,{BITS:e.nBitLength,allowedLengths:r,modOnDecode:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function Kh(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=Lh(e);return function(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}(e,Fh(Uh(t,n),r,s))}function qh(e,t){const n=t=>Kh({...e,hash:t});return{...n(t),create:n}}const zh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Zh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Wh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Gh=Al(zh.p),Hh=Al(Zh.p),Jh=Al(Wh.p),Yh=qh({...zh,Fp:Gh,lowS:!1},Ld);qh({...Zh,Fp:Hh,lowS:!1},qd),qh({...Wh,Fp:Jh,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Kd);const Xh=Yh,Qh=Ld;function ep(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}class tp{equals(e){return ep(this.toRawBytes(),e.toRawBytes())}toBase64(){return xe(this.toRawBytes())}toString(){throw new Error("`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.")}toSuiPublicKey(){return xe(this.toSuiBytes())}verifyWithIntent(e,t,n){const r=Sh(n,e),s=pi(r,{dkLen:32});return this.verify(s,t)}verifyPersonalMessage(e,t){return this.verifyWithIntent(Sr.byteVector().serialize(e).toBytes(),t,"PersonalMessage")}verifyTransaction(e,t){return this.verifyWithIntent(e,t,"TransactionData")}verifyAddress(e){return this.toSuiAddress()===e}toSuiBytes(){const e=this.toRawBytes(),t=new Uint8Array(e.length+1);return t.set([this.flag()]),t.set(e,1),t}toSuiAddress(){return Qt(vs(pi(this.toSuiBytes(),{dkLen:32})).slice(0,64))}}function np(e){const t=Ee(e),n=Ih[t[0]];switch(n){case"ED25519":case"Secp256k1":case"Secp256r1":const r=Oh[n],s=t.slice(1,t.length-r);return{serializedSignature:e,signatureScheme:n,signature:s,publicKey:t.slice(1+s.length),bytes:t};default:throw new Error("Unsupported signature scheme")}}function rp(e){const t="string"==typeof e?Ee(e):e;if(t[0]!==xh.Passkey)throw new Error("Invalid signature scheme");const n=sr.parse(t.slice(1));return{signatureScheme:"Passkey",serializedSignature:xe(t),signature:t,authenticatorData:n.authenticatorData,clientDataJson:n.clientDataJson,userSignature:new Uint8Array(n.userSignature),publicKey:new Uint8Array(n.userSignature.slice(65))}}function sp(e,t){if(!Boolean(e))throw new Error(t)}(class extends tp{constructor(e){if(super(),"string"==typeof e?this.data=Ee(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return xh.Passkey}async verify(e,t){const n=rp(t),r=JSON.parse(n.clientDataJson);if("webauthn.get"!==r.type)return!1;if(!ep(e,Ee(r.challenge.replace(/-/g,"+").replace(/_/g,"/"))))return!1;const s=n.userSignature.slice(65);if(!ep(this.toRawBytes(),s))return!1;const i=new Uint8Array([...n.authenticatorData,...Qh(n.clientDataJson)]),a=n.userSignature.slice(1,65);return Xh.verify(a,Qh(i),s)}}).SIZE=33;const ip={Name:[],Document:["definitions"],OperationDefinition:["description","name","variableDefinitions","directives","selectionSet"],VariableDefinition:["description","variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["description","name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"],TypeCoordinate:["name"],MemberCoordinate:["name","memberName"],ArgumentCoordinate:["name","fieldName","argumentName"],DirectiveCoordinate:["name"],DirectiveArgumentCoordinate:["name","argumentName"]},ap=new Set(Object.keys(ip));function op(e){const t=null==e?void 0:e.kind;return"string"==typeof t&&ap.has(t)}var cp,up;function dp(e){return 9===e||32===e}!function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"}(cp||(cp={})),function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension",e.TYPE_COORDINATE="TypeCoordinate",e.MEMBER_COORDINATE="MemberCoordinate",e.ARGUMENT_COORDINATE="ArgumentCoordinate",e.DIRECTIVE_COORDINATE="DirectiveCoordinate",e.DIRECTIVE_ARGUMENT_COORDINATE="DirectiveArgumentCoordinate"}(up||(up={}));function lp(e){return hp(e,[])}function hp(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return function(e,t){if(null===e)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(function(e){return"function"==typeof e.toJSON}(e)){const t=e.toJSON();if(t!==e)return"string"==typeof t?t:hp(t,n)}else if(Array.isArray(e))return function(e,t){if(0===e.length)return"[]";if(t.length>2)return"[Array]";const n=Math.min(10,e.length),r=e.length-n,s=[];for(let r=0;r<n;++r)s.push(hp(e[r],t));1===r?s.push("... 1 more item"):r>1&&s.push(`... ${r} more items`);return"["+s.join(", ")+"]"}(e,n);return function(e,t){const n=Object.entries(e);if(0===n.length)return"{}";if(t.length>2)return"["+function(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if("Object"===t&&"function"==typeof e.constructor){const t=e.constructor.name;if("string"==typeof t&&""!==t)return t}return t}(e)+"]";const r=n.map(([e,n])=>e+": "+hp(n,t));return"{ "+r.join(", ")+" }"}(e,n)}(e,t);default:return String(e)}}const pp=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function fp(e){return gp[e.charCodeAt(0)]}const gp=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],mp=Object.freeze({});function yp(e,t){const n=e[t];return"object"==typeof n?n:"function"==typeof n?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function bp(e){return function(e,t,n=ip){const r=new Map;for(const e of Object.values(up))r.set(e,yp(t,e));let s,i,a,o=Array.isArray(e),c=[e],u=-1,d=[],l=e;const h=[],p=[];do{u++;const e=u===c.length,y=e&&0!==d.length;if(e){if(i=0===p.length?void 0:h[h.length-1],l=a,a=p.pop(),y)if(o){l=l.slice();let e=0;for(const[t,n]of d){const r=t-e;null===n?(l.splice(r,1),e++):l[r]=n}}else{l={...l};for(const[e,t]of d)l[e]=t}u=s.index,c=s.keys,d=s.edits,o=s.inArray,s=s.prev}else if(a){if(i=o?u:c[u],l=a[i],null==l)continue;h.push(i)}let b;if(!Array.isArray(l)){var f,g;op(l)||sp(!1,`Invalid AST Node: ${lp(l)}.`);const n=e?null===(f=r.get(l.kind))||void 0===f?void 0:f.leave:null===(g=r.get(l.kind))||void 0===g?void 0:g.enter;if(b=null==n?void 0:n.call(t,l,i,a,h,p),b===mp)break;if(!1===b){if(!e){h.pop();continue}}else if(void 0!==b&&(d.push([i,b]),!e)){if(!op(b)){h.pop();continue}l=b}}var m;void 0===b&&y&&d.push([i,l]),e?h.pop():(s={inArray:o,index:u,keys:c,edits:d,prev:s},o=Array.isArray(l),c=o?l:null!==(m=n[l.kind])&&void 0!==m?m:[],u=-1,d=[],a&&p.push(a),a=l)}while(void 0!==s);return 0!==d.length?d[d.length-1][1]:e}(e,wp)}const wp={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>vp(e.definitions,"\n\n")},OperationDefinition:{leave(e){const t=xp(e.variableDefinitions)?Ep("(\n",vp(e.variableDefinitions,"\n"),"\n)"):Ep("(",vp(e.variableDefinitions,", "),")"),n=Ep("",e.description,"\n")+vp([e.operation,vp([e.name,t]),vp(e.directives," ")]," ");return("query"===n?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r,description:s})=>Ep("",s,"\n")+e+": "+t+Ep(" = ",n)+Ep(" ",vp(r," "))},SelectionSet:{leave:({selections:e})=>kp(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:s}){const i=Ep("",e,": ")+t;let a=i+Ep("(",vp(n,", "),")");return a.length>80&&(a=i+Ep("(\n",Sp(vp(n,"\n")),"\n)")),vp([a,vp(r," "),s]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+Ep(" ",vp(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>vp(["...",Ep("on ",e),vp(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:s,description:i})=>Ep("",i,"\n")+`fragment ${e}${Ep("(",vp(n,", "),")")} `+`on ${t} ${Ep("",vp(r," ")," ")}`+s},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?function(e,t){const n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),s=1===r.length,i=r.length>1&&r.slice(1).every(e=>0===e.length||dp(e.charCodeAt(0))),a=n.endsWith('\\"""'),o=e.endsWith('"')&&!a,c=e.endsWith("\\"),u=o||c,d=!(null!=t&&t.minimize)&&(!s||e.length>70||u||i||a);let l="";const h=s&&dp(e.charCodeAt(0));return(d&&!h||i)&&(l+="\n"),l+=n,(d||u)&&(l+="\n"),'"""'+l+'"""'}(e):`"${e.replace(pp,fp)}"`},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+vp(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+vp(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+Ep("(",vp(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>Ep("",e,"\n")+vp(["schema",vp(t," "),kp(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>Ep("",e,"\n")+vp(["scalar",t,vp(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>Ep("",e,"\n")+vp(["type",t,Ep("implements ",vp(n," & ")),vp(r," "),kp(s)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:s})=>Ep("",e,"\n")+t+(xp(n)?Ep("(\n",Sp(vp(n,"\n")),"\n)"):Ep("(",vp(n,", "),")"))+": "+r+Ep(" ",vp(s," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:s})=>Ep("",e,"\n")+vp([t+": "+n,Ep("= ",r),vp(s," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>Ep("",e,"\n")+vp(["interface",t,Ep("implements ",vp(n," & ")),vp(r," "),kp(s)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>Ep("",e,"\n")+vp(["union",t,vp(n," "),Ep("= ",vp(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>Ep("",e,"\n")+vp(["enum",t,vp(n," "),kp(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>Ep("",e,"\n")+vp([t,vp(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>Ep("",e,"\n")+vp(["input",t,vp(n," "),kp(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:s})=>Ep("",e,"\n")+"directive @"+t+(xp(n)?Ep("(\n",Sp(vp(n,"\n")),"\n)"):Ep("(",vp(n,", "),")"))+(r?" repeatable":"")+" on "+vp(s," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>vp(["extend schema",vp(e," "),kp(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>vp(["extend scalar",e,vp(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>vp(["extend type",e,Ep("implements ",vp(t," & ")),vp(n," "),kp(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>vp(["extend interface",e,Ep("implements ",vp(t," & ")),vp(n," "),kp(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>vp(["extend union",e,vp(t," "),Ep("= ",vp(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>vp(["extend enum",e,vp(t," "),kp(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>vp(["extend input",e,vp(t," "),kp(n)]," ")},TypeCoordinate:{leave:({name:e})=>e},MemberCoordinate:{leave:({name:e,memberName:t})=>vp([e,Ep(".",t)])},ArgumentCoordinate:{leave:({name:e,fieldName:t,argumentName:n})=>vp([e,Ep(".",t),Ep("(",n,":)")])},DirectiveCoordinate:{leave:({name:e})=>vp(["@",e])},DirectiveArgumentCoordinate:{leave:({name:e,argumentName:t})=>vp(["@",e,Ep("(",t,":)")])}};function vp(e,t=""){var n;return null!==(n=null==e?void 0:e.filter(e=>e).join(t))&&void 0!==n?n:""}function kp(e){return Ep("{\n",Sp(vp(e,"\n")),"\n}")}function Ep(e,t,n=""){return null!=t&&""!==t?e+t+n:""}function Sp(e){return Ep(" ",e.replace(/\n/g,"\n "))}function xp(e){var t;return null!==(t=null==e?void 0:e.some(e=>e.includes("\n")))&&void 0!==t&&t}var Op=(e=>(e.PersonalMessage="PERSONAL_MESSAGE",e.TransactionData="TRANSACTION_DATA",e))(Op||{});class Ip extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t}toString(){return this.value}}new Ip("\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}\n ",{fragmentName:"OBJECT_OWNER_FIELDS"}),new Ip("\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n asMoveObject {\n contents {\n bcs\n type {\n repr\n }\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}",{fragmentName:"OBJECT_FIELDS"}),new Ip("\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n contents {\n bcs\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}",{fragmentName:"MOVE_OBJECT_FIELDS"}),new Ip("\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}\n ",{fragmentName:"TRANSACTION_FIELDS"});const Tp=new Ip("\n query getAllBalances($owner: SuiAddress!, $limit: Int, $cursor: String) {\n address(address: $owner) {\n balances(first: $limit, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n coinType {\n repr\n }\n totalBalance\n }\n }\n }\n}\n "),_p=new Ip('\n query getBalance($owner: SuiAddress!, $coinType: String! = "0x2::sui::SUI") {\n address(address: $owner) {\n balance(coinType: $coinType) {\n coinType {\n repr\n }\n totalBalance\n }\n }\n}\n '),Ap=new Ip('\n query getCoins($owner: SuiAddress!, $first: Int, $cursor: String, $type: String! = "0x2::coin::Coin<0x2::sui::SUI>") {\n address(address: $owner) {\n address\n objects(first: $first, after: $cursor, filter: {type: $type}) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n contents {\n bcs\n json\n type {\n repr\n }\n }\n address\n version\n digest\n previousTransaction {\n digest\n }\n }\n }\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}'),jp=new Ip("\n query getDynamicFields($parentId: SuiAddress!, $first: Int, $cursor: String) {\n address(address: $parentId) {\n dynamicFields(first: $first, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n name {\n bcs\n type {\n repr\n }\n }\n value {\n __typename\n ... on MoveValue {\n type {\n repr\n }\n }\n ... on MoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n}\n "),Cp=new Ip("\n query getMoveFunction($package: SuiAddress!, $module: String!, $function: String!) {\n package(address: $package) {\n module(name: $module) {\n function(name: $function) {\n name\n visibility\n isEntry\n typeParameters {\n constraints\n }\n parameters {\n signature\n }\n return {\n signature\n }\n }\n }\n }\n}\n "),Pp=new Ip("\n query getReferenceGasPrice {\n epoch {\n referenceGasPrice\n }\n}\n "),Bp=new Ip("\n query defaultSuinsName($address: SuiAddress!) {\n address(address: $address) {\n defaultSuinsName\n }\n}\n "),Np=new Ip("\n query getOwnedObjects($owner: SuiAddress!, $limit: Int, $cursor: String, $filter: ObjectFilter) {\n address(address: $owner) {\n objects(first: $limit, after: $cursor, filter: $filter) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n ...MOVE_OBJECT_FIELDS\n }\n }\n }\n}\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n contents {\n bcs\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}"),$p=new Ip("\n query multiGetObjects($objectKeys: [ObjectKey!]!) {\n multiGetObjects(keys: $objectKeys) {\n ...OBJECT_FIELDS\n }\n}\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n asMoveObject {\n contents {\n bcs\n type {\n repr\n }\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}"),Rp=new Ip("\n query simulateTransaction($transaction: JSON!) {\n simulateTransaction(transaction: $transaction) {\n error\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),Mp=new Ip("\n mutation executeTransaction($transactionDataBcs: Base64!, $signatures: [Base64!]!) {\n executeTransaction(\n transactionDataBcs: $transactionDataBcs\n signatures: $signatures\n ) {\n errors\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),Dp=new Ip("\n query getTransactionBlock($digest: String!) {\n transaction(digest: $digest) {\n ...TRANSACTION_FIELDS\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionBcs\n signatures {\n signatureBytes\n }\n effects {\n effectsBcs\n epoch {\n epochId\n }\n unchangedConsensusObjects {\n nodes {\n __typename\n ... on ConsensusObjectRead {\n object {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n objectChanges {\n nodes {\n address\n inputState {\n version\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n outputState {\n asMoveObject {\n address\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChanges(first: 50) {\n pageInfo {\n hasNextPage\n }\n nodes {\n owner {\n address\n }\n coinType {\n repr\n }\n amount\n }\n }\n }\n}"),Up=new Ip("\n query verifyZkLoginSignature($bytes: Base64!, $signature: Base64!, $intentScope: ZkLoginIntentScope!, $author: SuiAddress!) {\n verifyZkLoginSignature(\n bytes: $bytes\n signature: $signature\n intentScope: $intentScope\n author: $author\n ) {\n success\n error\n }\n}\n ");var Vp,Fp,Lp,Kp=e=>{throw TypeError(e)},qp=(e,t,n)=>t.has(e)||Kp("Cannot "+n),zp=(e,t,n)=>t.has(e)?Kp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Zp=(e,t,n)=>(qp(e,t,"access private method"),n);class Wp extends $a{constructor({graphqlClient:e,mvr:t}){var n,r,s,i;super({network:e.network,base:e,mvr:t}),zp(this,Fp),zp(this,Vp),s=e,qp(n=this,r=Vp,"write to private field"),i?i.call(n,s):r.set(n,s)}async getObjects(e){const t=Te(e.objectIds,50),n=[];for(const e of t){const t=await Zp(this,Fp,Lp).call(this,{query:$p,variables:{objectKeys:e.map(e=>({address:e}))}},e=>e.multiGetObjects);n.push(...e.map(e=>Qt(e)).map(e=>t.find(t=>t?.address===e)??new Ma("notFound",`Object ${e} not found`)).map(e=>e instanceof Ma?e:{id:e.address,version:e.version?.toString(),digest:e.digest,owner:Hp(e.owner),type:e.asMoveObject?.contents?.type?.repr,content:Promise.resolve(e.asMoveObject?.contents?.bcs?Ee(e.asMoveObject.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}return{objects:n}}async getOwnedObjects(e){const t=await Zp(this,Fp,Lp).call(this,{query:Np,variables:{owner:e.address,limit:e.limit,cursor:e.cursor,filter:e.type?{type:(await this.mvr.resolveType({type:e.type})).type}:void 0}},e=>e.address?.objects);return{objects:t.nodes.map(e=>({id:e.address,version:e.version?.toString(),digest:e.digest,owner:Hp(e.owner),type:e.contents?.type?.repr,content:Promise.resolve(e.contents?.bcs?Ee(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null})),hasNextPage:t.pageInfo.hasNextPage,cursor:t.pageInfo.endCursor??null}}async getCoins(e){const t=await Zp(this,Fp,Lp).call(this,{query:Ap,variables:{owner:e.address,cursor:e.cursor,first:e.limit,type:`0x2::coin::Coin<${(await this.mvr.resolveType({type:e.coinType})).type}>`}},e=>e.address?.objects);return{cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage,objects:t.nodes.map(e=>({id:e.address,version:e.version?.toString(),digest:e.digest,owner:Hp(e.owner),type:e.contents?.type?.repr,balance:e.contents?.json?.balance,content:Promise.resolve(e.contents?.bcs?Ee(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}}async getBalance(e){const t=await Zp(this,Fp,Lp).call(this,{query:_p,variables:{owner:e.address,type:(await this.mvr.resolveType({type:e.coinType})).type}},e=>e.address?.balance);return{balance:{coinType:t.coinType?.repr,balance:t.totalBalance}}}async getAllBalances(e){const t=await Zp(this,Fp,Lp).call(this,{query:Tp,variables:{owner:e.address}},e=>e.address?.balances);return{cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage,balances:t.nodes.map(e=>({coinType:e.coinType?.repr,balance:e.totalBalance}))}}async getTransaction(e){return{transaction:Jp(await Zp(this,Fp,Lp).call(this,{query:Dp,variables:{digest:e.digest}},e=>e.transaction))}}async executeTransaction(e){const t=await Zp(this,Fp,Lp).call(this,{query:Mp,variables:{transactionDataBcs:xe(e.transaction),signatures:e.signatures}},e=>e.executeTransaction);if(t.errors){if(1===t.errors.length)throw new Error(t.errors[0]);throw new AggregateError(t.errors.map(e=>new Error(e)))}return{transaction:Jp(t.effects?.transaction)}}async dryRunTransaction(e){const t=await Zp(this,Fp,Lp).call(this,{query:Rp,variables:{transaction:{bcs:{value:xe(e.transaction)}}}},e=>e.simulateTransaction);if(t.error)throw new Error(t.error);return{transaction:Jp(t.effects?.transaction)}}async getReferenceGasPrice(){return{referenceGasPrice:await Zp(this,Fp,Lp).call(this,{query:Pp},e=>e.epoch?.referenceGasPrice)}}async getDynamicFields(e){const t=await Zp(this,Fp,Lp).call(this,{query:jp,variables:{parentId:e.parentId}},e=>e.address?.dynamicFields);return{dynamicFields:t.nodes.map(t=>{const n="MoveObject"===t.value?.__typename?t.value.contents?.type?.repr:t.value?.type?.repr;return{id:fi(e.parentId,t.name?.type?.repr,Ee(t.name?.bcs)),type:Xt("MoveObject"===t.value?.__typename?`0x2::dynamic_field::Field<0x2::dynamic_object_field::Wrapper<${t.name?.type?.repr}>,0x2::object::ID>`:`0x2::dynamic_field::Field<${t.name?.type?.repr},${n}>`),name:{type:t.name?.type?.repr,bcs:Ee(t.name?.bcs)},valueType:n}}),cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage}}async verifyZkLoginSignature(e){const t="TransactionData"===e.intentScope?Op.TransactionData:Op.PersonalMessage,n=await Zp(this,Fp,Lp).call(this,{query:Up,variables:{bytes:e.bytes,signature:e.signature,intentScope:t,author:e.author}},e=>e.verifyZkLoginSignature);return{success:n.success??!1,errors:n.error?[n.error]:[]}}async defaultNameServiceName(e){return{data:{name:await Zp(this,Fp,Lp).call(this,{query:Bp,signal:e.signal,variables:{address:e.address}},e=>e.address?.defaultSuinsName??null)}}}async getMoveFunction(e){const t=await Zp(this,Fp,Lp).call(this,{query:Cp,variables:{package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name}},e=>e.package?.module?.function);let n="unknown";switch(t.visibility){case"PUBLIC":n="public";break;case"PRIVATE":n="private";break;case"FRIEND":n="friend"}return{function:{packageId:Qt(e.packageId),moduleName:e.moduleName,name:t.name,visibility:n,isEntry:t.isEntry??!1,typeParameters:t.typeParameters?.map(({constraints:e})=>({isPhantom:!1,constraints:e.map(e=>{switch(e){case"COPY":return"copy";case"DROP":return"drop";case"STORE":return"store";case"KEY":return"key";default:return"unknown"}})??[]}))??[],parameters:t.parameters?.map(e=>Yp(e.signature))??[],returns:t.return?.map(({signature:e})=>Yp(e))??[]}}}resolveTransactionPlugin(){throw new Error("GraphQL client does not support transaction resolution yet")}}Vp=new WeakMap,Fp=new WeakSet,Lp=async function(e,t){const{data:n,errors:r}=await(s=this,i=Vp,qp(s,i,"read from private field"),a?a.call(s):i.get(s)).query(e);var s,i,a;!function(e){if(!e||0===e.length)return;const t=e.map(e=>new Gp(e));if(1===t.length)throw t[0];throw new AggregateError(t)}(r);const o=n&&(t?t(n):n);if(null==o)throw new Error("Missing response data");return o};class Gp extends Error{constructor(e){super(e.message),this.locations=e.locations}}function Hp(e){switch(e.__typename){case"AddressOwner":return{$kind:"AddressOwner",AddressOwner:e.address?.address};case"ConsensusAddressOwner":return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:e?.address?.address,startVersion:String(e.startVersion)}};case"ObjectOwner":return{$kind:"ObjectOwner",ObjectOwner:e.address?.address};case"Immutable":return{$kind:"Immutable",Immutable:!0};case"Shared":return{$kind:"Shared",Shared:{initialSharedVersion:String(e.initialSharedVersion)}}}}function Jp(e){const t={};if(e.effects?.unchangedConsensusObjects?.nodes.forEach(e=>{if("ConsensusObjectRead"===e.__typename){const n=e.object?.asMoveObject?.contents?.type?.repr,r=e.object?.asMoveObject?.address;n&&r&&(t[r]=n)}}),e.effects?.objectChanges?.nodes.forEach(e=>{const n=e.address,r=e.inputState?.asMoveObject?.contents?.type?.repr??e.outputState?.asMoveObject?.contents?.type?.repr;n&&r&&(t[n]=r)}),e.effects?.balanceChanges?.pageInfo.hasNextPage)throw new Error("Pagination for balance changes is not supported");return{digest:e.digest,effects:Ua(Ee(e.effects?.effectsBcs)),epoch:e.effects?.epoch?.epochId?.toString()??null,objectTypes:Promise.resolve(t),transaction:Da(Ee(e.transactionBcs)),signatures:e.signatures.map(e=>e.signatureBytes),balanceChanges:e.effects?.balanceChanges?.nodes.map(e=>({coinType:e?.coinType?.repr,address:e.owner?.address,amount:e.amount}))??[]}}function Yp(e){let t=null;return"&"===e.ref?t="immutable":"&mut"===e.ref&&(t="mutable"),{reference:t,body:Xp(e.body)}}function Xp(e){switch(e){case"address":return{$kind:"address"};case"bool":return{$kind:"bool"};case"u8":return{$kind:"u8"};case"u16":return{$kind:"u16"};case"u32":return{$kind:"u32"};case"u64":return{$kind:"u64"};case"u128":return{$kind:"u128"};case"u256":return{$kind:"u256"}}if("string"==typeof e)throw new Error(`Unknown type: ${e}`);if("vector"in e)return{$kind:"vector",vector:Xp(e.vector)};if("datatype"in e)return{$kind:"datatype",datatype:{typeName:`${Qt(e.datatype.package)}::${e.datatype.module}::${e.datatype.type}`,typeParameters:e.datatype.typeParameters.map(e=>Xp(e))}};if("typeParameter"in e)return{$kind:"typeParameter",index:e.typeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}var Qp,ef,tf,nf,rf=e=>{throw TypeError(e)},sf=(e,t,n)=>t.has(e)||rf("Cannot "+n),af=(e,t,n)=>(sf(e,t,"read from private field"),n?n.call(e):t.get(e)),of=(e,t,n)=>t.has(e)?rf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),cf=(e,t,n,r)=>(sf(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class uf extends Error{}class df extends pt{constructor({url:e,fetch:t=fetch,headers:n={},queries:r={},network:s="unknown",mvr:i}){super({network:s}),of(this,Qp),of(this,ef),of(this,tf),of(this,nf),cf(this,Qp,e),cf(this,ef,r),cf(this,tf,n),cf(this,nf,(...e)=>t(...e)),this.core=new Wp({graphqlClient:this,mvr:i})}async query(e){const t=await af(this,nf).call(this,af(this,Qp),{method:"POST",headers:{"Content-Type":"application/json",...af(this,tf)},body:JSON.stringify({query:"string"==typeof e.query||e.query instanceof String?String(e.query):bp(e.query),variables:e.variables,extensions:e.extensions,operationName:e.operationName}),signal:e.signal});if(!t.ok)throw new uf(`GraphQL request failed: ${t.statusText} (${t.status})`);return await t.json()}async execute(e,t){return this.query({...t,query:af(this,ef)[e]})}}function lf(e,t){return _s(e.toString(16).padStart(2*t,"0").slice(2*-t))}function hf(e,t){const n=lf(e,t),r=function(e){for(let t=0;t<e.length;t++)if(0!==e[t])return t;return-1}(n);return-1===r?new Uint8Array([0]):n.slice(r)}function pf(e){if(1!==e.length)throw new Error("Invalid base64Url character: "+e);const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(e);if(-1===t)throw new Error("Invalid base64Url character: "+e);const n=t.toString(2).padStart(6,"0");return Array.from(n).map(Number)}function ff(e,t){if(e.length<2)throw new Error(`Input (s = ${e}) is not tightly packed because s.length < 2`);let n=function(e){let t=[];for(let n=0;n<e.length;n++){const r=pf(e.charAt(n));t=t.concat(r)}return t}(e);const r=t%4;if(0===r);else if(1===r)n=n.slice(2);else{if(2!==r)throw new Error(`Input (s = ${e}) is not tightly packed because i%4 = 3 (i = ${t}))`);n=n.slice(4)}const s=(t+e.length-1)%4;if(3===s);else if(2===s)n=n.slice(0,n.length-2);else{if(1!==s)throw new Error(`Input (s = ${e}) is not tightly packed because (i + s.length - 1)%4 = 0 (i = ${t}))`);n=n.slice(0,n.length-4)}if(n.length%8!=0)throw new Error("We should never reach here...");const i=new Uint8Array(Math.floor(n.length/8));let a=0;for(let e=0;e<n.length;e+=8){const t=n.slice(e,e+8),r=parseInt(t.join(""),2);i[a++]=r}return(new TextDecoder).decode(i)}function gf(e,t){const n=ff(e.value,e.indexMod4),[r,s]=function(e){if("}"!==e.slice(-1)&&","!==e.slice(-1))throw new Error("Invalid claim");const t=JSON.parse("{"+e.slice(0,-1)+"}");if(1!==Object.keys(t).length)throw new Error("Invalid claim");const n=Object.keys(t)[0];return[n,t[n]]}(n);if(r!==t)throw new Error(`Invalid field name: found ${r} expected ${t}`);return s}Qp=new WeakMap,ef=new WeakMap,tf=new WeakMap,nf=new WeakMap;const mf=st.struct("ZkLoginSignature",{inputs:st.struct("ZkLoginSignatureInputs",{proofPoints:st.struct("ZkLoginSignatureInputsProofPoints",{a:st.vector(st.string()),b:st.vector(st.vector(st.string())),c:st.vector(st.string())}),issBase64Details:st.struct("ZkLoginSignatureInputsClaim",{value:st.string(),indexMod4:st.u8()}),headerBase64:st.string(),addressSeed:st.string()}),maxEpoch:st.u64(),userSignature:st.byteVector()});var yf,bf,wf,vf,kf,Ef=e=>{throw TypeError(e)},Sf=(e,t,n)=>t.has(e)||Ef("Cannot "+n),xf=(e,t,n)=>(Sf(e,t,"read from private field"),n?n.call(e):t.get(e)),Of=(e,t,n)=>t.has(e)?Ef("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),If=(e,t,n,r)=>(Sf(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Tf=(e,t,n)=>(Sf(e,t,"access private method"),n);yf=new WeakMap,bf=new WeakMap,wf=new WeakMap,vf=new WeakSet,kf=function(){const e=jf(xf(this,yf),!0),t=new Uint8Array(e.length+1);return t[0]=this.flag(),t.set(e,1),Qt(vs(pi(t,{dkLen:32})).slice(0,64))};let _f=class e extends tp{constructor(e,{client:t}={}){super(),Of(this,vf),Of(this,yf),Of(this,bf),Of(this,wf),If(this,bf,t),"string"==typeof e?If(this,yf,Ee(e)):e instanceof Uint8Array?If(this,yf,e):If(this,yf,Uint8Array.from(e)),If(this,wf,xf(this,yf).length!==xf(this,yf)[0]+1+32),xf(this,wf)&&If(this,yf,jf(xf(this,yf)))}static fromBytes(t,{client:n,address:r,legacyAddress:s}={}){let i;if(!0===s?i=new e(jf(t,!0),{client:n}):!1===s?i=new e(jf(t,!1),{client:n}):r?(i=new e(jf(t,!1),{client:n}),i.toSuiAddress()!==r&&(i=new e(jf(t,!0),{client:n}))):i=new e(t,{client:n}),r&&i.toSuiAddress()!==r)throw new Error("Public key bytes do not match the provided address");return i}static fromProof(e,t){const{issBase64Details:n,addressSeed:r}=t,s=gf(n,"iss"),i=Af(BigInt(r),s,{legacyAddress:!0});if(i.toSuiAddress()===e)return i;const a=Af(BigInt(r),s,{legacyAddress:!1});if(a.toSuiAddress()!==e)throw new Error("Proof does not match address");return a}equals(e){return super.equals(e)}toSuiAddress(){return xf(this,wf)?Tf(this,vf,kf).call(this):super.toSuiAddress()}toRawBytes(){return xf(this,yf)}flag(){return xh.ZkLogin}async verify(e,t){throw Error("does not support")}verifyPersonalMessage(t,n){const r=Pf(n);return Cf({address:new e(r.publicKey).toSuiAddress(),bytes:xe(t),signature:r.serializedSignature,intentScope:"PersonalMessage",client:xf(this,bf)})}verifyTransaction(t,n){const r=Pf(n);return Cf({address:new e(r.publicKey).toSuiAddress(),bytes:xe(t),signature:r.serializedSignature,intentScope:"TransactionData",client:xf(this,bf)})}verifyAddress(e){return e===super.toSuiAddress()||e===Tf(this,vf,kf).call(this)}};function Af(e,t,n){const r=n?.legacyAddress?hf(e,32):lf(e,32),s=(new TextEncoder).encode(function(e){return"accounts.google.com"===e?"https://accounts.google.com":e}(t)),i=new Uint8Array(1+s.length+r.length);return i.set([s.length],0),i.set(s,1),i.set(r,1+s.length),new _f(i,n)}function jf(e,t=!1){const n=e[0]+1,r=BigInt(`0x${Ie(e.slice(n))}`),s=t?hf(r,32):lf(r,32),i=new Uint8Array(n+s.length);return i.set(e.slice(0,n),0),i.set(s,n),i}async function Cf({address:e,bytes:t,signature:n,intentScope:r,client:s=new df({url:"https://graphql.mainnet.sui.io/graphql"})}){const i=await s.core.verifyZkLoginSignature({bytes:t,signature:n,intentScope:r,author:e});return!0===i.success&&0===i.errors.length}function Pf(e){const t="string"==typeof e?Ee(e):e;if(t[0]!==xh.ZkLogin)throw new Error("Invalid signature scheme");const n=t.slice(1),{inputs:r,maxEpoch:s,userSignature:i}=function(e){return mf.parse("string"==typeof e?Ee(e):e)}(n),{issBase64Details:a,addressSeed:o}=r,c=gf(a,"iss"),u=Af(BigInt(o),c);return{serializedSignature:xe(t),signatureScheme:"ZkLogin",zkLogin:{inputs:r,maxEpoch:s,userSignature:i,iss:c,addressSeed:BigInt(o)},signature:t,publicKey:u.toRawBytes()}}function Bf(e){const t=Ee(e),n=Ih[t[0]];switch(n){case"Passkey":return rp(e);case"MultiSig":return{serializedSignature:e,signatureScheme:n,multisig:Sr.MultiSig.parse(t.slice(1)),bytes:t,signature:void 0};case"ZkLogin":return Pf(e);case"ED25519":case"Secp256k1":case"Secp256r1":return np(e);default:throw new Error("Unsupported signature scheme")}}const Nf="suiprivkey";class $f{async signWithIntent(e,t){const n=Sh(t,e),r=pi(n,{dkLen:32});return{signature:function({signature:e,signatureScheme:t,publicKey:n}){if(!n)throw new Error("`publicKey` is required");const r=n.toRawBytes(),s=new Uint8Array(1+e.length+r.length);return s.set([xh[t]]),s.set(e,1),s.set(r,1+e.length),xe(s)}({signature:await this.sign(r),signatureScheme:this.getKeyScheme(),publicKey:this.getPublicKey()}),bytes:xe(e)}}async signTransaction(e){return this.signWithIntent(e,"TransactionData")}async signPersonalMessage(e){const{signature:t}=await this.signWithIntent(st.byteVector().serialize(e).toBytes(),"PersonalMessage");return{bytes:xe(e),signature:t}}async signAndExecuteTransaction({transaction:e,client:t}){const n=await e.build({client:t}),{signature:r}=await this.signTransaction(n);return(await t.core.executeTransaction({transaction:n,signatures:[r]})).transaction}toSuiAddress(){return this.getPublicKey().toSuiAddress()}}class Rf extends $f{}function Mf(e){const{prefix:t,words:n}=we.decode(e);if(t!==Nf)throw new Error("invalid private key prefix");const r=new Uint8Array(we.fromWords(n)),s=r.slice(1),i=Ih[r[0]];return{scheme:i,schema:i,secretKey:s}}function Df(e,t){if(32!==e.length)throw new Error("Invalid bytes length");const n=xh[t],r=new Uint8Array(e.length+1);return r.set([n]),r.set(e,1),we.encode(Nf,we.toWords(r))}function Uf(e,t,n,r){as(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},r),{c:i,dkLen:a,asyncTick:o}=s;if(ss(i),ss(a),ss(o),i<1)throw new Error("iterations (c) should be >= 1");const c=Cs(t),u=Cs(n),d=new Uint8Array(a),l=_h.create(e,c),h=l._cloneInto().update(u);return{c:i,dkLen:a,asyncTick:o,DK:d,PRF:l,PRFSalt:h}}function Vf(e,t,n,r){const{c:s,dkLen:i,DK:a,PRF:o,PRFSalt:c}=Uf(e,t,n,r);let u;const d=new Uint8Array(4),l=ls(d),h=new Uint8Array(o.outputLen);for(let e=1,t=0;t<i;e++,t+=o.outputLen){const n=a.subarray(t,t+o.outputLen);l.setInt32(0,e,!1),(u=c._cloneInto(u)).update(d).digestInto(h),n.set(h.subarray(0,n.length));for(let e=1;e<s;e++){o._cloneInto(u).update(h).digestInto(h);for(let e=0;e<n.length;e++)n[e]^=h[e]}}return function(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),ds(s),n}(o,c,a,u,h)}function Ff(e){if("string"!=typeof e)throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function Lf(e,t=""){return Vf(Kd,function(e){const t=Ff(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}(e).nfkd,(e=>Ff("mnemonic"+e))(t),{c:2048,dkLen:64})}function Kf(e){return!!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(e)}function qf(e){return!!new RegExp("^m\\/(54|74)'\\/784'\\/[0-9]+'\\/[0-9]+\\/[0-9]+$").test(e)}function zf(e){return Lf(e,"")}const Zf=Kd,Wf=new RegExp("^m(\\/[0-9]+')+$"),Gf=e=>e.replace("'",""),Hf=(e,t,n=2147483648)=>{if(!(e=>!!Wf.test(e)&&!e.split("/").slice(1).map(Gf).some(isNaN))(e))throw new Error("Invalid derivation path");const{key:r,chainCode:s}=(e=>{const t=_h.create(Zf,"ed25519 seed").update(Oe(e)).digest();return{key:t.slice(0,32),chainCode:t.slice(32)}})(t);return e.split("/").slice(1).map(Gf).map(e=>parseInt(e,10)).reduce((e,t)=>(({key:e,chainCode:t},n)=>{const r=new ArrayBuffer(4);new DataView(r).setUint32(0,n);const s=new Uint8Array(1+e.length+r.byteLength);s.set(new Uint8Array(1).fill(0)),s.set(e,1),s.set(new Uint8Array(r,0,r.byteLength),e.length+1);const i=_h.create(Zf,t).update(s).digest();return{key:i.slice(0,32),chainCode:i.slice(32)}})(e,t+n),{key:r,chainCode:s})};class Jf extends tp{constructor(e){if(super(),"string"==typeof e?this.data=Ee(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),32!==this.data.length)throw new Error(`Invalid public key input. Expected 32 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return xh.ED25519}async verify(e,t){let n;if("string"==typeof t){const e=np(t);if("ED25519"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!ep(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return hh.verify(n,e,this.toRawBytes())}}Jf.SIZE=32;const Yf="m/44'/784'/0'/0'/0'";class Xf extends Rf{constructor(e){if(super(),e)this.keypair={publicKey:e.publicKey,secretKey:e.secretKey.slice(0,32)};else{const e=hh.utils.randomPrivateKey();this.keypair={publicKey:hh.getPublicKey(e),secretKey:e}}}getKeyScheme(){return"ED25519"}static generate(){const e=hh.utils.randomPrivateKey();return new Xf({publicKey:hh.getPublicKey(e),secretKey:e})}static fromSecretKey(e,t){if("string"==typeof e){const n=Mf(e);if("ED25519"!==n.schema)throw new Error(`Expected a ED25519 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=e.length;if(32!==n)throw new Error(`Wrong secretKey size. Expected 32 bytes, got ${n}.`);const r={publicKey:hh.getPublicKey(e),secretKey:e};if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),n=hh.sign(t,e);if(!hh.verify(n,t,r.publicKey))throw new Error("provided secretKey is invalid")}return new Xf(r)}getPublicKey(){return new Jf(this.keypair.publicKey)}getSecretKey(){return Df(this.keypair.secretKey.slice(0,32),this.getKeyScheme())}async sign(e){return hh.sign(e,this.keypair.secretKey)}static deriveKeypair(e,t){if(null==t&&(t=Yf),!Kf(t))throw new Error("Invalid derivation path");const{key:n}=Hf(t,function(e){return Ie(zf(e))}(e));return Xf.fromSecretKey(n)}static deriveKeypairFromSeed(e,t){if(null==t&&(t=Yf),!Kf(t))throw new Error("Invalid derivation path");const{key:n}=Hf(t,e);return Xf.fromSecretKey(n)}}const Qf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},eg={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},tg=BigInt(2);const ng=Al(Qf.p,void 0,void 0,{sqrt:function(e){const t=Qf.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,l=bl(d,n,t)*d%t,h=bl(l,n,t)*d%t,p=bl(h,tg,t)*u%t,f=bl(p,s,t)*p%t,g=bl(f,i,t)*f%t,m=bl(g,o,t)*g%t,y=bl(m,c,t)*m%t,b=bl(y,o,t)*g%t,w=bl(b,n,t)*d%t,v=bl(w,a,t)*f%t,k=bl(v,r,t)*u%t,E=bl(k,tg,t);if(!ng.eql(ng.sqr(E),e))throw new Error("Cannot find square root");return E}}),rg=qh({...Qf,Fp:ng,lowS:!0,endo:eg},Ld),sg=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ig=(()=>Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)))(),ag=(()=>ig.map(e=>(9*e+5)%16))(),og=(()=>{const e=[[ig],[ag]];for(let t=0;t<4;t++)for(let n of e)n.push(n[t].map(e=>sg[e]));return e})(),cg=(()=>og[0])(),ug=(()=>og[1])(),dg=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),lg=cg.map((e,t)=>e.map(e=>dg[t][e])),hg=ug.map((e,t)=>e.map(e=>dg[t][e])),pg=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),fg=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function gg(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const mg=new Uint32Array(16);class yg extends Vs{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:s}=this;return[e,t,n,r,s]}set(e,t,n,r,s){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(e,t){for(let n=0;n<16;n++,t+=4)mg[n]=e.getUint32(t,!0);let n=0|this.h0,r=n,s=0|this.h1,i=s,a=0|this.h2,o=a,c=0|this.h3,u=c,d=0|this.h4,l=d;for(let e=0;e<5;e++){const t=4-e,h=pg[e],p=fg[e],f=cg[e],g=ug[e],m=lg[e],y=hg[e];for(let t=0;t<16;t++){const r=ps(n+gg(e,s,a,c)+mg[f[t]]+h,m[t])+d|0;n=d,d=c,c=0|ps(a,10),a=s,s=r}for(let e=0;e<16;e++){const n=ps(r+gg(t,i,o,u)+mg[g[e]]+p,y[e])+l|0;r=l,l=u,u=0|ps(o,10),o=i,i=n}}this.set(this.h1+a+u|0,this.h2+c+l|0,this.h3+d+r|0,this.h4+n+i|0,this.h0+s+o|0)}roundClean(){ds(mg)}destroy(){this.destroyed=!0,ds(this.buffer),this.set(0,0,0,0,0)}}const bg=Ns(()=>new yg),wg=rg.ProjectivePoint,vg=(e=>{return Q((n=t=>e(e(t)),H(t=4),W(n),{encode(e){if(!z(e))throw new Error("checksum.encode: input should be Uint8Array");const r=n(e).slice(0,t),s=new Uint8Array(e.length+t);return s.set(e),s.set(r,e.length),s},decode(e){if(!z(e))throw new Error("checksum.decode: input should be Uint8Array");const r=e.slice(0,-t),s=e.slice(-t),i=n(r).slice(0,t);for(let e=0;e<t;e++)if(i[e]!==s[e])throw new Error("Invalid checksum");return r}}),pe);var t,n})(Ld);function kg(e){is(e);const t=0===e.length?"0":vs(e);return BigInt("0x"+t)}const Eg=As("Bitcoin seed"),Sg={private:76066276,public:76067358},xg=2147483648,Og=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error("invalid number, should be from 0 to 2**32-1, got "+e);const t=new Uint8Array(4);return ls(t).setUint32(0,e,!1),t};class Ig{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return ls(this.pubHash).getUint32(0,!1)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){const e=this.privateKey;if(!e)throw new Error("No private key");return vg.encode(this.serialize(this.versions.private,Ps(new Uint8Array([0]),e)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return vg.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(e,t=Sg){if(is(e),8*e.length<128||8*e.length>512)throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+e.length);const n=_h(Kd,Eg,e);return new Ig({versions:t,chainCode:n.slice(32),privateKey:n.slice(0,32)})}static fromExtendedKey(e,t=Sg){const n=vg.decode(e),r=ls(n),s=r.getUint32(0,!1),i={versions:t,depth:n[4],parentFingerprint:r.getUint32(5,!1),index:r.getUint32(9,!1),chainCode:n.slice(13,45)},a=n.slice(45),o=0===a[0];if(s!==t[o?"private":"public"])throw new Error("Version mismatch");return new Ig(o?{...i,privateKey:a.slice(1)}:{...i,publicKey:a})}static fromJSON(e){return Ig.fromExtendedKey(e.xpriv)}constructor(e){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!e||"object"!=typeof e)throw new Error("HDKey.constructor must not be called directly");if(this.versions=e.versions||Sg,this.depth=e.depth||0,this.chainCode=e.chainCode||null,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(e.publicKey&&e.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(e.privateKey){if(!rg.utils.isValidPrivateKey(e.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof e.privateKey?e.privateKey:kg(e.privateKey),this.privKeyBytes=function(e){if("bigint"!=typeof e)throw new Error("bigint expected");return _s(e.toString(16).padStart(64,"0"))}(this.privKey),this.pubKey=rg.getPublicKey(e.privateKey,!0)}else{if(!e.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=wg.fromHex(e.publicKey).toRawBytes(!0)}var t;this.pubHash=(t=this.pubKey,bg(Ld(t)))}derive(e){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;const t=e.replace(/^[mM]'?\//,"").split("/");let n=this;for(const e of t){const t=/^(\d+)('?)$/.exec(e),r=t&&t[1];if(!t||3!==t.length||"string"!=typeof r)throw new Error("invalid child index: "+e);let s=+r;if(!Number.isSafeInteger(s)||s>=xg)throw new Error("Invalid index");"'"===t[2]&&(s+=xg),n=n.deriveChild(s)}return n}deriveChild(e){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let t=Og(e);if(e>=xg){const e=this.privateKey;if(!e)throw new Error("Could not derive hardened child key");t=Ps(new Uint8Array([0]),e,t)}else t=Ps(this.pubKey,t);const n=_h(Kd,this.chainCode,t),r=kg(n.slice(0,32)),s=n.slice(32);if(!rg.utils.isValidPrivateKey(r))throw new Error("Tweak bigger than curve order");const i={versions:this.versions,chainCode:s,depth:this.depth+1,parentFingerprint:this.fingerprint,index:e};try{if(this.privateKey){const e=yl(this.privKey+r,rg.CURVE.n);if(!rg.utils.isValidPrivateKey(e))throw new Error("The tweak was out of range or the resulted private key is invalid");i.privateKey=e}else{const e=wg.fromHex(this.pubKey).add(wg.fromPrivateKey(r));if(e.equals(wg.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=e.toRawBytes(!0)}return new Ig(i)}catch(t){return this.deriveChild(e+1)}}sign(e){if(!this.privateKey)throw new Error("No privateKey set!");return is(e,32),rg.sign(e,this.privKey).toCompactRawBytes()}verify(e,t){if(is(e,32),is(t,64),!this.publicKey)throw new Error("No publicKey set!");let n;try{n=rg.Signature.fromCompact(t)}catch(e){return!1}return rg.verify(n,e,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(e,t){if(!this.chainCode)throw new Error("No chainCode set");return is(t,33),Ps(Og(e),new Uint8Array([this.depth]),Og(this.parentFingerprint),Og(this.index),this.chainCode,t)}}class Tg extends tp{constructor(e){if(super(),"string"==typeof e?this.data=Ee(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return xh.Secp256k1}async verify(e,t){let n;if("string"==typeof t){const e=np(t);if("Secp256k1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!ep(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return rg.verify(rg.Signature.fromCompact(n),Qh(e),this.toRawBytes())}}Tg.SIZE=33;class _g extends Rf{constructor(e){if(super(),e)this.keypair=e;else{const e=rg.utils.randomPrivateKey(),t=rg.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256k1"}static generate(){return new _g}static fromSecretKey(e,t){if("string"==typeof e){const n=Mf(e);if("Secp256k1"!==n.schema)throw new Error(`Expected a Secp256k1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=rg.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=vs(pi(t,{dkLen:32})),s=rg.sign(r,e);if(!rg.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new _g({publicKey:n,secretKey:e})}static fromSeed(e){const t=rg.getPublicKey(e,!0);return new _g({publicKey:t,secretKey:e})}getPublicKey(){return new Tg(this.keypair.publicKey)}getSecretKey(){return Df(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Qh(e);return rg.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/54'/784'/0'/0/0"),!qf(t))throw new Error("Invalid derivation path");const n=Ig.fromMasterSeed(zf(e)).derive(t);if(null==n.publicKey||null==n.privateKey)throw new Error("Invalid key");return new _g({publicKey:n.publicKey,secretKey:n.privateKey})}}class Ag extends tp{constructor(e){if(super(),"string"==typeof e?this.data=Ee(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),33!==this.data.length)throw new Error(`Invalid public key input. Expected 33 bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return xh.Secp256r1}async verify(e,t){let n;if("string"==typeof t){const e=Bf(t);if("Secp256r1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!ep(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Xh.verify(Xh.Signature.fromCompact(n),Qh(e),this.toRawBytes())}}Ag.SIZE=33;class jg extends Rf{constructor(e){if(super(),e)this.keypair=e;else{const e=Xh.utils.randomPrivateKey(),t=Xh.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256r1"}static generate(){return new jg}static fromSecretKey(e,t){if("string"==typeof e){const n=Mf(e);if("Secp256r1"!==n.schema)throw new Error(`Expected a Secp256r1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=Xh.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=vs(pi(t,{dkLen:32})),s=Xh.sign(r,e,{lowS:!0});if(!Xh.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new jg({publicKey:n,secretKey:e})}static fromSeed(e){const t=Xh.getPublicKey(e,!0);return new jg({publicKey:t,secretKey:e})}getPublicKey(){return new Ag(this.keypair.publicKey)}getSecretKey(){return Df(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Qh(e);return Xh.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/74'/784'/0'/0/0"),!qf(t))throw new Error("Invalid derivation path");const n=Ig.fromMasterSeed(zf(e)).derive(t).privateKey;return jg.fromSecretKey(n)}}var Cg;function Pg(e,t=!1){let n,r;if("object"==typeof e){if(!t)throw new Error("Invalid secret key format");r=Ee(e.privateKey),n=e.schema}else{const t=Mf(e);n=t.schema,r=t.secretKey}switch(n){case"ED25519":{let e=r;return 64===r.length&&(e=r.slice(0,32)),Xf.fromSecretKey(e)}case"Secp256k1":return _g.fromSecretKey(r);case"Secp256r1":return jg.fromSecretKey(r);default:throw new Error(`Invalid keypair schema: ${n}`)}}async function Bg(e,t){const n=await e.signPersonalMessage(t);return Ng("string"==typeof n?n:n.signature,!0)}function Ng(e,t=!1){const n=Bf(e);let r=s.from(n.signature).toString("hex"),i=s.from(n.publicKey).toString("base64"),a=Cg.KP_SECP256;if("Secp256k1"===n.signatureScheme||"Secp256r1"===n.signatureScheme)a=Cg.KP_SECP256;else if("ED25519"===n.signatureScheme)a=t?Cg.KP_ED25519:Cg.UI_ED25519;else{if("ZkLogin"!==n.signatureScheme)throw new Error(`Unsupported signature scheme: ${n.signatureScheme}`);a=Cg.ZK_ED25519}return`${r}${a}${i}`}function $g(t,n=18){if(!t&&0!==t)return"0";try{const r=new e(t);if(r.isNaN())return"0";return r.multipliedBy(new e(10).pow(n)).integerValue(e.ROUND_DOWN).toString(10)}catch(e){return"0"}}function Rg(t,n=18){return new e(t).multipliedBy(new e(10).pow(n))}function Mg(e){return e instanceof Error?e.message:"string"==typeof e?e:String(e)}function Dg(e){const t=function(){try{if(void 0!==import.meta&&import.meta.url){const e=o(import.meta.url);return a.dirname(e)}}catch(e){}return"undefined"!=typeof __dirname?__dirname:process.cwd()}();let n=null;if(a.isAbsolute(e))n=e;else{const r=a.resolve(t,".."),s=a.resolve(r,e);if(i.existsSync(s))n=s;else{const r=function(e){let t=e;const n=a.parse(t).root;for(;t!==n;){const e=a.join(t,"package.json");if(i.existsSync(e))try{if("dipcoin-cli"===JSON.parse(i.readFileSync(e,"utf-8")).name)return t}catch(e){}const n=a.dirname(t);if(n===t)break;t=n}return null}(t);if(r){const t=a.resolve(r,"dist",e);i.existsSync(t)&&(n=t)}if(!n){const t=a.resolve(process.cwd(),e);i.existsSync(t)&&(n=t)}}}if(!n||!i.existsSync(n))return{packages:[]};const r=JSON.parse(i.readFileSync(n).toString());return r.packages&&Array.isArray(r.packages)||(r.packages=[]),r}!function(e){e.KP_SECP256="0",e.KP_ED25519="1",e.UI_ED25519="2",e.ZK_ED25519="3"}(Cg||(Cg={}));const Ug=a.join(c.homedir(),".config","dipcoin","jwt");function Vg(e){return a.join(Ug,`${e}.json`)}function Fg(e){try{const t=Vg(e);if(!i.existsSync(t))return null;const n=i.readFileSync(t,"utf-8"),r=JSON.parse(n),s=Math.floor(Date.now()/1e3);return r.exp-60>s?r.token:(i.unlinkSync(t),null)}catch{return null}}function Lg(e,t){try{const n=function(e){try{const t=e.split(".");if(3!==t.length)return null;const n=JSON.parse(Buffer.from(t[1],"base64").toString());return"number"==typeof n.exp?n.exp:null}catch{return null}}(t);if(!n)return;i.mkdirSync(Ug,{recursive:!0});const r={token:t,exp:n};i.writeFileSync(Vg(e),JSON.stringify(r),{mode:384})}catch{}}function Kg(e){try{const t=Vg(e);i.existsSync(t)&&i.unlinkSync(t)}catch{}}class qg{httpClient;keypair;subKeypair;walletAddress;subAddress;options;jwtToken;subJwtToken;isAuthenticating=!1;isSubAuthenticating=!1;deploymentConfig;suiClient;priceServiceConnection;pythClient;tradingPairsCache;tradingPairsCacheTimestamp;constructor(e,t){this.options=t,this.httpClient=new ld(t.apiBaseUrl),this.keypair="string"==typeof e?Pg(e):e,t.subAccountKey&&("string"==typeof t.subAccountKey?this.subKeypair=Pg(t.subAccountKey):this.subKeypair=t.subAccountKey,this.subAddress=this.subKeypair.getPublicKey().toSuiAddress()),this.walletAddress=this.keypair.getPublicKey().toSuiAddress(),this.httpClient.setWalletAddress(this.walletAddress),this.deploymentConfig=Dg(`config/deployed/${t.network}/main_contract.json`);const n=t.customRpc||function(e){switch(e){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${e}`)}}(t.network);this.suiClient=new to({url:n})}get address(){return this.walletAddress}get subAccountAddress(){return this.subAddress}get optionsField(){return this.options}async authenticate(){try{if(this.jwtToken)return{status:!0,data:this.jwtToken};const e=Fg(this.walletAddress);if(e)return this.jwtToken=e,this.httpClient.setAuthToken(e),{status:!0,data:e};if(this.isAuthenticating&&(await new Promise(e=>setTimeout(e,100)),this.jwtToken))return{status:!0,data:this.jwtToken};this.isAuthenticating=!0;const t=(new TextEncoder).encode(cd),n=await Bg(this.keypair,t),r=await this.httpClient.post(od.AUTHORIZE,{userAddress:this.walletAddress,isTermAccepted:!0,signature:n});return 200===r.code&&r.data?.token?(this.jwtToken=r.data.token,this.httpClient.setAuthToken(this.jwtToken),Lg(this.walletAddress,this.jwtToken),this.isAuthenticating=!1,{status:!0,data:this.jwtToken}):(this.isAuthenticating=!1,{status:!1,error:r.message||"Failed to authenticate"})}catch(e){return this.isAuthenticating=!1,{status:!1,error:Mg(e)}}}async authenticateSub(){if(!this.subKeypair)return{status:!1,error:"Sub-account keypair not configured"};const e=this.subKeypair.getPublicKey().toSuiAddress();try{if(this.subJwtToken)return{status:!0,data:this.subJwtToken};const t=Fg(e);if(t)return this.subJwtToken=t,{status:!0,data:t};if(this.isSubAuthenticating&&(await new Promise(e=>setTimeout(e,100)),this.subJwtToken))return{status:!0,data:this.subJwtToken};this.isSubAuthenticating=!0;const n=(new TextEncoder).encode(cd),r=await Bg(this.subKeypair,n),s=await this.httpClient.post(od.AUTHORIZE,{userAddress:e,isTermAccepted:!0,signature:r});return 200===s.code&&s.data?.token?(this.subJwtToken=s.data.token,Lg(e,this.subJwtToken),this.isSubAuthenticating=!1,{status:!0,data:this.subJwtToken}):(this.isSubAuthenticating=!1,{status:!1,error:s.message||"Failed to authenticate sub-account"})}catch(e){return this.isSubAuthenticating=!1,{status:!1,error:Mg(e)}}}async authenticateForTrading(){if(this.subKeypair){const e=await this.authenticateSub();return e.status&&e.data?(this.httpClient.setAuthToken(e.data),this.subAddress&&this.httpClient.setWalletAddress(this.subAddress),e):e}return this.authenticate()}restoreMainAuth(){this.httpClient.setWalletAddress(this.walletAddress),this.jwtToken&&this.httpClient.setAuthToken(this.jwtToken)}async getJWTToken(e=!1){return e&&(this.jwtToken=void 0,this.httpClient.setAuthToken("")),this.authenticate()}clearAuth(){this.jwtToken&&Kg(this.walletAddress),this.subJwtToken&&this.subAddress&&Kg(this.subAddress),this.jwtToken=void 0,this.subJwtToken=void 0,this.httpClient.setAuthToken("")}async placeOrder(t){try{const n=await this.authenticateForTrading();if(!n.status)return this.restoreMainAuth(),{status:!1,error:n.error||"Authentication failed"};if(!(t.symbol&&t.side&&t.orderType&&t.quantity&&t.leverage))throw new Error("Missing required order parameters");if(t.orderType===Cd.LIMIT&&!t.price)throw new Error("Price is required for LIMIT orders");const{symbol:r,side:s,orderType:i,quantity:a,price:o,leverage:c,market:u,reduceOnly:d=!1,clientId:l="",creator:h,tpTriggerPrice:p,tpOrderType:f=Cd.MARKET,tpOrderPrice:g="",slTriggerPrice:m,slOrderType:y=Cd.MARKET,slOrderPrice:b=""}=t,w=h||this.walletAddress,v=this.subKeypair||this.keypair;if(!u)throw new Error("Market (PerpetualID) is required. Please provide the market parameter with the PerpetualID for the trading pair.");const k=o&&""!==o?Rg(o):new e(0),E=Rg(a),S=Rg(c),x=new e(0),O=new e(+new Date),I={market:u,creator:w,isLong:s===jd.BUY,reduceOnly:d,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:E,price:i===Cd.LIMIT?k:new e(0),leverage:S,expiration:x,salt:O};let T=null,_=null;p&&(_=new e(Date.now()+1),T={market:I.market,creator:w,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:E,price:f===Cd.LIMIT?Rg(g||p):Rg(""),leverage:S,expiration:x,salt:_});let A=null,j=null;m&&(j=new e(Date.now()+2),A={market:I.market,creator:w,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:E,price:y===Cd.LIMIT?Rg(b||m):Rg(""),leverage:S,expiration:x,salt:j});const C=hd(I),P=(new TextEncoder).encode(C),B=await Bg(v,P);let N,$;if(T){const e=hd(T),t=(new TextEncoder).encode(e);N=await Bg(v,t)}if(A){const e=hd(A),t=(new TextEncoder).encode(e);$=await Bg(v,t)}const R={symbol:r,side:s,orderType:i,quantity:$g(a),price:$g(o||""),leverage:$g(c),salt:O.toString(),creator:w,clientId:l,reduceOnly:d,orderSignature:B};p&&N&&(R.tpOrderSignature=N,R.tpTriggerPrice=$g(p),R.tpOrderType=f,R.tpOrderPrice=f===Cd.LIMIT?$g(g||p):$g(""),R.tpSalt=_?.toString(),R.triggerWay="oracle"),m&&$&&(R.slOrderSignature=$,R.slTriggerPrice=$g(m),R.slOrderType=y,R.slOrderPrice=y===Cd.LIMIT?$g(b||m):$g(""),R.slSalt=j?.toString());const M=await this.httpClient.post(od.PLACE_ORDER,R);if(1e3===M.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(od.PLACE_ORDER,R);if(this.restoreMainAuth(),200===e.code)return{status:!0,data:e}}return this.restoreMainAuth(),{status:!1,error:"Authentication expired and refresh failed"}}return this.restoreMainAuth(),200===M.code?{status:!0,data:M}:{status:!1,error:M.message||"Order failed",data:M}}catch(e){return this.restoreMainAuth(),{status:!1,error:Mg(e)}}}async cancelOrder(e){try{const t=await this.authenticateForTrading();if(!t.status)return this.restoreMainAuth(),{status:!1,error:t.error||"Authentication failed"};const{symbol:n,orderHashes:r,parentAddress:s=this.walletAddress}=e;if(!r||0===r.length)throw new Error("Order hashes are required");const i=this.subKeypair||this.keypair,a={orderHashes:r},o=(new TextEncoder).encode(JSON.stringify(a)),c={symbol:n,orderHashes:r,signature:await Bg(i,o),parentAddress:s},u=await this.httpClient.post(od.CANCEL_ORDER,c);if(1e3===u.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(od.CANCEL_ORDER,c);if(this.restoreMainAuth(),200===e.code)return{status:!0,data:e}}return this.restoreMainAuth(),{status:!1,error:"Authentication expired and refresh failed"}}return this.restoreMainAuth(),200===u.code?{status:!0,data:u}:{status:!1,error:u.message||"Cancellation Failed",data:u}}catch(e){return this.restoreMainAuth(),{status:!1,error:Mg(e)}}}async adjustLeverage(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const{symbol:n,leverage:r,marginType:s="ISOLATED"}=e;if(!n)throw new Error("Symbol is required for adjusting leverage");if(!this.isPositiveNumber(r))throw new Error("Leverage must be greater than zero");const i={symbol:n,marginType:s,leverage:$g(r)};let a=await this.httpClient.post(od.ADJUST_LEVERAGE,i);if(1e3===a.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};a=await this.httpClient.post(od.ADJUST_LEVERAGE,i)}return 200===a.code?{status:!0,data:a}:{status:!1,data:a,error:a.message||"Failed to adjust leverage"}}catch(e){return{status:!1,error:Mg(e)}}}async getUserConfig(e){if(!e)return{status:!1,error:"Symbol is required"};try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={symbol:e};let r=await this.httpClient.get(od.GET_USER_CONFIG,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(od.GET_USER_CONFIG,{params:n})}if(200===r.code&&r.data){const t=Array.isArray(r.data)?r.data[0]:r.data;if(!t)return{status:!1,error:"User config not found"};const n=t.leverage??t.leverageWei??"0";return{status:!0,data:{...t,symbol:t.symbol||e,marginType:t.marginType||t.marginTypeEnum,leverageWei:n,leverage:this.formatWeiToNormal(n)}}}return{status:!1,error:r.message||"Failed to fetch user config"}}catch(e){return{status:!1,error:Mg(e)}}}async placePositionTpSlOrders(t){try{const n=await this.authenticateForTrading();if(!n.status)return this.restoreMainAuth(),{status:!1,error:n.error||"Authentication failed"};const r=this.subKeypair||this.keypair,{symbol:s,market:i,side:a,isLong:o,leverage:c,quantity:u,reduceOnly:d=!0,postOnly:l=!1,orderbookOnly:h=!0,ioc:p=!1,tp:f,sl:g}=t;if(!this.isPositiveNumber(u))return{status:!1,error:"Quantity must be greater than zero"};const m=this.hasTpSlOrderConfig(f,u),y=this.hasTpSlOrderConfig(g,u);if(!m&&!y)return{status:!1,error:"At least one TP or SL configuration is required"};const b=Rg(c),w=$g(c),v=new e(0),k=new e(+new Date),E=k.plus(1),S={symbol:s,side:a,leverage:w,creator:this.walletAddress},x=async e=>{let t=await this.httpClient.post(od.PLAN_CLOSE_ORDER,e);if(1e3===t.code){this.clearAuth();(await this.authenticate()).status&&(t=await this.httpClient.post(od.PLAN_CLOSE_ORDER,e))}return t},O={};let I,T;if(m&&f){if(!this.isPositiveNumber(f.triggerPrice))return{status:!1,error:"TP trigger price must be greater than zero"};const t=f.salt?new e(f.salt):k,n=Rg(f.quantity??u),s=(f.orderType||Cd.MARKET)===Cd.LIMIT?Rg(f.orderPrice??f.triggerPrice??"0"):new e(0),a=hd({market:i,creator:this.walletAddress,isLong:!o,reduceOnly:d,postOnly:l,orderbookOnly:h,ioc:p,quantity:n,price:s,leverage:b,expiration:v,salt:t}),c=await Bg(r,(new TextEncoder).encode(a));I={...S,tpOrderType:f.orderType||Cd.MARKET,tpTpslType:f.tpslType||"position",tpTriggerPrice:$g(f.triggerPrice),tpOrderPrice:(f.orderType||Cd.MARKET)===Cd.LIMIT?$g(f.orderPrice??f.triggerPrice??"0"):"0",tpQuantity:$g(f.quantity??u),tpTriggerWay:f.triggerWay||"oracle",tpSalt:t.toString(),tpOrderSignature:c},void 0!==f.planId&&(I.tpPlanId=f.planId)}if(y&&g){if(!this.isPositiveNumber(g.triggerPrice))return{status:!1,error:"SL trigger price must be greater than zero"};const t=g.salt?new e(g.salt):E,n=Rg(g.quantity??u),s=(g.orderType||Cd.MARKET)===Cd.LIMIT?Rg(g.orderPrice??g.triggerPrice??"0"):new e(0),a=hd({market:i,creator:this.walletAddress,isLong:!o,reduceOnly:d,postOnly:l,orderbookOnly:h,ioc:p,quantity:n,price:s,leverage:b,expiration:v,salt:t}),c=await Bg(r,(new TextEncoder).encode(a));T={...S,slOrderType:g.orderType||Cd.MARKET,slTpslType:g.tpslType||"position",slTriggerPrice:$g(g.triggerPrice),slOrderPrice:(g.orderType||Cd.MARKET)===Cd.LIMIT?$g(g.orderPrice??g.triggerPrice??"0"):"0",slQuantity:$g(g.quantity??u),slTriggerWay:g.triggerWay||"oracle",slSalt:t.toString(),slOrderSignature:c},void 0!==g.planId&&(T.slPlanId=g.planId)}if(m&&y&&I&&T){const e={...I,...T},t=await x(e);O.tpResult=t,O.slResult=t}else m&&I?O.tpResult=await x(I):y&&T&&(O.slResult=await x(T));return[O.tpResult,O.slResult].some(e=>e&&200===e.code)?(this.restoreMainAuth(),{status:!0,data:O}):(this.restoreMainAuth(),{status:!1,data:O,error:O.tpResult?.message||O.slResult?.message||"Failed to place TP/SL order"})}catch(e){return this.restoreMainAuth(),{status:!1,error:Mg(e)}}}async getPositionTpSl(e,t="normal"){try{const n=await this.authenticate();if(!n.status)return{status:!1,error:n.error||"Authentication failed"};const r={positionId:e,tpslType:t};let s=await this.httpClient.get(od.GET_POSITION_TPSL,{params:r});if(1e3===s.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};s=await this.httpClient.get(od.GET_POSITION_TPSL,{params:r})}if(200===s.code){const e=Array.isArray(s.data)?s.data:s.data?.data||[];return{status:!0,data:e.map(e=>this.transformPositionTpSlOrder(e))}}return{status:!1,error:s.message||"Failed to fetch TP/SL orders"}}catch(e){return{status:!1,error:Mg(e)}}}async cancelTpSlOrders(e){return this.cancelOrder(e)}async getAccountInfo(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.parentAddress&&(n.parentAddress=e.parentAddress);const r=await this.httpClient.get(od.GET_ACCOUNT_INFO,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(od.GET_ACCOUNT_INFO,{params:n});if(200===e.code&&e.data)return{status:!0,data:{walletBalance:e.data.walletBalance||"0",totalUnrealizedProfit:e.data.totalUnrealizedProfit||"0",accountValue:e.data.accountValue||"0",freeCollateral:e.data.freeCollateral||"0",totalMargin:e.data.totalMargin||"0"}}}return{status:!1,error:"Authentication expired and refresh failed"}}return 200===r.code&&r.data?{status:!0,data:{walletBalance:r.data.walletBalance||"0",totalUnrealizedProfit:r.data.totalUnrealizedProfit||"0",accountValue:r.data.accountValue||"0",freeCollateral:r.data.freeCollateral||"0",totalMargin:r.data.totalMargin||"0"}}:{status:!1,error:r.message||"Failed to get account info"}}catch(e){return{status:!1,error:Mg(e)}}}async getPositions(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};"string"==typeof e?n.symbol=e:e&&(e.symbol&&(n.symbol=e.symbol),e.parentAddress&&(n.parentAddress=e.parentAddress));const r=await this.httpClient.get(od.GET_POSITIONS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(od.GET_POSITIONS,{params:n});if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}}return{status:!1,error:"Authentication expired and refresh failed"}}if(200===r.code){return{status:!0,data:Array.isArray(r.data)?r.data:r.data?.data||[]}}return{status:!1,error:r.message||"Failed to get positions"}}catch(e){return{status:!1,error:Mg(e)}}}async getTradingPairs(){try{const e=await this.httpClient.get(od.GET_TRADING_PAIRS);if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}return{status:!1,error:e.message||"Failed to get trading pairs"}}catch(e){return{status:!1,error:Mg(e)}}}async getPerpetualID(e){try{const t=await this.getTradingPairs();if(t.status&&t.data){const n=t.data.find(t=>t.symbol===e);return n?.perpId||null}return null}catch(e){return null}}async getOpenOrders(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};"string"==typeof e?n.symbol=e:e&&(e.symbol&&(n.symbol=e.symbol),e.page&&(n.page=e.page),e.pageSize&&(n.pageSize=e.pageSize),e.parentAddress&&(n.parentAddress=e.parentAddress));const r=await this.httpClient.get(od.GET_OPEN_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(od.GET_OPEN_ORDERS,{params:n});if(200===e.code){return{status:!0,data:Array.isArray(e.data)?e.data:e.data?.data||[]}}}return{status:!1,error:"Authentication expired and refresh failed"}}if(200===r.code){return{status:!0,data:Array.isArray(r.data)?r.data:r.data?.data||[]}}return{status:!1,error:r.message||"Failed to get open orders"}}catch(e){return{status:!1,error:Mg(e)}}}async getOrderBook(e){try{if(!e)return{status:!1,error:"Symbol is required"};const t={symbol:e},n=await this.httpClient.get(od.GET_ORDER_BOOK,{params:t});if(200===n.code&&n.data){let t=n.data;if(t.data&&(t=t.data),!t||!Array.isArray(t.bids)||!Array.isArray(t.asks))return{status:!1,error:"Invalid order book data structure"};const r=this.processOrderBookEntries(t.bids,"bids"),s=this.processOrderBookEntries(t.asks,"asks");return{status:!0,data:{symbol:e,bids:r,asks:s,timestamp:Date.now()}}}return{status:!1,error:n.message||"Failed to get order book"}}catch(e){return{status:!1,error:Mg(e)}}}processOrderBookEntries(e,t){return Array.isArray(e)?e.filter(e=>{if(Array.isArray(e)&&e.length>=2){const[t,n]=e;return t&&n&&!isNaN(parseFloat(String(t)))&&!isNaN(parseFloat(String(n)))&&parseFloat(String(n))>0}return!!(e&&e.price&&e.quantity)&&(!isNaN(parseFloat(String(e.price)))&&!isNaN(parseFloat(String(e.quantity)))&&parseFloat(String(e.quantity))>0)}).map(e=>{let t,n;return Array.isArray(e)&&e.length>=2?[t,n]=e:(t=e.price,n=e.quantity),{price:String(t),quantity:String(n)}}).sort((e,n)=>{const r=parseFloat(e.price),s=parseFloat(n.price);return"bids"===t?s-r:r-s}):[]}formatWeiToNormal(t,n=18){try{const r=new e(t);return r.isNaN()||r.isZero()?"0":r.dividedBy(new e(10).pow(n)).toString()}catch(e){return"0"}}async getTicker(e){try{if(!e)return{status:!1,error:"Symbol is required"};const t={symbol:e},n=await this.httpClient.get(od.GET_TICKER,{params:t});if(200===n.code&&n.data){let e=n.data;if(e.data&&(e=e.data),!e||!e.symbol)return{status:!1,error:"Invalid ticker data structure"};return{status:!0,data:this.processTickerData(e)}}return{status:!1,error:n.message||"Failed to get ticker"}}catch(e){return{status:!1,error:Mg(e)}}}transformPositionTpSlOrder(e){const t=e=>null!=e&&""!==e?this.formatWeiToNormal(e):void 0,n=e.planOrderType;return{...e,id:e.id??e.planId??e.planBatchId,planBatchId:e.planBatchId??e.id,planOrderType:n,orderType:e.orderType,symbol:e.symbol,side:e.side,status:e.status,hash:e.hash,quantity:t(e.quantity)??"0",price:t(e.price),triggerPrice:t(e.triggerPrice),tpTriggerPrice:t(e.tpTriggerPrice),tpOrderPrice:t(e.tpOrderPrice),slTriggerPrice:t(e.slTriggerPrice),slOrderPrice:t(e.slOrderPrice),tpPlanId:"takeProfit"===n?e.tpPlanId??e.id??null:e.tpPlanId??null,slPlanId:"stopLoss"===n?e.slPlanId??e.id??null:e.slPlanId??null,tpslType:e.tpslType,createdAt:e.createdAt,updatedAt:e.updatedAt}}hasTpSlOrderConfig(e,t){if(!e)return!1;if(!this.isPositiveNumber(e.triggerPrice))return!1;const n=e.quantity??t;return this.isPositiveNumber(n)}isPositiveNumber(t){if(null==t||""===t)return!1;try{return new e(t).gt(0)}catch{return!1}}processTickerData(t){let n;if(t.bestAskPrice&&t.bestBidPrice){const r=new e(t.bestAskPrice),s=new e(t.bestBidPrice);n=r.plus(s).dividedBy(2).toString()}else n=t.bestAskPrice?String(t.bestAskPrice):t.bestBidPrice?String(t.bestBidPrice):"0";const r={symbol:t.symbol,lastPrice:String(t.lastPrice||"0"),high24h:String(t.high24h||"0"),low24h:String(t.low24h||"0"),amount24h:String(t.amount24h||"0"),volume24h:String(t.volume24h||"0"),midPrice:n,timestamp:t.timestamp||Date.now()};return t.markPrice&&(r.markPrice=String(t.markPrice)),t.bestAskPrice&&(r.bestAskPrice=String(t.bestAskPrice)),t.bestBidPrice&&(r.bestBidPrice=String(t.bestBidPrice)),t.bestAskAmount&&(r.bestAskAmount=String(t.bestAskAmount)),t.bestBidAmount&&(r.bestBidAmount=String(t.bestBidAmount)),t.open24h&&(r.open24h=String(t.open24h)),t.change24h&&(r.change24h=String(t.change24h)),t.rate24h&&(r.rate24h=String(t.rate24h)),t.openPrice&&(r.openPrice=String(t.openPrice)),t.oraclePrice&&(r.oraclePrice=String(t.oraclePrice)),t.fundingRate&&(r.fundingRate=String(t.fundingRate)),t.openInterest&&(r.openInterest=String(t.openInterest)),r}async getHistoryOrders(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.symbol&&(n.symbol=e.symbol),e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress),e?.beginTime&&(n.beginTime=e.beginTime),e?.endTime&&(n.endTime=e.endTime);let r=await this.httpClient.get(od.HISTORY_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(od.HISTORY_ORDERS,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get history orders"}}catch(e){return{status:!1,error:Mg(e)}}}async getFundingSettlements(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.symbol&&(n.symbol=e.symbol),e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress),e?.beginTime&&(n.beginTime=e.beginTime);let r=await this.httpClient.get(od.FUNDING_SETTLEMENTS,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(od.FUNDING_SETTLEMENTS,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get funding settlements"}}catch(e){return{status:!1,error:Mg(e)}}}async getBalanceChanges(e){try{const t=await this.authenticate();if(!t.status)return{status:!1,error:t.error||"Authentication failed"};const n={};e?.page&&(n.page=e.page),e?.pageSize&&(n.pageSize=e.pageSize),e?.parentAddress&&(n.parentAddress=e.parentAddress),e?.beginTime&&(n.beginTime=e.beginTime);let r=await this.httpClient.get(od.BALANCE_CHANGES,{params:n});if(1e3===r.code){this.clearAuth();if(!(await this.authenticate()).status)return{status:!1,error:"Authentication expired and refresh failed"};r=await this.httpClient.get(od.BALANCE_CHANGES,{params:n})}return 200===r.code&&r.data?{status:!0,data:r.data}:{status:!1,error:r.message||"Failed to get balance changes"}}catch(e){return{status:!1,error:Mg(e)}}}async getOraclePrice(e){try{if(!e)return{status:!1,error:"Symbol is required"};const t=await this.httpClient.get(od.ORACLE,{params:{symbol:e}});return 200===t.code&&void 0!==t.data?{status:!0,data:String(t.data)}:{status:!1,error:t.message||"Failed to get oracle price"}}catch(e){return{status:!1,error:Mg(e)}}}async addMargin(e){const t=await this.buildMarginTransaction(e,"add");if(t)return Od(this.suiClient,t,this.keypair);const n=this.buildMarginCallArgs(e,"add"),r=Ed(this.deploymentConfig,n,void 0,n.gasBudget,this.keypair.getPublicKey().toSuiAddress());return Od(this.suiClient,r,this.keypair)}async removeMargin(e){const t=await this.buildMarginTransaction(e,"remove");if(t)return Od(this.suiClient,t,this.keypair);const n=this.buildMarginCallArgs(e,"remove"),r=Sd(this.deploymentConfig,n,void 0,n.gasBudget,this.keypair.getPublicKey().toSuiAddress());return Od(this.suiClient,r,this.keypair)}buildMarginCallArgs(t,n){const{amount:r,accountAddress:s,symbol:i,market:a,perpId:o,subAccountsMapId:c,gasBudget:u,txHash:d}=t;if(!this.isPositiveNumber(r))throw new Error(`Amount must be greater than zero to ${n} margin`);const l=new e(r).toNumber();if(!Number.isFinite(l))throw new Error("Amount is too large to represent as a number");const h=a||i,p=h?h.toUpperCase():void 0,f=o||(p?this.resolvePerpIdFromDeployment(p):void 0);if(!p&&!f)throw new Error("Either market/symbol or perpId must be provided for margin adjustments");return{amount:l,account:s||this.walletAddress,market:p,perpID:f,subAccountsMapID:c,gasBudget:u,txHash:d}}getDeploymentProtocolConfigId(){const e=this.deploymentConfig?.objects?.ProtocolConfig?.id;if(!e)throw new Error("Deployment config missing ProtocolConfig id");return e}async buildMarginTransaction(e,t){const n=this.buildMarginCallArgs(e,t),r=(n.market?await this.buildUpdatePriceTransaction(n.market):void 0)||new Ba;return"add"===t?Ed(this.deploymentConfig,n,r,e.gasBudget):Sd(this.deploymentConfig,n,r,e.gasBudget)}async buildUpdatePriceTransaction(e){if(e)try{return"mainnet"===this.options.network?await this.buildMainnetPriceUpdateTransaction(e):await this.buildTestnetPriceUpdateTransaction(e)}catch(e){return}}async buildMainnetPriceUpdateTransaction(e){const t=this.getPriceInfoObjectId(e),n=await this.resolvePriceFeedId(e);if(!t||!n)return;if(this.ensurePythClients(),!this.priceServiceConnection||!this.pythClient)return;const r=new Ba,s=[n],i=await this.priceServiceConnection.getPriceFeedsUpdateData(s),[a,o]=await this.suiClient.multiGetObjects({ids:[t,"0x6"],options:{showContent:!0,showBcs:!0,showType:!0}}),c=this.extractOracleArrivalTime(a);return this.extractClockTimeSeconds(o)-c>5&&await this.pythClient.updatePriceFeeds(r,i,s),r}async buildTestnetPriceUpdateTransaction(e){try{const t=await Id(this.suiClient,this.deploymentConfig,e);if(null==t)return;return xd(this.deploymentConfig,{price:Number(t),market:e})}catch(e){return}}getPriceInfoObjectId(e){const t=e?.toUpperCase(),n=this.getDeploymentMarket(t);return n?.Objects?.PriceInfoObject?.id}getDeploymentMarket(e){if(!e)return;const t=this.deploymentConfig?.markets,n=e.toUpperCase();return t?.[n]||t?.[e]}async resolvePriceFeedId(e){const t=e?.toUpperCase(),n=this.getDeploymentMarket(t),r=n?.Config?.priceInfoFeedId||n?.Config?.priceIdentifierId;if(r)return r;const s=(await this.getCachedTradingPairs()).find(n=>n.symbol?.toUpperCase()===t||n.symbol===e);return s?s.priceIdentifierId||s.priceInfoFeedId:void 0}async getCachedTradingPairs(){const e=this.tradingPairsCacheTimestamp?Date.now()-this.tradingPairsCacheTimestamp:1/0;if(this.tradingPairsCache&&e<6e4)return this.tradingPairsCache;const t=await this.getTradingPairs();return t.status&&t.data?(this.tradingPairsCache=t.data,this.tradingPairsCacheTimestamp=Date.now(),t.data):this.tradingPairsCache||[]}ensurePythClients(){const e=dd[this.options.network];e&&(this.priceServiceConnection||(this.priceServiceConnection=new rd(e.priceServiceUrl)),this.pythClient||(this.pythClient=new id(this.suiClient,e.pythStateId,e.wormholeStateId)))}extractOracleArrivalTime(e){const t=e?.data?.content&&"fields"in e.data.content&&e.data.content.fields?.price_info?.fields?.arrival_time;if("number"==typeof t)return t;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e:0}return 0}extractClockTimeSeconds(e){const t=e?.data?.content&&"fields"in e.data.content&&e.data.content.fields?.timestamp_ms;if("number"==typeof t)return t/1e3;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e/1e3:0}return 0}resolvePerpIdFromDeployment(e){try{const t=function(e,t){return vd(e,t)}(this.deploymentConfig,e);return t||void 0}catch(e){return}}async setSubAccount(e){return await Ad(this.suiClient,this.deploymentConfig,{account:e,status:!0},this.keypair)}async depositToBank(e){return await Td(this.suiClient,this.deploymentConfig,{amount:$g(e,ud.USDC),accountAddress:this.address},this.keypair)}async withdrawFromBank(e){return await _d(this.suiClient,this.deploymentConfig,{amount:$g(e,ud.USDC),accountAddress:this.address},this.keypair)}async getAllBalances(e){try{return{status:!0,data:await this.suiClient.getAllBalances({owner:e||this.walletAddress})}}catch(e){return{status:!1,error:Mg(e)}}}async getCoinMetadata(e){try{const t=await this.suiClient.getCoinMetadata({coinType:e});return t?{status:!0,data:{decimals:t.decimals,symbol:t.symbol,name:t.name}}:{status:!1,error:"Coin metadata not found"}}catch(e){return{status:!1,error:Mg(e)}}}getVaultPackageId(){const e=this.deploymentConfig?.vaultPackage;if(!e)throw new Error("Deployment config missing vaultPackage");return e}getVaultConfigId(){const e=this.deploymentConfig?.objects?.VaultConfig?.id;if(!e)throw new Error("Deployment config missing VaultConfig id");return e}getBankId(){const e=this.deploymentConfig?.objects?.Bank?.id;if(!e)throw new Error("Deployment config missing Bank id");return e}getTxIndexerId(){const e=this.deploymentConfig?.objects?.TxIndexer?.id;if(!e)throw new Error("Deployment config missing TxIndexer id");return e}getSubAccountsId(){const e=this.deploymentConfig?.objects?.SubAccounts?.id;if(!e)throw new Error("Deployment config missing SubAccounts id");return e}getCurrencyType(){const e=this.deploymentConfig?.objects?.Currency?.dataType;if(!e)throw new Error("Deployment config missing Currency dataType");return e}getMarketSymbols(){return Object.keys(this.deploymentConfig?.markets||{})}getVaultPerpetualId(e){const t=this.deploymentConfig?.markets?.[e]?.Objects?.Perpetual?.id;if(!t)throw new Error(`Deployment config missing Perpetual id for ${e}`);return t}getVaultPriceInfoObjectId(e){const t=this.deploymentConfig?.markets?.[e]?.Objects?.PriceInfoObject?.id;if(!t)throw new Error(`Deployment config missing PriceInfoObject id for ${e}`);return t}async buildVaultNavTransaction(e,t,n){const r=n||new Ba,s=this.getVaultPackageId(),i=this.getCurrencyType(),a=t&&t.length>0?t:this.getMarketSymbols();if("testnet"===this.options.network){const e=[];for(const t of a)try{const n=await Id(this.suiClient,this.deploymentConfig,t);null!=n&&e.push({price:Number(n),market:t})}catch{}e.length>0&&function(e,t,n,r,s){let i=n||new Ba;for(const n of t.prices)i=xd(e,n,i,void 0,void 0);r&&i.setGasBudget(r),s&&i.setSender(s)}(this.deploymentConfig,{prices:e},r)}const[o]=r.moveCall({target:`${s}::vault::new_vault_nav`,arguments:[r.object(this.getDeploymentProtocolConfigId()),r.object(this.getVaultConfigId()),r.object(e),r.object(this.getBankId())],typeArguments:[i]});for(const e of a){const t=this.getVaultPerpetualId(e),n=this.getVaultPriceInfoObjectId(e);r.moveCall({target:`${s}::vault::compute_perpetual_position_value`,arguments:[o,r.object("0x6"),r.object(t),r.object(n)],typeArguments:[]})}return{nav:o,tx:r}}async signAndExecuteVaultTx(e){return e.setSender(this.keypair.getPublicKey().toSuiAddress()),await this.suiClient.signAndExecuteTransaction({signer:this.keypair,transaction:e,options:{showEffects:!0,showObjectChanges:!0}})}async createVault(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::create_vault`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object("0x6"),t.object(this.getVaultConfigId()),t.object(this.getSubAccountsId()),t.object(this.getBankId()),t.object(this.getTxIndexerId()),t.pure.string(e.name),t.pure.address(e.trader),t.pure.u128($g(e.maxCap)),t.pure.u128($g(e.minDepositAmount)),t.pure.u128(e.creatorMinimumShareRatio),t.pure.u128(e.creatorProfitShareRatio),t.pure.u128($g(e.initialAmount))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async depositToVault(e){const{nav:t,tx:n}=await this.buildVaultNavTransaction(e.vaultID,e.markets),r=this.getVaultPackageId();return n.moveCall({target:`${r}::vault::deposit`,arguments:[n.object(this.getDeploymentProtocolConfigId()),n.object(this.getVaultConfigId()),n.object("0x6"),n.object(this.getBankId()),n.object(this.getTxIndexerId()),n.object(e.vaultID),t,n.pure.u128($g(e.amount))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(n)}async requestWithdrawFromVault(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::request_withdraw`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object("0x6"),t.object(e.vaultID),t.pure.u128($g(e.shares))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async fillWithdrawalRequests(e){const{nav:t,tx:n}=await this.buildVaultNavTransaction(e.vaultID,e.markets),r=this.getVaultPackageId(),s=n.makeMoveVec({elements:e.withdrawalRequestIDs.map(e=>n.object(e))});return n.moveCall({target:`${r}::vault::fill_withdrawal_requests`,arguments:[n.object(this.getDeploymentProtocolConfigId()),n.object(this.getVaultConfigId()),n.object("0x6"),n.object(this.getBankId()),n.object(this.getTxIndexerId()),n.object(e.vaultID),t,s],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(n)}async closeVault(e){const{nav:t,tx:n}=await this.buildVaultNavTransaction(e.vaultID,e.markets),r=this.getVaultPackageId();return n.moveCall({target:`${r}::vault::close_vault_v2`,arguments:[n.object(this.getDeploymentProtocolConfigId()),n.object(this.getVaultConfigId()),n.object(this.getSubAccountsId()),n.object(e.vaultID),n.object(this.getBankId()),n.object("0x6"),t],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(n)}async removeVault(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::remove_vault`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(this.getBankId()),t.object(e.vaultID)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async claimClosedVaultFunds(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::claim_closed_vault_funds`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(this.getBankId()),t.object(this.getTxIndexerId()),t.object(e.vaultID)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultTrader(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_trader`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.object(this.getSubAccountsId()),t.pure.address(e.newTrader)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultSubTrader(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_sub_trader`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.object(this.getSubAccountsId()),t.pure.address(e.subTrader),t.pure.bool(e.status)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultDepositStatus(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_deposit_status`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.pure.bool(e.status)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultMaxCap(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_max_cap`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.pure.u128($g(e.maxCap))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultMinDepositAmount(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_min_deposit_amount`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.pure.u128($g(e.minDepositAmount))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultAutoCloseOnWithdraw(e){const t=new Ba,n=this.getVaultPackageId();return t.moveCall({target:`${n}::vault::set_auto_close_on_withdraw`,arguments:[t.object(this.getDeploymentProtocolConfigId()),t.object(this.getVaultConfigId()),t.object(e.vaultID),t.pure.bool(e.autoCloseOnWithdraw)],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async getVaultInfo(e){try{const t=await this.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return t.data?.content&&"moveObject"===t.data.content.dataType?{status:!0,data:t.data.content.fields}:{status:!1,error:"Vault object not found or not a Move object"}}catch(e){return{status:!1,error:Mg(e)}}}async listVaults(e){try{const t=e||this.walletAddress,n=await this.httpClient.get(od.VAULTS_BY_CREATOR,{params:{address:t}});return 200===n.code?{status:!0,data:n.data||[]}:{status:!1,error:n.message||"Failed to list vaults"}}catch(e){return{status:!1,error:Mg(e)}}}}function zg(e,t){const n=d(t);return new qg(e,n)}export{od as API_ENDPOINTS,ud as DECIMALS,u as DEFAULT_API_URLS,ad as DEFAULT_SLIPPAGE,qg as DipCoinPerpSDK,ld as HttpClient,cd as ONBOARDING_MESSAGE,jd as OrderSide,Cd as OrderType,dd as PYTH_CONFIG,Cg as SignerTypes,Ng as buildSignature,qg as default,Mg as formatError,$g as formatNormalToWei,Rg as formatNormalToWeiBN,Pg as fromExportedKeypair,zg as initDipCoinPerpSDK,d as initSDKOptions,Dg as readFile,Bg as signMessage};
|
|
4
4
|
//# sourceMappingURL=index.esm.js.map
|