dipcoin-cli 0.5.0 → 0.6.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.
Files changed (40) hide show
  1. package/README.md +215 -543
  2. package/dist/cli/commands/account.d.ts.map +1 -1
  3. package/dist/cli/commands/balance.d.ts.map +1 -1
  4. package/dist/cli/commands/history.d.ts.map +1 -1
  5. package/dist/cli/commands/market.d.ts.map +1 -1
  6. package/dist/cli/commands/orders.d.ts +3 -0
  7. package/dist/cli/commands/orders.d.ts.map +1 -0
  8. package/dist/cli/commands/position.d.ts.map +1 -1
  9. package/dist/cli/commands/sub-account.d.ts +3 -0
  10. package/dist/cli/commands/sub-account.d.ts.map +1 -0
  11. package/dist/cli/commands/trade.d.ts.map +1 -1
  12. package/dist/cli/commands/vault.d.ts +0 -1
  13. package/dist/cli/commands/vault.d.ts.map +1 -1
  14. package/dist/cli/index.d.ts +1 -1
  15. package/dist/cli/index.d.ts.map +1 -1
  16. package/dist/cli/utils/output.d.ts +8 -0
  17. package/dist/cli/utils/output.d.ts.map +1 -1
  18. package/dist/cli/utils/sdk-factory.d.ts +35 -2
  19. package/dist/cli/utils/sdk-factory.d.ts.map +1 -1
  20. package/dist/cli/utils/vault-index.d.ts +6 -0
  21. package/dist/cli/utils/vault-index.d.ts.map +1 -0
  22. package/dist/cli.cjs +1179 -217
  23. package/dist/cli.cjs.map +1 -0
  24. package/dist/config/deployed/testnet/main_contract.json +58 -275
  25. package/dist/index.cjs.js +2 -2
  26. package/dist/index.cjs.js.map +1 -1
  27. package/dist/index.esm.js +2 -2
  28. package/dist/index.esm.js.map +1 -1
  29. package/dist/index.mjs +2 -2
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/src/config/index.d.ts.map +1 -1
  32. package/dist/src/constants/index.d.ts +1 -0
  33. package/dist/src/constants/index.d.ts.map +1 -1
  34. package/dist/src/sdk/sdk.d.ts +117 -1
  35. package/dist/src/sdk/sdk.d.ts.map +1 -1
  36. package/dist/src/types/index.d.ts +6 -1
  37. package/dist/src/types/index.d.ts.map +1 -1
  38. package/dist/src/utils/jwt-cache.d.ts +14 -0
  39. package/dist/src/utils/jwt-cache.d.ts.map +1 -0
  40. package/package.json +7 -10
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@dipcoinlab/perp-ts-library"),t=require("bignumber.js"),n=require("node:buffer"),r=require("axios"),s=require("child_process"),i=require("buffer"),a=require("fs"),o=require("path"),c=require("url");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=u(t),l=u(r),h=u(a),p=u(o);const f={mainnet:"https://gray-api.dipcoin.io",testnet:"https://demoapi.dipcoin.io/exchange"};function g(e){return{apiBaseUrl:e.apiBaseUrl||f[e.network],network:e.network,customRpc:e.customRpc}}const m="1.45.0",y={"-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 b extends Error{}class w extends b{constructor(e,t){super(e),this.code=t,this.type=y[t]??"ServerError"}}class v extends b{constructor(e,t,n){super(e),this.status=t,this.statusText=n}}var E,k,S,O,x,T,I,_,A,C=e=>{throw TypeError(e)},j=(e,t,n)=>t.has(e)||C("Cannot "+n),P=(e,t,n)=>(j(e,t,"read from private field"),n?n.call(e):t.get(e)),B=(e,t,n)=>t.has(e)?C("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),N=(e,t,n,r)=>(j(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),R=(e,t,n)=>(j(e,t,"access private method"),n);const $={WebSocketConstructor:"undefined"!=typeof WebSocket?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class M{constructor(e,t={}){if(B(this,I),B(this,E,0),B(this,k,0),B(this,S,null),B(this,O,null),B(this,x,new Set),B(this,T,new Map),this.endpoint=e,this.options={...$,...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 R(this,I,_).call(this);return new Promise((s,i)=>{N(this,E,P(this,E)+1),P(this,T).set(P(this,E),{resolve:s,reject:i,timeout:setTimeout(()=>{P(this,T).delete(P(this,E)),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n?.addEventListener("abort",()=>{P(this,T).delete(P(this,E)),i(n.reason)}),r.send(JSON.stringify({jsonrpc:"2.0",id:P(this,E),method:e,params:t}))}).then(({error:e,result:t})=>{if(e)throw new w(e.message,e.code);return t})}async subscribe(e){const t=new U(e);return P(this,x).add(t),await t.subscribe(this),()=>t.unsubscribe(this)}}E=new WeakMap,k=new WeakMap,S=new WeakMap,O=new WeakMap,x=new WeakMap,T=new WeakMap,I=new WeakSet,_=function(){return P(this,O)||N(this,O,new Promise(e=>{P(this,S)?.close(),N(this,S,new this.options.WebSocketConstructor(this.endpoint)),P(this,S).addEventListener("open",()=>{N(this,k,0),e(P(this,S))}),P(this,S).addEventListener("close",()=>{var e,t,n,r;(e=this,t=k,{set _(r){N(e,t,r,n)},get _(){return P(e,t,r)}})._++,P(this,k)<=this.options.maxReconnects&&setTimeout(()=>{R(this,I,A).call(this)},this.options.reconnectTimeout)}),P(this,S).addEventListener("message",({data:e})=>{let t;try{t=JSON.parse(e)}catch(e){return}if("id"in t&&null!=t.id&&P(this,T).has(t.id)){const{resolve:e,timeout:n}=P(this,T).get(t.id);clearTimeout(n),e(t)}else if("params"in t){const{params:e}=t;P(this,x).forEach(t=>{t.subscriptionId===e.subscription&&e.subscription===t.subscriptionId&&t.onMessage(e.result)})}})})),P(this,O)},A=async function(){return P(this,S)?.close(),N(this,O,null),Promise.allSettled([...P(this,x)].map(e=>e.subscribe(this)))};class U{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 D,F,L,V,K,q=e=>{throw TypeError(e)},z=(e,t,n)=>t.has(e)||q("Cannot "+n),Z=(e,t,n)=>(z(e,t,"read from private field"),n?n.call(e):t.get(e)),W=(e,t,n)=>t.has(e)?q("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),G=(e,t,n,r)=>(z(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class H{constructor(e){W(this,V),W(this,D,0),W(this,F),W(this,L),G(this,F,e)}fetch(e,t){const n=Z(this,F).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){G(this,D,Z(this,D)+1);const t=await this.fetch(Z(this,F).rpc?.url??Z(this,F).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":m,"Client-Target-Api-Version":"1.61.0","Client-Request-Method":e.method,...Z(this,F).rpc?.headers},body:JSON.stringify({jsonrpc:"2.0",id:Z(this,D),method:e.method,params:e.params})});if(!t.ok)throw new v(`Unexpected status code: ${t.status}`,t.status,t.statusText);const n=await t.json();if("error"in n&&null!=n.error)throw new w(n.error.message,n.error.code);return n.result}async subscribe(e){const t=await(n=this,r=V,s=K,z(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()}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@dipcoinlab/perp-ts-library"),t=require("bignumber.js"),n=require("node:buffer"),r=require("axios"),s=require("child_process"),i=require("buffer"),a=require("fs"),o=require("path"),c=require("url"),u=require("os");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=d(t),h=d(r),p=d(a),f=d(o),g=d(u);const m={mainnet:"https://gray-api.dipcoin.io",testnet:"https://demoapi.dipcoin.io/exchange"};function y(e){return{apiBaseUrl:e.apiBaseUrl||m[e.network],network:e.network,customRpc:e.customRpc,subAccountKey:e.subAccountKey}}const b="1.45.0",w={"-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 v extends Error{}class k extends v{constructor(e,t){super(e),this.code=t,this.type=w[t]??"ServerError"}}class E extends v{constructor(e,t,n){super(e),this.status=t,this.statusText=n}}var S,x,O,T,I,_,A,C,j,P=e=>{throw TypeError(e)},B=(e,t,n)=>t.has(e)||P("Cannot "+n),N=(e,t,n)=>(B(e,t,"read from private field"),n?n.call(e):t.get(e)),R=(e,t,n)=>t.has(e)?P("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),$=(e,t,n,r)=>(B(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),M=(e,t,n)=>(B(e,t,"access private method"),n);const D={WebSocketConstructor:"undefined"!=typeof WebSocket?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class U{constructor(e,t={}){if(R(this,A),R(this,S,0),R(this,x,0),R(this,O,null),R(this,T,null),R(this,I,new Set),R(this,_,new Map),this.endpoint=e,this.options={...D,...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 M(this,A,C).call(this);return new Promise((s,i)=>{$(this,S,N(this,S)+1),N(this,_).set(N(this,S),{resolve:s,reject:i,timeout:setTimeout(()=>{N(this,_).delete(N(this,S)),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n?.addEventListener("abort",()=>{N(this,_).delete(N(this,S)),i(n.reason)}),r.send(JSON.stringify({jsonrpc:"2.0",id:N(this,S),method:e,params:t}))}).then(({error:e,result:t})=>{if(e)throw new k(e.message,e.code);return t})}async subscribe(e){const t=new V(e);return N(this,I).add(t),await t.subscribe(this),()=>t.unsubscribe(this)}}S=new WeakMap,x=new WeakMap,O=new WeakMap,T=new WeakMap,I=new WeakMap,_=new WeakMap,A=new WeakSet,C=function(){return N(this,T)||$(this,T,new Promise(e=>{N(this,O)?.close(),$(this,O,new this.options.WebSocketConstructor(this.endpoint)),N(this,O).addEventListener("open",()=>{$(this,x,0),e(N(this,O))}),N(this,O).addEventListener("close",()=>{var e,t,n,r;(e=this,t=x,{set _(r){$(e,t,r,n)},get _(){return N(e,t,r)}})._++,N(this,x)<=this.options.maxReconnects&&setTimeout(()=>{M(this,A,j).call(this)},this.options.reconnectTimeout)}),N(this,O).addEventListener("message",({data:e})=>{let t;try{t=JSON.parse(e)}catch(e){return}if("id"in t&&null!=t.id&&N(this,_).has(t.id)){const{resolve:e,timeout:n}=N(this,_).get(t.id);clearTimeout(n),e(t)}else if("params"in t){const{params:e}=t;N(this,I).forEach(t=>{t.subscriptionId===e.subscription&&e.subscription===t.subscriptionId&&t.onMessage(e.result)})}})})),N(this,T)},j=async function(){return N(this,O)?.close(),$(this,T,null),Promise.allSettled([...N(this,I)].map(e=>e.subscribe(this)))};class V{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 F,L,K,q,z,Z=e=>{throw TypeError(e)},W=(e,t,n)=>t.has(e)||Z("Cannot "+n),G=(e,t,n)=>(W(e,t,"read from private field"),n?n.call(e):t.get(e)),H=(e,t,n)=>t.has(e)?Z("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),J=(e,t,n,r)=>(W(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class Y{constructor(e){H(this,q),H(this,F,0),H(this,L),H(this,K),J(this,L,e)}fetch(e,t){const n=G(this,L).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){J(this,F,G(this,F)+1);const t=await this.fetch(G(this,L).rpc?.url??G(this,L).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":b,"Client-Target-Api-Version":"1.61.0","Client-Request-Method":e.method,...G(this,L).rpc?.headers},body:JSON.stringify({jsonrpc:"2.0",id:G(this,F),method:e.method,params:e.params})});if(!t.ok)throw new E(`Unexpected status code: ${t.status}`,t.status,t.statusText);const n=await t.json();if("error"in n&&null!=n.error)throw new k(n.error.message,n.error.code);return n.result}async subscribe(e){const t=await(n=this,r=q,s=z,W(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 J(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Y(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function X(e){if("function"!=typeof e)throw new Error("function expected");return!0}function Q(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function ee(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function te(e){if(!Array.isArray(e))throw new Error("array expected")}function ne(e,t){if(!Y(!0,t))throw new Error(`${e}: array of strings expected`)}function re(e,t){if(!Y(!1,t))throw new Error(`${e}: array of numbers expected`)}function se(...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 ie(e){const t="string"==typeof e?e.split(""):e,n=t.length;ne("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(te(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=>(te(t),t.map(t=>{Q("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function ae(e=""){return Q("join",e),{encode:t=>(ne("join.decode",t),t.join(e)),decode:t=>(Q("join.decode",t),t.split(e))}}function oe(e,t="="){return ee(e),Q("padding",t),{encode(n){for(ne("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){ne("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 ce(e){return X(e),{encode:e=>e,decode:t=>e(t)}}function ue(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(te(e),!e.length)return[];let r=0;const s=[],i=Array.from(e,e=>{if(ee(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()}D=new WeakMap,F=new WeakMap,L=new WeakMap,V=new WeakSet,K=function(){if(!Z(this,L)){const e=Z(this,F).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");G(this,L,new M(Z(this,F).websocket?.url??Z(this,F).url,{WebSocketConstructor:e,...Z(this,F).websocket}))}return Z(this,L)};const de=(e,t)=>0===t?e:de(t,e%t),le=(e,t)=>e+(t-de(e,t)),he=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function pe(e,t,n,r){if(te(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(le(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${le(t,n)}`);let s=0,i=0;const a=he[t],o=he[n]-1,c=[];for(const r of e){if(ee(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=he[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 fe(e,t=!1){if(ee(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(le(8,e)>32||le(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!J(n))throw new Error("radix2.encode input should be Uint8Array");return pe(Array.from(n),8,e,!t)},decode:n=>(re("radix2.decode",n),Uint8Array.from(pe(n,e,8,t)))}}function ge(e){return X(e),function(...t){try{return e.apply(null,t)}catch(e){}}}se(fe(4),ie("0123456789ABCDEF"),ae("")),se(fe(5),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),oe(5),ae("")),se(fe(5),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ae("")),se(fe(5),ie("0123456789ABCDEFGHIJKLMNOPQRSTUV"),oe(5),ae("")),se(fe(5),ie("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ae("")),se(fe(5),ie("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ae(""),ce(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const me=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();me||se(fe(6),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),oe(6),ae("")),se(fe(6),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ae("")),me||se(fe(6),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),oe(6),ae("")),se(fe(6),ie("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ae(""));const ye=e=>{return se((ee(t=58),{encode:e=>{if(!J(e))throw new Error("radix.encode input should be Uint8Array");return ue(Array.from(e),256,t)},decode:e=>(re("radix.decode",e),Uint8Array.from(ue(e,t,256)))}),ie(e),ae(""));var t},be=ye("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");ye("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),ye("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const we=se(ie("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ae("")),ve=[996825010,642813549,513874426,1027748829,705979059];function Ee(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<ve.length;e++)1==(t>>e&1)&&(n^=ve[e]);return n}function ke(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=Ee(s)^n>>5}s=Ee(s);for(let t=0;t<r;t++)s=Ee(s)^31&e.charCodeAt(t);for(let e of t)s=Ee(s)^e;for(let e=0;e<6;e++)s=Ee(s);return s^=n,we.encode(pe([s%he[30]],30,5,!1))}function Se(e){const t="bech32"===e?1:734539939,n=fe(5),r=n.decode,s=n.encode,i=ge(r);function a(e,n,r=90){Q("bech32.encode prefix",e),J(n)&&(n=Array.from(n)),re("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=ke(a,n,t);return`${a}1${we.encode(n)}${o}`}function o(e,n=90){Q("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=we.decode(o).slice(0,-6),u=ke(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:ge(o),fromWords:r,fromWordsUnsafe:i,toWords:s}}const Oe=Se("bech32");Se("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||se(fe(4),ie("0123456789abcdef"),ae(""),ce(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 xe=e=>be.encode(e),Te=e=>be.decode(e);function Ie(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}const _e=8192;function Ae(e){if(e.length<_e)return btoa(String.fromCharCode(...e));let t="";for(var n=0;n<e.length;n+=_e){const r=e.slice(n,n+_e);t+=String.fromCharCode(...r)}return btoa(t)}function Ce(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 je(e){return e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Pe(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}class Be{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 Ne;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 Me(t);let n;try{n=e._batchLoadFn(t.keys)}catch(n){return $e(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 $e(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(!Ue(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)}`);Me(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=>{$e(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(!Ue(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 Ne="object"==typeof process&&"function"==typeof process.nextTick?function(e){Re||(Re=Promise.resolve()),Re.then(()=>{process.nextTick(e)})}:"function"==typeof setImmediate?function(e){setImmediate(e)}:function(e){setTimeout(e)};let Re;function $e(e,t,n){Me(t);for(let r=0;r<t.keys.length;r++)e.clear(t.keys[r]),t.callbacks[r].reject(n)}function Me(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Ue(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 De(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 Fe{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 Le(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 Ve{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 Ke(BigInt(e),8).forEach(e=>this.write8(e)),this}write128(e){return Ke(BigInt(e),16).forEach(e=>this.write8(e)),this}write256(e){return Ke(BigInt(e),32).forEach(e=>this.write8(e)),this}writeULEB(e){return De(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 xe(e);case"base64":return Ae(e);case"hex":return je(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}(this.toBytes(),e)}}function Ke(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 qe,ze,Ze,We,Ge=e=>{throw TypeError(e)},He=(e,t,n)=>t.has(e)||Ge("Cannot "+n),Je=(e,t,n)=>(He(e,t,"read from private field"),n?n.call(e):t.get(e)),Ye=(e,t,n)=>t.has(e)?Ge("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Xe=(e,t,n,r)=>(He(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);qe=new WeakMap,ze=new WeakMap;let Qe=class e{constructor(e){Ye(this,qe),Ye(this,ze),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Xe(this,qe,e.write),Xe(this,ze,e.serialize??((e,t)=>{const n=new Ve({initialSize:this.serializedSize(e)??void 0,...t});return Je(this,qe).call(this,e,n),n.toBytes()})),this.validate=e.validate??(()=>{})}write(e,t){this.validate(e),Je(this,qe).call(this,e,t)}serialize(e,t){return this.validate(e),new nt(this,Je(this,ze).call(this,e,t))}parse(e){const t=new Fe(e);return this.read(t)}fromHex(e){return this.parse(Ce(e))}fromBase58(e){return this.parse(Te(e))}fromBase64(e){return this.parse(Ie(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)=>Je(this,qe).call(this,n?n(e):e,t),serializedSize:e=>this.serializedSize(n?n(e):e),serialize:(e,t)=>Je(this,ze).call(this,n?n(e):e,t),validate:e=>{s?.(e),this.validate(n?n(e):e)}})}};const et=Symbol.for("@mysten/serialized-bcs");function tt(e){return!!e&&"object"==typeof e&&!0===e[et]}class nt{constructor(e,t){Ye(this,Ze),Ye(this,We),Xe(this,Ze,e),Xe(this,We,t)}get[et](){return!0}toBytes(){return Je(this,We)}toHex(){return je(Je(this,We))}toBase64(){return Ae(Je(this,We))}toBase58(){return xe(Je(this,We))}parse(){return Je(this,Ze).parse(Je(this,We))}}function rt({size:e,...t}){return new Qe({...t,serializedSize:()=>e})}function st({readMethod:e,writeMethod:t,...n}){return rt({...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 it({readMethod:e,writeMethod:t,...n}){return rt({...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)}})}Ze=new WeakMap,We=new WeakMap;class at extends Qe{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 ot extends Qe{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 ct extends Qe{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 ut={u8:e=>st({readMethod:"read8",writeMethod:"write8",size:1,maxValue:255,...e,name:e?.name??"u8"}),u16:e=>st({readMethod:"read16",writeMethod:"write16",size:2,maxValue:65535,...e,name:e?.name??"u16"}),u32:e=>st({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:e?.name??"u32"}),u64:e=>it({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:e?.name??"u64"}),u128:e=>it({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:e?.name??"u128"}),u256:e=>it({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:e?.name??"u256"}),bool:e=>rt({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 Qe({...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(De(e)),...e,name:e?.name??"uleb128"}),bytes:(e,t)=>rt({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 Qe({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:De(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 Qe({...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=De(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 Qe({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 ut.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 Qe({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 ct({fields:e,...t}),struct:(e,t,n)=>new at({name:e,fields:t,...n}),enum:(e,t,n)=>new ot({name:e,fields:t,...n}),map:function(e,t){return ut.vector(ut.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 Qe({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 dt,lt,ht=e=>{throw TypeError(e)},pt=(e,t,n)=>t.has(e)||ht("Cannot "+n),ft=(e,t,n)=>(pt(e,t,"read from private field"),n?n.call(e):t.get(e)),gt=(e,t,n)=>t.has(e)?ht("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),mt=(e,t,n,r)=>(pt(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);dt=new WeakMap,lt=new WeakMap;let yt=class e{constructor({prefix:e,cache:t}={}){gt(this,dt),gt(this,lt),mt(this,dt,e??[]),mt(this,lt,t??new Map)}read(e,t){const n=[ft(this,dt),...e].join(":");if(ft(this,lt).has(n))return ft(this,lt).get(n);const r=t();return ft(this,lt).set(n,r),"object"==typeof r&&null!==r&&"then"in r?Promise.resolve(r).then(e=>(ft(this,lt).set(n,e),e)).catch(e=>{throw ft(this,lt).delete(n),e}):r}readSync(e,t){const n=[ft(this,dt),...e].join(":");if(ft(this,lt).has(n))return ft(this,lt).get(n);const r=t();return ft(this,lt).set(n,r),r}clear(e){const t=[...ft(this,dt),...e??[]].join(":");if(t)for(const e of ft(this,lt).keys())e.startsWith(t)&&ft(this,lt).delete(e);else ft(this,lt).clear()}scope(t){return new e({prefix:[...ft(this,dt),...Array.isArray(t)?t:[t]],cache:ft(this,lt)})}};class bt{constructor({network:e,base:t,cache:n=t?.cache??new yt}){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 wt(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 vt(e,t,n,r,s){const i=s&&"input"in s?s.input:n.value,a=s?.expected??e.expects??null,o=s?.received??wt(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 Et(e,t){return Object.hasOwn(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}var kt=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function St(e,t){return{kind:"validation",type:"check",reference:St,async:!1,expects:null,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement(e.value)&&vt(this,"input",e,t),e}}}function Ot(e){return{kind:"validation",type:"integer",reference:Ot,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(e,t){return e.typed&&!this.requirement(e.value)&&vt(this,"integer",e,t),e}}}function xt(e){return{kind:"transformation",type:"transform",reference:xt,async:!1,operation:e,_run(e){return e.value=this.operation(e.value),e}}}function Tt(e,t,n){return"function"==typeof e.default?e.default(t,n):e.default}function It(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function _t(e,t){return{kind:"schema",type:"array",reference:_t,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 vt(this,"type",e,t);return e}}}function At(e){return{kind:"schema",type:"bigint",reference:At,expects:"bigint",async:!1,message:e,_run(e,t){return"bigint"==typeof e.value?e.typed=!0:vt(this,"type",e,t),e}}}function Ct(e){return{kind:"schema",type:"boolean",reference:Ct,expects:"boolean",async:!1,message:e,_run(e,t){return"boolean"==typeof e.value?e.typed=!0:vt(this,"type",e,t),e}}}function jt(e){return{kind:"schema",type:"lazy",reference:jt,expects:"unknown",async:!1,getter:e,_run(e,t){return this.getter(e.value)._run(e,t)}}}function Pt(e,t){return{kind:"schema",type:"literal",reference:Pt,expects:wt(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:vt(this,"type",e,t),e}}}function Bt(e,...t){const n={kind:"schema",type:"nullable",reference:Bt,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(e,t){return null===e.value&&("default"in this&&(e.value=Tt(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 Nt(e,...t){const n={kind:"schema",type:"nullish",reference:Nt,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=Tt(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 Rt(e){return{kind:"schema",type:"number",reference:Rt,expects:"number",async:!1,message:e,_run(e,t){return"number"!=typeof e.value||isNaN(e.value)?vt(this,"type",e,t):e.typed=!0,e}}}function $t(e,t){return{kind:"schema",type:"object",reference:$t,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 vt(this,"type",e,t);return e}}}function Mt(e,...t){const n={kind:"schema",type:"optional",reference:Mt,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(e,t){return void 0===e.value&&("default"in this&&(e.value=Tt(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 Ut(e,t,n){return{kind:"schema",type:"record",reference:Ut,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(Et(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 vt(this,"type",e,t);return e}}}function Dt(e){return{kind:"schema",type:"string",reference:Dt,expects:"string",async:!1,message:e,_run(e,t){return"string"==typeof e.value?e.typed=!0:vt(this,"type",e,t),e}}}function Ft(e,t){return{kind:"schema",type:"tuple",reference:Ft,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 vt(this,"type",e,t);return e}}}function Lt(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function Vt(e,t){return{kind:"schema",type:"union",reference:Vt,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];vt(this,"type",e,t,{issues:Lt(r)}),e.typed=!0}else{if(1===s?.length)return s[0];vt(this,"type",e,t,{issues:Lt(s)})}return e}}}function Kt(){return{kind:"schema",type:"unknown",reference:Kt,expects:"unknown",async:!1,_run:e=>(e.typed=!0,e)}}function qt(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 kt(r.issues);return r.value}function zt(...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 Zt=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Wt=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i;const Gt=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,Ht=/^\d+$/,Jt=e=>{const t=e.split("/");if(t.length<2||t.length>3)return!1;const[n,r,s]=t;return!(void 0!==s&&!Ht.test(s))&&(!!function(e){return!(e.length>235)&&(e.includes("@")?Zt.test(e):Wt.test(e))}(n)&&(Gt.test(r)&&r.length<64))},Yt=e=>{const t=e.split(/::|<|>|,/);for(const e of t)if(e.includes("/")&&!Jt(e))return!1;return!0};function Xt(e){try{return 32===Te(e).length}catch{return!1}}const Qt=32;function en(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)===Qt}function tn(e){return en(e)}function nn(e){const[t,n]=e.split("::"),r=Jt(t),s=e.slice(t.length+n.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?Le(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(e=>function(e){return e.includes("::")?nn(e):e}(e.trim())):[];return{address:r?t:sn(t),module:n,name:i,typeParams:a}}function rn(e){const{address:t,module:n,name:r,typeParams:s}="string"==typeof e?nn(e):e;return`${t}::${n}::${r}${s?.length>0?`<${s.map(e=>"string"==typeof e?e:rn(e)).join(",")}>`:""}`}function sn(e,t=!1){let n=e.toLowerCase();return!t&&n.startsWith("0x")&&(n=n.slice(2)),`0x${n.padStart(64,"0")}`}function an(e,t=!1){return sn(e,t)}function on(e){return zt(Vt(Object.entries(e).map(([e,t])=>$t({[e]:t}))),xt(e=>({...e,$kind:Object.keys(e)[0]})))}const cn=zt(Dt(),xt(e=>sn(e)),St(en)),un=cn,dn=Dt(),ln=zt(Vt([Dt(),zt(Rt(),Ot())]),St(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),hn=$t({objectId:cn,version:ln,digest:Dt()}),pn=zt(Vt([$t({GasCoin:Pt(!0)}),$t({Input:zt(Rt(),Ot()),type:Mt(Pt("pure"))}),$t({Input:zt(Rt(),Ot()),type:Mt(Pt("object"))}),$t({Result:zt(Rt(),Ot())}),$t({NestedResult:Ft([zt(Rt(),Ot()),zt(Rt(),Ot())])})]),xt(e=>({...e,$kind:Object.keys(e)[0]}))),fn=$t({budget:Bt(ln),price:Bt(ln),owner:Bt(cn),payment:Bt(_t(hn))}),gn=Vt([Pt("address"),Pt("bool"),Pt("u8"),Pt("u16"),Pt("u32"),Pt("u64"),Pt("u128"),Pt("u256"),$t({vector:jt(()=>gn)}),$t({datatype:$t({package:Dt(),module:Dt(),type:Dt(),typeParameters:_t(jt(()=>gn))})}),$t({typeParameter:zt(Rt(),Ot())})]),mn=$t({ref:Bt(Vt([Pt("&"),Pt("&mut")])),body:gn}),yn=$t({package:un,module:Dt(),function:Dt(),typeArguments:_t(Dt()),arguments:_t(pn),_argumentTypes:Mt(Bt(_t(mn)))}),bn=$t({name:Dt(),inputs:Ut(Dt(),Vt([pn,_t(pn)])),data:Ut(Dt(),Kt())}),wn=on({MoveCall:yn,TransferObjects:$t({objects:_t(pn),address:pn}),SplitCoins:$t({coin:pn,amounts:_t(pn)}),MergeCoins:$t({destination:pn,sources:_t(pn)}),Publish:$t({modules:_t(dn),dependencies:_t(un)}),MakeMoveVec:$t({type:Bt(Dt()),elements:_t(pn)}),Upgrade:$t({modules:_t(dn),dependencies:_t(un),package:un,ticket:pn}),$Intent:bn}),vn=on({ImmOrOwnedObject:hn,SharedObject:$t({objectId:un,initialSharedVersion:ln,mutable:Ct()}),Receiving:hn}),En=on({Object:vn,Pure:$t({bytes:dn}),UnresolvedPure:$t({value:Kt()}),UnresolvedObject:$t({objectId:un,version:Mt(Bt(ln)),digest:Mt(Bt(Dt())),initialSharedVersion:Mt(Bt(ln)),mutable:Mt(Bt(Ct()))})}),kn=on({Object:vn,Pure:$t({bytes:dn})}),Sn=on({None:Pt(!0),Epoch:ln}),On=$t({version:Pt(2),sender:Nt(cn),expiration:Nt(Sn),gasData:fn,inputs:_t(En),commands:_t(wn)}),xn={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=>qt(pn,e)),address:qt(pn,t)}}),SplitCoins:(e,t)=>({$kind:"SplitCoins",SplitCoins:{coin:qt(pn,e),amounts:t.map(e=>qt(pn,e))}}),MergeCoins:(e,t)=>({$kind:"MergeCoins",MergeCoins:{destination:qt(pn,e),sources:t.map(e=>qt(pn,e))}}),Publish:({modules:e,dependencies:t})=>({$kind:"Publish",Publish:{modules:e.map(e=>"string"==typeof e?e:Ae(new Uint8Array(e))),dependencies:t.map(e=>an(e))}}),Upgrade:({modules:e,dependencies:t,package:n,ticket:r})=>({$kind:"Upgrade",Upgrade:{modules:e.map(e=>"string"==typeof e?e:Ae(new Uint8Array(e))),dependencies:t.map(e=>an(e)),package:n,ticket:qt(pn,r)}}),MakeMoveVec:({type:e,elements:t})=>({$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(e=>qt(pn,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=>qt(pn,e)):qt(pn,t)])),data:n}})},Tn=/^vector<(.+)>$/,In=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class _n{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(Tn);if(n)return{vector:_n.parseFromStr(n[1],t)};const r=e.match(In);if(r){return{struct:{address:t?sn(r[1]):r[1],module:r[2],name:r[3],typeParams:void 0===r[5]?[]:_n.parseStructTypeArgs(r[5],t)}}}throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,t=!1){return Le(e).map(e=>_n.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<${_n.tagToString(e.vector)}>`;if("struct"in e){const t=e.struct,n=t.typeParams.map(_n.tagToString).join(", ");return`${t.address}::${t.module}::${t.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}const An=ut.bytes(Qt).transform({validate:e=>{const t="string"==typeof e?e:je(e);if(!t||!en(sn(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>"string"==typeof e?Ce(sn(e)):e,output:e=>sn(je(e))}),Cn=ut.byteVector().transform({name:"ObjectDigest",input:e=>Te(e),output:e=>xe(new Uint8Array(e)),validate:e=>{if(32!==Te(e).length)throw new Error("ObjectDigest must be 32 bytes")}}),jn=ut.struct("SuiObjectRef",{objectId:An,version:ut.u64(),digest:Cn}),Pn=ut.struct("SharedObjectRef",{objectId:An,initialSharedVersion:ut.u64(),mutable:ut.bool()}),Bn=ut.enum("ObjectArg",{ImmOrOwnedObject:jn,SharedObject:Pn,Receiving:jn}),Nn=ut.enum("Owner",{AddressOwner:An,ObjectOwner:An,Shared:ut.struct("Shared",{initialSharedVersion:ut.u64()}),Immutable:null,ConsensusAddressOwner:ut.struct("ConsensusAddressOwner",{owner:An,startVersion:ut.u64()})}),Rn=ut.enum("CallArg",{Pure:ut.struct("Pure",{bytes:ut.byteVector().transform({input:e=>"string"==typeof e?Ie(e):e,output:e=>Ae(new Uint8Array(e))})}),Object:Bn}),$n=ut.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:ut.lazy(()=>$n),struct:ut.lazy(()=>Zn),u16:null,u32:null,u256:null}),Mn=$n.transform({input:e=>"string"==typeof e?_n.parseFromStr(e,!0):e,output:e=>_n.tagToString(e)}),Un=ut.enum("Argument",{GasCoin:null,Input:ut.u16(),Result:ut.u16(),NestedResult:ut.tuple([ut.u16(),ut.u16()])}),Dn=ut.struct("ProgrammableMoveCall",{package:An,module:ut.string(),function:ut.string(),typeArguments:ut.vector(Mn),arguments:ut.vector(Un)}),Fn=ut.enum("Command",{MoveCall:Dn,TransferObjects:ut.struct("TransferObjects",{objects:ut.vector(Un),address:Un}),SplitCoins:ut.struct("SplitCoins",{coin:Un,amounts:ut.vector(Un)}),MergeCoins:ut.struct("MergeCoins",{destination:Un,sources:ut.vector(Un)}),Publish:ut.struct("Publish",{modules:ut.vector(ut.byteVector().transform({input:e=>"string"==typeof e?Ie(e):e,output:e=>Ae(new Uint8Array(e))})),dependencies:ut.vector(An)}),MakeMoveVec:ut.struct("MakeMoveVec",{type:(Ln=Mn,ut.enum("Option",{None:null,Some:Ln})).transform({input:e=>null===e?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:ut.vector(Un)}),Upgrade:ut.struct("Upgrade",{modules:ut.vector(ut.byteVector().transform({input:e=>"string"==typeof e?Ie(e):e,output:e=>Ae(new Uint8Array(e))})),dependencies:ut.vector(An),package:An,ticket:Un})});var Ln;const Vn=ut.struct("ProgrammableTransaction",{inputs:ut.vector(Rn),commands:ut.vector(Fn)}),Kn=ut.enum("TransactionKind",{ProgrammableTransaction:Vn,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),qn=ut.enum("TransactionExpiration",{None:null,Epoch:ut.u64({name:"unsafe_u64",...zn}).transform({input:e=>e,output:e=>Number(e)})});var zn;const Zn=ut.struct("StructTag",{address:An,module:ut.string(),name:ut.string(),typeParams:ut.vector($n)}),Wn=ut.struct("GasData",{payment:ut.vector(jn),owner:An,price:ut.u64(),budget:ut.u64()}),Gn=ut.struct("TransactionDataV1",{kind:Kn,sender:An,gasData:Wn,expiration:qn}),Hn=ut.enum("TransactionData",{V1:Gn}),Jn=ut.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Yn=ut.enum("IntentVersion",{V0:null}),Xn=ut.enum("AppId",{Sui:null}),Qn=ut.struct("Intent",{scope:Jn,version:Yn,appId:Xn});function er(e){return ut.struct(`IntentMessage<${e.name}>`,{intent:Qn,value:e})}const tr=ut.enum("CompressedSignature",{ED25519:ut.bytes(64),Secp256k1:ut.bytes(64),Secp256r1:ut.bytes(64),ZkLogin:ut.byteVector(),Passkey:ut.byteVector()}),nr=ut.enum("PublicKey",{ED25519:ut.bytes(32),Secp256k1:ut.bytes(33),Secp256r1:ut.bytes(33),ZkLogin:ut.byteVector(),Passkey:ut.bytes(33)}),rr=ut.struct("MultiSigPkMap",{pubKey:nr,weight:ut.u8()}),sr=ut.struct("MultiSigPublicKey",{pk_map:ut.vector(rr),threshold:ut.u16()}),ir=ut.struct("MultiSig",{sigs:ut.vector(tr),bitmap:ut.u16(),multisig_pk:sr}),ar=ut.byteVector().transform({input:e=>"string"==typeof e?Ie(e):e,output:e=>Ae(new Uint8Array(e))}),or=ut.struct("SenderSignedTransaction",{intentMessage:er(Hn),txSignatures:ut.vector(ar)}),cr=ut.vector(or,{name:"SenderSignedData"}),ur=ut.struct("PasskeyAuthenticator",{authenticatorData:ut.byteVector(),clientDataJson:ut.string(),userSignature:ut.byteVector()}),dr=ut.enum("PackageUpgradeError",{UnableToFetchPackage:ut.struct("UnableToFetchPackage",{packageId:An}),NotAPackage:ut.struct("NotAPackage",{objectId:An}),IncompatibleUpgrade:null,DigestDoesNotMatch:ut.struct("DigestDoesNotMatch",{digest:ut.byteVector()}),UnknownUpgradePolicy:ut.struct("UnknownUpgradePolicy",{policy:ut.u8()}),PackageIDDoesNotMatch:ut.struct("PackageIDDoesNotMatch",{packageId:An,ticketId:An})}),lr=ut.struct("ModuleId",{address:An,name:ut.string()}),hr=ut.struct("MoveLocation",{module:lr,function:ut.u16(),instruction:ut.u16(),functionName:ut.option(ut.string())}),pr=ut.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:ut.struct("IndexOutOfBounds",{idx:ut.u16()}),SecondaryIndexOutOfBounds:ut.struct("SecondaryIndexOutOfBounds",{resultIdx:ut.u16(),secondaryIdx:ut.u16()}),InvalidResultArity:ut.struct("InvalidResultArity",{resultIdx:ut.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),fr=ut.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),gr=ut.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:ut.struct("MoveObjectTooBig",{objectSize:ut.u64(),maxObjectSize:ut.u64()}),MovePackageTooBig:ut.struct("MovePackageTooBig",{objectSize:ut.u64(),maxObjectSize:ut.u64()}),CircularObjectOwnership:ut.struct("CircularObjectOwnership",{object:An}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:ut.option(hr),MoveAbort:ut.tuple([hr,ut.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:ut.struct("CommandArgumentError",{argIdx:ut.u16(),kind:pr}),TypeArgumentError:ut.struct("TypeArgumentError",{argumentIdx:ut.u16(),kind:fr}),UnusedValueWithoutDrop:ut.struct("UnusedValueWithoutDrop",{resultIdx:ut.u16(),secondaryIdx:ut.u16()}),InvalidPublicFunctionReturnType:ut.struct("InvalidPublicFunctionReturnType",{idx:ut.u16()}),InvalidTransferObject:null,EffectsTooLarge:ut.struct("EffectsTooLarge",{currentSize:ut.u64(),maxSize:ut.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:ut.struct("PackageUpgradeError",{upgradeError:dr}),WrittenObjectsTooLarge:ut.struct("WrittenObjectsTooLarge",{currentSize:ut.u64(),maxSize:ut.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:ut.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:ut.vector(An)}),AddressDeniedForCoin:ut.struct("AddressDeniedForCoin",{address:An,coinType:ut.string()}),CoinTypeGlobalPause:ut.struct("CoinTypeGlobalPause",{coinType:ut.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),mr=ut.enum("ExecutionStatus",{Success:null,Failed:ut.struct("ExecutionFailed",{error:gr,command:ut.option(ut.u64())})}),yr=ut.struct("GasCostSummary",{computationCost:ut.u64(),storageCost:ut.u64(),storageRebate:ut.u64(),nonRefundableStorageFee:ut.u64()}),br=ut.struct("TransactionEffectsV1",{status:mr,executedEpoch:ut.u64(),gasUsed:yr,modifiedAtVersions:ut.vector(ut.tuple([An,ut.u64()])),sharedObjects:ut.vector(jn),transactionDigest:Cn,created:ut.vector(ut.tuple([jn,Nn])),mutated:ut.vector(ut.tuple([jn,Nn])),unwrapped:ut.vector(ut.tuple([jn,Nn])),deleted:ut.vector(jn),unwrappedThenDeleted:ut.vector(jn),wrapped:ut.vector(jn),gasObject:ut.tuple([jn,Nn]),eventsDigest:ut.option(Cn),dependencies:ut.vector(Cn)}),wr=ut.tuple([ut.u64(),Cn]),vr=ut.enum("ObjectIn",{NotExist:null,Exist:ut.tuple([wr,Nn])}),Er=ut.enum("ObjectOut",{NotExist:null,ObjectWrite:ut.tuple([Cn,Nn]),PackageWrite:wr}),kr=ut.enum("IDOperation",{None:null,Created:null,Deleted:null}),Sr=ut.struct("EffectsObjectChange",{inputState:vr,outputState:Er,idOperation:kr}),Or=ut.enum("UnchangedSharedKind",{ReadOnlyRoot:wr,MutateDeleted:ut.u64(),ReadDeleted:ut.u64(),Cancelled:ut.u64(),PerEpochConfig:null}),xr=ut.struct("TransactionEffectsV2",{status:mr,executedEpoch:ut.u64(),gasUsed:yr,transactionDigest:Cn,gasObjectIndex:ut.option(ut.u32()),eventsDigest:ut.option(Cn),dependencies:ut.vector(Cn),lamportVersion:ut.u64(),changedObjects:ut.vector(ut.tuple([An,Sr])),unchangedSharedObjects:ut.vector(ut.tuple([An,Or])),auxDataDigest:ut.option(Cn)}),Tr=ut.enum("TransactionEffects",{V1:br,V2:xr});function Ir(e){switch(e){case"u8":return ut.u8();case"u16":return ut.u16();case"u32":return ut.u32();case"u64":return ut.u64();case"u128":return ut.u128();case"u256":return ut.u256();case"bool":return ut.bool();case"string":return ut.string();case"id":case"address":return An}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[e,n]=t.slice(1);return"vector"===e?ut.vector(Ir(n)):ut.option(Ir(n))}throw new Error(`Invalid Pure type name: ${e}`)}const _r={...ut,U8:ut.u8(),U16:ut.u16(),U32:ut.u32(),U64:ut.u64(),U128:ut.u128(),U256:ut.u256(),ULEB128:ut.uleb128(),Bool:ut.bool(),String:ut.string(),Address:An,AppId:Xn,Argument:Un,CallArg:Rn,Command:Fn,CompressedSignature:tr,GasData:Wn,Intent:Qn,IntentMessage:er,IntentScope:Jn,IntentVersion:Yn,MultiSig:ir,MultiSigPkMap:rr,MultiSigPublicKey:sr,ObjectArg:Bn,ObjectDigest:Cn,Owner:Nn,PasskeyAuthenticator:ur,ProgrammableMoveCall:Dn,ProgrammableTransaction:Vn,PublicKey:nr,SenderSignedData:cr,SenderSignedTransaction:or,SharedObjectRef:Pn,StructTag:Zn,SuiObjectRef:jn,TransactionData:Hn,TransactionDataV1:Gn,TransactionEffects:Tr,TransactionExpiration:qn,TransactionKind:Kn,TypeTag:Mn},Ar=$t({digest:Dt(),objectId:Dt(),version:Vt([zt(Rt(),Ot()),Dt(),At()])}),Cr=on({ImmOrOwned:Ar,Shared:$t({objectId:un,initialSharedVersion:ln,mutable:Ct()}),Receiving:Ar}),jr=on({Object:Cr,Pure:_t(zt(Rt(),Ot()))}),Pr=Vt([$t({kind:Pt("Input"),index:zt(Rt(),Ot()),value:Kt(),type:Mt(Pt("object"))}),$t({kind:Pt("Input"),index:zt(Rt(),Ot()),value:Kt(),type:Pt("pure")})]),Br=Vt([$t({Epoch:zt(Rt(),Ot())}),$t({None:Bt(Pt(!0))})]),Nr=zt(Vt([Rt(),Dt(),At()]),St(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),Rr=Vt([$t({bool:Bt(Pt(!0))}),$t({u8:Bt(Pt(!0))}),$t({u64:Bt(Pt(!0))}),$t({u128:Bt(Pt(!0))}),$t({address:Bt(Pt(!0))}),$t({signer:Bt(Pt(!0))}),$t({vector:jt(()=>Rr)}),$t({struct:jt(()=>$r)}),$t({u16:Bt(Pt(!0))}),$t({u32:Bt(Pt(!0))}),$t({u256:Bt(Pt(!0))})]),$r=$t({address:Dt(),module:Dt(),name:Dt(),typeParams:_t(Rr)}),Mr=$t({budget:Mt(Nr),price:Mt(Nr),payment:Mt(_t(Ar)),owner:Mt(Dt())}),Ur=Vt([...[Pr,$t({kind:Pt("GasCoin")}),$t({kind:Pt("Result"),index:zt(Rt(),Ot())}),$t({kind:Pt("NestedResult"),index:zt(Rt(),Ot()),resultIndex:zt(Rt(),Ot())})]]),Dr=$t({kind:Pt("MoveCall"),target:zt(Dt(),St(e=>3===e.split("::").length)),typeArguments:_t(Dt()),arguments:_t(Ur)}),Fr=$t({kind:Pt("TransferObjects"),objects:_t(Ur),address:Ur}),Lr=$t({kind:Pt("SplitCoins"),coin:Ur,amounts:_t(Ur)}),Vr=$t({kind:Pt("MergeCoins"),destination:Ur,sources:_t(Ur)}),Kr=$t({kind:Pt("MakeMoveVec"),type:Vt([$t({Some:Rr}),$t({None:Bt(Pt(!0))})]),objects:_t(Ur)}),qr=Vt([...[Dr,Fr,Lr,Vr,$t({kind:Pt("Publish"),modules:_t(_t(zt(Rt(),Ot()))),dependencies:_t(Dt())}),$t({kind:Pt("Upgrade"),modules:_t(_t(zt(Rt(),Ot()))),dependencies:_t(Dt()),packageId:Dt(),ticket:Ur}),Kr]]);function zr(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(Ie(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:_n.parseFromStr(e.MakeMoveVec.type)},objects:e.MakeMoveVec.elements.map(e=>Zr(e,t))};if(e.MergeCoins)return{kind:"MergeCoins",destination:Zr(e.MergeCoins.destination,t),sources:e.MergeCoins.sources.map(e=>Zr(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=>Zr(e,t))};if(e.Publish)return{kind:"Publish",modules:e.Publish.modules.map(e=>Array.from(Ie(e))),dependencies:e.Publish.dependencies};if(e.SplitCoins)return{kind:"SplitCoins",coin:Zr(e.SplitCoins.coin,t),amounts:e.SplitCoins.amounts.map(e=>Zr(e,t))};if(e.TransferObjects)return{kind:"TransferObjects",objects:e.TransferObjects.objects.map(e=>Zr(e,t)),address:Zr(e.TransferObjects.address,t)};if(e.Upgrade)return{kind:"Upgrade",modules:e.Upgrade.modules.map(e=>Array.from(Ie(e))),dependencies:e.Upgrade.dependencies,packageId:e.Upgrade.package,ticket:Zr(e.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(e)}`)})}}function Zr(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 Wr(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 Gr(e){return Vt(Object.entries(e).map(([e,t])=>$t({[e]:t})))}$t({version:Pt(1),sender:Mt(Dt()),expiration:Nt(Br),gasConfig:Mr,inputs:_t(Pr),transactions:_t(qr)});const Hr=Gr({GasCoin:Pt(!0),Input:zt(Rt(),Ot()),Result:zt(Rt(),Ot()),NestedResult:Ft([zt(Rt(),Ot()),zt(Rt(),Ot())])}),Jr=$t({budget:Bt(ln),price:Bt(ln),owner:Bt(cn),payment:Bt(_t(hn))}),Yr=$t({package:un,module:Dt(),function:Dt(),typeArguments:_t(Dt()),arguments:_t(Hr)}),Xr=$t({name:Dt(),inputs:Ut(Dt(),Vt([Hr,_t(Hr)])),data:Ut(Dt(),Kt())}),Qr=Gr({MoveCall:Yr,TransferObjects:$t({objects:_t(Hr),address:Hr}),SplitCoins:$t({coin:Hr,amounts:_t(Hr)}),MergeCoins:$t({destination:Hr,sources:_t(Hr)}),Publish:$t({modules:_t(dn),dependencies:_t(un)}),MakeMoveVec:$t({type:Bt(Dt()),elements:_t(Hr)}),Upgrade:$t({modules:_t(dn),dependencies:_t(un),package:un,ticket:Hr}),$Intent:Xr}),es=Gr({ImmOrOwnedObject:hn,SharedObject:$t({objectId:un,initialSharedVersion:ln,mutable:Ct()}),Receiving:hn}),ts=Gr({Object:es,Pure:$t({bytes:dn}),UnresolvedPure:$t({value:Kt()}),UnresolvedObject:$t({objectId:un,version:Mt(Bt(ln)),digest:Mt(Bt(Dt())),initialSharedVersion:Mt(Bt(ln)),mutable:Mt(Bt(Ct()))})}),ns=Gr({None:Pt(!0),Epoch:ln}),rs=$t({version:Pt(2),sender:Nt(cn),expiration:Nt(ns),gasData:Jr,inputs:_t(ts),commands:_t(Qr),digest:Mt(Bt(Dt()))});const ss={Pure:function(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?Ae(e):e.toBase64()}}},ObjectRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:t,version:n,objectId:sn(e)}}}),SharedObjectRef:({objectId:e,mutable:t,initialSharedVersion:n})=>({$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:t,initialSharedVersion:n,objectId:sn(e)}}}),ReceivingRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:t,version:n,objectId:sn(e)}}})};BigInt(1e9);const is=an("0x6"),as="0x2::sui::SUI";an("0x5"),an("0x8");const os="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function cs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function us(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ds(e,...t){if(!cs(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 ls(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");us(e.outputLen),us(e.blockLen)}function hs(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 ps(e,t){ds(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function fs(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function gs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ms(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ys(e,t){return e<<32-t|e>>>t}function bs(e,t){return e<<t|e>>>32-t>>>0}const ws=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function vs(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Es=ws?e=>e:e=>vs(e);const ks=ws?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=vs(e[t]);return e},Ss=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Os=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function xs(e){if(ds(e),Ss)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Os[e[n]];return t}const Ts=48,Is=57,_s=65,As=70,Cs=97,js=102;function Ps(e){return e>=Ts&&e<=Is?e-Ts:e>=_s&&e<=As?e-(_s-10):e>=Cs&&e<=js?e-(Cs-10):void 0}function Bs(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ss)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=Ps(e.charCodeAt(s)),i=Ps(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 Ns(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Rs(e){return"string"==typeof e&&(e=Ns(e)),ds(e),e}function $s(e){return"string"==typeof e&&(e=Ns(e)),ds(e),e}function Ms(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];ds(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 Us{}function Ds(e){const t=t=>e().update(Rs(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Fs(e){const t=(t,n)=>e(n).update(Rs(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}function Ls(e=32){if(os&&"function"==typeof os.getRandomValues)return os.getRandomValues(new Uint8Array(e));if(os&&"function"==typeof os.randomBytes)return Uint8Array.from(os.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Vs=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 Ks(e,t,n){return e&t^~e&n}function qs(e,t,n){return e&t^e&n^t&n}class zs extends Us{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=ms(this.buffer)}update(e){hs(this),ds(e=Rs(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=ms(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){hs(this),ps(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,gs(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=ms(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 Zs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ws=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Gs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Hs=BigInt(2**32-1),Js=BigInt(32);function Ys(e,t=!1){return t?{h:Number(e&Hs),l:Number(e>>Js&Hs)}:{h:0|Number(e>>Js&Hs),l:0|Number(e&Hs)}}const Xs=(e,t,n)=>e>>>n,Qs=(e,t,n)=>e<<32-n|t>>>n,ei=(e,t,n)=>e>>>n|t<<32-n,ti=(e,t,n)=>e<<32-n|t>>>n,ni=(e,t,n)=>e<<64-n|t>>>n-32,ri=(e,t,n)=>e>>>n-32|t<<64-n,si=(e,t)=>t;function ii(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const ai=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),oi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,ci=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ui=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,di=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),li=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,hi=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pi=new Uint32Array(32);function fi(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=pi[2*e],u=pi[2*e+1],d=pi[2*t],l=pi[2*t+1],h=pi[2*n],p=pi[2*n+1],f=pi[2*r],g=pi[2*r+1],m=ai(c,d,a);var y;u=oi(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:si(0,f),Dl:(y=g,y)}),({h:p,l:h}=ii(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:ei(l,d,24),Bl:ti(l,d,24)}),pi[2*e]=c,pi[2*e+1]=u,pi[2*t]=d,pi[2*t+1]=l,pi[2*n]=h,pi[2*n+1]=p,pi[2*r]=f,pi[2*r+1]=g}function gi(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=pi[2*e],u=pi[2*e+1],d=pi[2*t],l=pi[2*t+1],h=pi[2*n],p=pi[2*n+1],f=pi[2*r],g=pi[2*r+1],m=ai(c,d,a);u=oi(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:ei(g,f,16),Dl:ti(g,f,16)}),({h:p,l:h}=ii(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:ni(l,d,63),Bl:ri(l,d,63)}),pi[2*e]=c,pi[2*e+1]=u,pi[2*t]=d,pi[2*t+1]=l,pi[2*n]=h,pi[2*n+1]=p,pi[2*r]=f,pi[2*r+1]=g}class mi extends Us{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,us(e),us(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=fs(this.buffer)}update(e){hs(this),ds(e=Rs(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&&(ks(r),this.compress(r,0,!1),ks(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));ks(e);for(let n=0;o+t<s;n+=r.length,o+=t)this.length+=t,this.compress(e,n,!1);ks(e);continue}n.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c}return this}digestInto(e){hs(this),ps(e,this);const{pos:t,buffer32:n}=this;this.finished=!0,gs(this.buffer.subarray(t)),ks(n),this.compress(n,0,!0),ks(n);const r=fs(e);this.get().forEach((e,t)=>r[t]=Es(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 yi extends mi{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|hi[0],this.v0h=0|hi[1],this.v1l=0|hi[2],this.v1h=0|hi[3],this.v2l=0|hi[4],this.v2h=0|hi[5],this.v3l=0|hi[6],this.v3h=0|hi[7],this.v4l=0|hi[8],this.v4h=0|hi[9],this.v5l=0|hi[10],this.v5h=0|hi[11],this.v6l=0|hi[12],this.v6h=0|hi[13],this.v7l=0|hi[14],this.v7h=0|hi[15],function(e,t={},n,r,s){if(us(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=Rs(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==s){s=Rs(s);const e=fs(s);this.v4l^=Es(e[0]),this.v4h^=Es(e[1]),this.v5l^=Es(e[2]),this.v5h^=Es(e[3])}if(void 0!==r){r=Rs(r);const e=fs(r);this.v6l^=Es(e[0]),this.v6h^=Es(e[1]),this.v7l^=Es(e[2]),this.v7h^=Es(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)=>pi[t]=e),pi.set(hi,16);let{h:r,l:s}=Ys(BigInt(this.length));pi[24]=hi[8]^s,pi[25]=hi[9]^r,n&&(pi[28]=~pi[28],pi[29]=~pi[29]);let i=0;const a=Vs;for(let n=0;n<12;n++)fi(0,4,8,12,e,t+2*a[i++]),gi(0,4,8,12,e,t+2*a[i++]),fi(1,5,9,13,e,t+2*a[i++]),gi(1,5,9,13,e,t+2*a[i++]),fi(2,6,10,14,e,t+2*a[i++]),gi(2,6,10,14,e,t+2*a[i++]),fi(3,7,11,15,e,t+2*a[i++]),gi(3,7,11,15,e,t+2*a[i++]),fi(0,5,10,15,e,t+2*a[i++]),gi(0,5,10,15,e,t+2*a[i++]),fi(1,6,11,12,e,t+2*a[i++]),gi(1,6,11,12,e,t+2*a[i++]),fi(2,7,8,13,e,t+2*a[i++]),gi(2,7,8,13,e,t+2*a[i++]),fi(3,4,9,14,e,t+2*a[i++]),gi(3,4,9,14,e,t+2*a[i++]);this.v0l^=pi[0]^pi[16],this.v0h^=pi[1]^pi[17],this.v1l^=pi[2]^pi[18],this.v1h^=pi[3]^pi[19],this.v2l^=pi[4]^pi[20],this.v2h^=pi[5]^pi[21],this.v3l^=pi[6]^pi[22],this.v3h^=pi[7]^pi[23],this.v4l^=pi[8]^pi[24],this.v4h^=pi[9]^pi[25],this.v5l^=pi[10]^pi[26],this.v5h^=pi[11]^pi[27],this.v6l^=pi[12]^pi[28],this.v6h^=pi[13]^pi[29],this.v7l^=pi[14]^pi[30],this.v7h^=pi[15]^pi[31],gs(pi)}destroy(){this.destroyed=!0,gs(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const bi=Fs(e=>new yi(e));function wi(e,t,n){const r=_r.Address.serialize(e).toBytes(),s=_r.TypeTag.serialize(t).toBytes(),i=_r.u64().serialize(n.length).toBytes(),a=bi.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(r),a.update(i),a.update(n),a.update(s),`0x${je(a.digest().slice(0,32))}`}function vi(e){if("string"==typeof e)switch(e){case"address":return _r.Address;case"bool":return _r.Bool;case"u8":return _r.U8;case"u16":return _r.U16;case"u32":return _r.U32;case"u64":return _r.U64;case"u128":return _r.U128;case"u256":return _r.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if("u8"===e.vector)return _r.byteVector().transform({input:e=>"string"==typeof e?(new TextEncoder).encode(e):e,output:e=>e});const t=vi(e.vector);return t?_r.vector(t):null}if("datatype"in e){const t=sn(e.datatype.package);if(t===sn("0x1")){if("ascii"===e.datatype.module&&"String"===e.datatype.type)return _r.String;if("string"===e.datatype.module&&"String"===e.datatype.type)return _r.String;if("option"===e.datatype.module&&"Option"===e.datatype.type){const t=vi(e.datatype.typeParameters[0]);return t?_r.vector(t):null}}if(t===sn("0x2")&&"object"===e.datatype.module&&"ID"===e.datatype.type)return _r.Address}return null}function Ei(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:Ei(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(Ei)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const ki=5e10;function Si(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:Ei(e.Reference)}:"object"==typeof e&&"MutableReference"in e?{ref:"&mut",body:Ei(e.MutableReference)}:{ref:null,body:Ei(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&&sn(t.package)===sn("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=vi(e.body);if(o)return s.type="pure",void(n[n.indexOf(i)]=ss.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=>an(e.UnresolvedObject.objectId)))],s=r.length?Pe(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=sn(n.UnresolvedObject.objectId),i=u.get(s);n.UnresolvedObject.initialSharedVersion??i?.initialSharedVersion?r=ss.SharedObjectRef({objectId:s,initialSharedVersion:n.UnresolvedObject.initialSharedVersion||i?.initialSharedVersion,mutable:n.UnresolvedObject.mutable||Oi(e,t)}):xi(e,t)&&(r=ss.ReceivingRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})),e.inputs[e.inputs.indexOf(n)]=r??ss.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(ki),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:as})).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=>qt(hn,e))}}(t,e)),await r()}}function Oi(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 xi(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 Ti(e,t){return!!e.inputs.some(e=>e.UnresolvedObject||e.UnresolvedPure)||!(t.onlyTransactionKind||e.gasConfig.price&&e.gasConfig.budget&&e.gasConfig.payment)}async function Ii(e,t,n){if(function(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(t=>{Ai(t,_r.U64,e)});break;case"TransferObjects":Ai(t.TransferObjects.address,_r.Address,e)}}(e),!Ti(e,t))return await _i(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()??Si(r))(e,t,async()=>{await _i(e),await n()})}function _i(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 Ai(e,t,n){if("Input"!==e.$kind)return;const r=n.inputs[e.Input];"UnresolvedPure"===r.$kind&&(n.inputs[e.Input]=ss.Pure(t.serialize(r.UnresolvedPure.value)))}function Ci(e){function t(t,n){if("string"==typeof t)return e(Ir(t).serialize(n));if(t instanceof Uint8Array||tt(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(_r.U8.serialize(t)),t.u16=t=>e(_r.U16.serialize(t)),t.u32=t=>e(_r.U32.serialize(t)),t.u64=t=>e(_r.U64.serialize(t)),t.u128=t=>e(_r.U128.serialize(t)),t.u256=t=>e(_r.U256.serialize(t)),t.bool=t=>e(_r.Bool.serialize(t)),t.string=t=>e(_r.String.serialize(t)),t.address=t=>e(_r.Address.serialize(t)),t.id=t.address,t.vector=(t,n)=>e(_r.vector(Ir(t)).serialize(n)),t.option=(t,n)=>e(_r.option(Ir(t)).serialize(n)),t}function ji(e){return"string"==typeof e?sn(e):e.Object?e.Object.ImmOrOwnedObject?sn(e.Object.ImmOrOwnedObject.objectId):e.Object.Receiving?sn(e.Object.Receiving.objectId):sn(e.Object.SharedObject.objectId):e.UnresolvedObject?sn(e.UnresolvedObject.objectId):void 0}function Pi(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 Bi(e){return sn(e).replace("0x","")}class Ni{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=_r.TransactionKind.parse(e).ProgrammableTransaction;if(!t)throw new Error("Unable to deserialize from bytes.");return Ni.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=_r.TransactionData.parse(e),n=t?.V1,r=n.kind.ProgrammableTransaction;if(!n||!r)throw new Error("Unable to deserialize from bytes.");return Ni.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 Ni(qt(On,e)):new Ni(qt(On,function(e){return qt(On,{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(It(jr,e.value)){const t=qt(jr,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:Ae(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?_n.tagToString(e.type.Some):null,elements:e.objects.map(e=>Wr(e))}};case"MergeCoins":return{MergeCoins:{destination:Wr(e.destination),sources:e.sources.map(e=>Wr(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=>Wr(e))}}}case"Publish":return{Publish:{modules:e.modules.map(e=>Ae(Uint8Array.from(e))),dependencies:e.dependencies}};case"SplitCoins":return{SplitCoins:{coin:Wr(e.coin),amounts:e.amounts.map(e=>Wr(e))}};case"TransferObjects":return{TransferObjects:{objects:e.objects.map(e=>Wr(e)),address:Wr(e.address)}};case"Upgrade":return{Upgrade:{modules:e.modules.map(e=>Ae(Uint8Array.from(e))),dependencies:e.dependencies,package:e.packageId,ticket:Wr(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),bi(r,{dkLen:32})}("TransactionData",e);return xe(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 _r.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:Bi(o),expiration:a||{None:!0},gasData:{payment:c.payment,owner:Bi(this.gasData.owner??o),price:BigInt(c.price),budget:BigInt(c.budget)},kind:{ProgrammableTransaction:{inputs:r,commands:s}}};return _r.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 qt(pn,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=ji(r);let i=-1;if(void 0!==s&&(i=this.inputs.findIndex(e=>ji(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]);Pi(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 Ni.getDigestFromBytes(e)}snapshot(){return qt(On,this)}shallowClone(){return new Ni({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(sn(e.objectId)!==sn(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(sn(e.objectId)!==sn(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 Ri,$i,Mi,Ui,Di,Fi,Li,Vi,Ki,qi,zi=e=>{throw TypeError(e)},Zi=(e,t,n)=>t.has(e)||zi("Cannot "+n),Wi=(e,t,n)=>(Zi(e,t,"read from private field"),n?n.call(e):t.get(e)),Gi=(e,t,n)=>t.has(e)?zi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Hi=(e,t,n,r)=>(Zi(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Ji=(e,t,n)=>(Zi(e,t,"access private method"),n);const Yi={"Mvr-Source":`@mysten/sui@${m}`};class Xi{constructor({cache:e,url:t,pageSize:n=50,overrides:r}){Gi(this,Di),Gi(this,Ri),Gi(this,$i),Gi(this,Mi),Gi(this,Ui),Hi(this,Ri,e),Hi(this,$i,t),Hi(this,Mi,n),Hi(this,Ui,{packages:r?.packages,types:r?.types}),function(e){if(e?.packages)for(const[t,n]of Object.entries(e.packages)){if(!Jt(t))throw new Error(`Invalid package name: ${t}`);if(!en(sn(n)))throw new Error(`Invalid package ID: ${n}`)}if(e?.types)for(const[t,n]of Object.entries(e.types)){if(nn(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(!en(nn(n).address))throw new Error(`Invalid type: ${n}`)}}(Wi(this,Ui))}async resolvePackage({package:e}){if(!ta(e))return{package:e};return{package:await Wi(this,Di,Fi).load(e)}}async resolveType({type:e}){if(!ta(e))return{type:e};const t=[...Qi(e)],n=await Wi(this,Di,Li).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:ea(e,r)}}async resolve({types:e=[],packages:t=[]}){const n=new Set;for(const t of e??[])Qi(t,n);const r=[...n],[s,i]=await Promise.all([r.length>0?Wi(this,Di,Li).loadMany(r):[],t.length>0?Wi(this,Di,Fi).loadMany(t):[]]),a={...Wi(this,Ui)?.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=ea(t,a);o[t]={type:e}}const c={};for(const[e,n]of(t??[]).entries()){const t=Wi(this,Ui)?.packages?.[n]??i[e];if(t instanceof Error)throw t;c[n]={package:t}}return{types:o,packages:c}}}function Qi(e,t=new Set){if("string"==typeof e&&!ta(e))return t;const n=na(e)?e:nn(e);ta(n.address)&&t.add(`${n.address}::${n.module}::${n.name}`);for(const e of n.typeParams)Qi(e,t);return t}function ea(e,t){const n=na(e)?e:nn(e),r=`${n.address}::${n.module}::${n.name}`,s=t[r];return rn({...n,address:s?s.split("::")[0]:n.address,typeParams:n.typeParams.map(e=>ea(e,t))})}function ta(e){return e.includes("/")||e.includes("@")||e.includes(".sui")}function na(e){return"object"==typeof e&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function ra(e){const t=new Set;for(const n of e)if(ta(n)){if(!Yt(n))throw new Error(`Invalid type with names: ${n}`);t.add(n)}return t}Ri=new WeakMap,$i=new WeakMap,Mi=new WeakMap,Ui=new WeakMap,Di=new WeakSet,Fi=function(){return Wi(this,Ri).readSync(["#mvrPackageDataLoader",Wi(this,$i)??""],()=>{const e=new Be(async e=>{if(!Wi(this,$i))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Ji(this,Di,Vi).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve package: ${e}`))}),t=Wi(this,Ui)?.packages;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Li=function(){return Wi(this,Ri).readSync(["#mvrTypeDataLoader",Wi(this,$i)??""],()=>{const e=new Be(async e=>{if(!Wi(this,$i))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Ji(this,Di,Ki).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve type: ${e}`))}),t=Wi(this,Ui)?.types;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Vi=async function(e){if(0===e.length)return{};const t=Pe(e,Wi(this,Mi)),n={};return await Promise.all(t.map(async e=>{const t=await Ji(this,Di,qi).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},Ki=async function(e){if(0===e.length)return{};const t=Pe(e,Wi(this,Mi)),n={};return await Promise.all(t.map(async e=>{const t=await Ji(this,Di,qi).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},qi=async function(e,t){if(!Wi(this,$i))throw new Error("MVR Api URL is not set for the current client");const n=await fetch(`${Wi(this,$i)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...Yi},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 sa=new WeakMap,ia=e=>{let t;if(e){const n=e.overrides??{packages:{},types:{}};sa.has(n)||sa.set(n,new yt),t=new Xi({cache:sa.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&&ra([r.MakeMoveVec.type]).forEach(e=>{n.add(e)});break;case"MoveCall":const e=r.MoveCall,s=e.package.split("::")[0];if(ta(s)){if(!Jt(s))throw new Error(`Invalid package name: ${s}`);t.add(s)}ra(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(!ta(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(ta(s)&&!t.packages[s])throw new Error(`No address found for package: ${s}`);ta(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(ta(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 aa,oa,ca,ua,da,la,ha,pa,fa,ga,ma,ya,ba,wa,va,Ea,ka,Sa,Oa,xa=e=>{throw TypeError(e)},Ta=(e,t,n)=>t.has(e)||xa("Cannot "+n),Ia=(e,t,n)=>(Ta(e,t,"read from private field"),n?n.call(e):t.get(e)),_a=(e,t,n)=>t.has(e)?xa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Aa=(e,t,n,r)=>(Ta(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Ca=(e,t,n)=>(Ta(e,t,"access private method"),n);function ja(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 Pa=Symbol.for("@mysten/transaction");function Ba(e){return!!e&&"object"==typeof e&&!0===e[Pa]}const Na={buildPlugins:new Map,serializationPlugins:new Map},Ra=Symbol.for("@mysten/transaction/registry");function $a(){try{const e=globalThis;return e[Ra]||(e[Ra]=Na),e[Ra]}catch{return Na}}const Ma=class e{constructor(){_a(this,ga),_a(this,aa),_a(this,oa),_a(this,ca,new Map),_a(this,ua,[]),_a(this,da,[]),_a(this,la,new Set),_a(this,ha,new Set),_a(this,pa,new Map),_a(this,fa),this.object=function(e){function t(t){return e(t)}return t.system=e=>{const n=e?.mutable;return t(void 0!==n?ss.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},t.clock=()=>t(ss.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&&It(pn,e))return e;const t=ji(e),n=Ia(this,fa).inputs.find(e=>t===ji(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:Ia(this,fa).inputs.indexOf(n),type:"object"}:Ca(this,ga,ba).call(this,"object","string"==typeof e?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:sn(e)}}:e)});const e=$a();Aa(this,fa,new Ni),Aa(this,oa,[...e.buildPlugins.values()]),Aa(this,aa,[...e.serializationPlugins.values()])}static fromKind(t){const n=new e;return Aa(n,fa,Ni.fromKindBytes("string"==typeof t?Ie(t):t)),Aa(n,ua,Ia(n,fa).inputs.slice()),Aa(n,da,Ia(n,fa).commands.slice()),Aa(n,la,new Set(Ia(n,da).map((e,t)=>t))),n}static from(t){const n=new e;return Ba(t)?Aa(n,fa,Ni.restore(t.getData())):"string"==typeof t&&t.startsWith("{")?Aa(n,fa,Ni.restore(JSON.parse(t))):Aa(n,fa,Ni.fromBytes("string"==typeof t?Ie(t):t)),Aa(n,ua,Ia(n,fa).inputs.slice()),Aa(n,da,Ia(n,fa).commands.slice()),Aa(n,la,new Set(Ia(n,da).map((e,t)=>t))),n}static registerGlobalSerializationPlugin(e,t){$a().serializationPlugins.set(e,t??e)}static unregisterGlobalSerializationPlugin(e){$a().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,t){$a().buildPlugins.set(e,t??e)}static unregisterGlobalBuildPlugin(e){$a().buildPlugins.delete(e)}addSerializationPlugin(e){Ia(this,aa).push(e)}addBuildPlugin(e){Ia(this,oa).push(e)}addIntentResolver(e,t){if(Ia(this,ca).has(e)&&Ia(this,ca).get(e)!==t)throw new Error(`Intent resolver for ${e} already exists`);Ia(this,ca).set(e,t)}setSender(e){Ia(this,fa).sender=e}setSenderIfNotSet(e){Ia(this,fa).sender||(Ia(this,fa).sender=e)}setExpiration(e){Ia(this,fa).expiration=e?qt(Sn,e):null}setGasPrice(e){Ia(this,fa).gasConfig.price=String(e)}setGasBudget(e){Ia(this,fa).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){null==Ia(this,fa).gasData.budget&&(Ia(this,fa).gasConfig.budget=String(e))}setGasOwner(e){Ia(this,fa).gasConfig.owner=e}setGasPayment(e){Ia(this,fa).gasConfig.payment=e.map(e=>qt(hn,e))}get blockData(){return zr(Ia(this,fa).snapshot())}getData(){return Ia(this,fa).snapshot()}get[Pa](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:Ci(e=>tt(e)?Ca(this,ga,ba).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):Ca(this,ga,ba).call(this,"pure",It(kn,e)?qt(kn,e):e instanceof Uint8Array?ss.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(ss.ObjectRef(...e))}receivingRef(...e){return this.object(ss.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(ss.SharedObjectRef(...e))}add(e){if("function"==typeof e){if(Ia(this,pa).has(e))return Ia(this,pa).get(e);const t=Ca(this,ga,ma).call(this),n=e(t);if(!n||"object"!=typeof n||!("then"in n))return Aa(this,la,Ia(t,la)),Ia(this,pa).set(e,n),n;const r=Ca(this,ga,ya).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Ia(this,fa).commands.length,result:null}}});Ia(this,ha).add(Promise.resolve(n).then(e=>{r.$Intent.data.result=e}));const s=ja(()=>r.$Intent.data.resultIndex);return Ia(this,pa).set(e,s),s}return Ca(this,ga,ya).call(this,e),ja(Ia(this,fa).commands.length-1)}splitCoins(e,t){const n=xn.SplitCoins("string"==typeof e?this.object(e):Ca(this,ga,va).call(this,e),t.map(e=>"number"==typeof e||"bigint"==typeof e||"string"==typeof e?this.pure.u64(e):Ca(this,ga,wa).call(this,e)));return Ca(this,ga,ya).call(this,n),ja(Ia(this,fa).commands.length-1,t.length)}mergeCoins(e,t){return this.add(xn.MergeCoins(this.object(e),t.map(e=>this.object(e))))}publish({modules:e,dependencies:t}){return this.add(xn.Publish({modules:e,dependencies:t}))}upgrade({modules:e,dependencies:t,package:n,ticket:r}){return this.add(xn.Upgrade({modules:e,dependencies:t,package:n,ticket:this.object(r)}))}moveCall({arguments:e,...t}){return this.add(xn.MoveCall({...t,arguments:e?.map(e=>Ca(this,ga,wa).call(this,e))}))}transferObjects(e,t){return this.add(xn.TransferObjects(e.map(e=>this.object(e)),"string"==typeof t?this.pure.address(t):Ca(this,ga,wa).call(this,t)))}makeMoveVec({type:e,elements:t}){return this.add(xn.MakeMoveVec({type:e,elements:t.map(e=>this.object(e))}))}serialize(){return JSON.stringify(zr(Ia(this,fa).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const t=this.isFullyResolved();return JSON.stringify(qt(rs,t?{...Ia(this,fa).snapshot(),digest:Ia(this,fa).getDigest()}:Ia(this,fa).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!!Ia(this,fa).sender&&(!(Ia(this,ha).size>0)&&(!Ia(this,fa).commands.some(e=>e.$Intent)&&!Ti(Ia(this,fa),{})))}async build(e={}){return await this.prepareForSerialization(e),await Ca(this,ga,Ea).call(this,e),Ia(this,fa).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await Ca(this,ga,Ea).call(this,e),Ia(this,fa).getDigest()}async prepareForSerialization(e){await Ca(this,ga,Sa).call(this),Ca(this,ga,Oa).call(this);const t=new Set;for(const e of Ia(this,fa).commands)e.$Intent&&t.add(e.$Intent.name);const n=[...Ia(this,aa)];for(const r of t)if(!e.supportedIntents?.includes(r)){if(!Ia(this,ca).has(r))throw new Error(`Missing intent resolver for ${r}`);n.push(Ia(this,ca).get(r))}n.push(ia()),await Ca(this,ga,ka).call(this,n,e)}};aa=new WeakMap,oa=new WeakMap,ca=new WeakMap,ua=new WeakMap,da=new WeakMap,la=new WeakMap,ha=new WeakMap,pa=new WeakMap,fa=new WeakMap,ga=new WeakSet,ma=function(){const e=new Ma;return Aa(e,fa,Ia(this,fa)),Aa(e,aa,Ia(this,aa)),Aa(e,oa,Ia(this,oa)),Aa(e,ca,Ia(this,ca)),Aa(e,ha,Ia(this,ha)),Aa(e,la,new Set(Ia(this,la))),Aa(e,pa,Ia(this,pa)),Ia(this,ua).push(Ia(e,ua)),Ia(this,da).push(Ia(e,da)),e},ya=function(e){const t=Ia(this,fa).commands.length;return Ia(this,da).push(e),Ia(this,la).add(t),Ia(this,fa).commands.push(e),Ia(this,fa).mapCommandArguments(t,e=>{if("Result"===e.$kind&&!Ia(this,la).has(e.Result))throw new Error(`Result { Result: ${e.Result} } is not available to use in the current transaction`);if("NestedResult"===e.$kind&&!Ia(this,la).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>=Ia(this,fa).inputs.length)throw new Error(`Input { Input: ${e.Input} } references an input that does not exist in the current transaction`);return e}),e},ba=function(e,t){return Ia(this,ua).push(t),Ia(this,fa).addInput(e,t)},wa=function(e){return tt(e)?this.pure(e):Ca(this,ga,va).call(this,e)},va=function(e){if("function"==typeof e){const t=this.add(e);return"function"==typeof t?Ca(this,ga,va).call(this,t):qt(pn,t)}return qt(pn,e)},Ea=async function(e){if(!e.onlyTransactionKind&&!Ia(this,fa).sender)throw new Error("Missing transaction sender");await Ca(this,ga,ka).call(this,[...Ia(this,oa),Ii],e)},ka=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(Ia(this,fa),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{Aa(this,ua,Ia(this,fa).inputs.slice()),Aa(this,da,Ia(this,fa).commands.slice())}},Sa=async function(){for(;Ia(this,ha).size>0;){const e=Promise.all(Ia(this,ha));Ia(this,ha).clear(),Ia(this,ha).add(e),await e,Ia(this,ha).delete(e)}},Oa=function(){const e=Ia(this,fa).commands,t=Ia(this,fa).inputs,n=Ia(this,da).flat(1/0),r=Ia(this,ua).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}Ia(this,fa).commands=s,Ia(this,fa).inputs=r,Aa(this,da,s),Aa(this,ua,r),Aa(this,la,new Set(s.map((e,t)=>t))),Ia(this,fa).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 Ua=Ma;const Da={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class Fa extends bt{constructor(e){super(e),this.core=this,this.mvr=new Xi({cache:this.cache.scope("core.mvr"),url:e.mvr?.url??Da[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=_n.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=wi(e.parentId,t,e.name.bcs),{objects:[r]}=await this.getObjects({objectIds:[n],signal:e.signal});if(r instanceof Error)throw r;const s=nn(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]:rn(s.typeParams[0]),bcs:e.name.bcs},value:{type:"string"==typeof s.typeParams[1]?s.typeParams[1]:rn(s.typeParams[1]),bcs:i.slice(Qt+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 La extends Error{}class Va extends La{constructor(e,t){super(t),this.code=e}static fromResponse(e,t){switch(e.code){case"notExists":return new Va(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Va(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Va(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Va(e.code,`Display error: ${e.error}`);default:return new Va(e.code,"Unknown error while loading object"+(t?` ${t}`:""))}}}function Ka(e){return{...Ni.fromBytes(e).snapshot(),bcs:e}}function qa(e){const t=_r.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 za,Za=e=>{throw TypeError(e)},Wa=(e,t,n)=>t.has(e)||Za("Cannot "+n),Ga=(e,t,n)=>(Wa(e,t,"read from private field"),n?n.call(e):t.get(e));class Ha extends Fa{constructor({jsonRpcClient:e,mvr:t}){var n,r,s;super({network:e.network,base:e,mvr:t}),n=this,(r=za).has(n)?Za("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(n):r.set(n,s),((e,t,n,r)=>{Wa(e,t,"write to private field"),r?r.call(e,n):t.set(e,n)})(this,za,e)}async getObjects(e){const t=Pe(e.objectIds,50),n=[];for(const r of t){const t=await Ga(this,za).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(Va.fromResponse(s.error,r[e])):n.push(Ja(s.data))}return{objects:n}}async getOwnedObjects(e){const t=await Ga(this,za).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 Va.fromResponse(e.error);return Ja(e.data)}),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getCoins(e){const t=await Ga(this,za).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(to.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 Ga(this,za).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:t.coinType,balance:t.totalBalance}}}async getAllBalances(e){return{balances:(await Ga(this,za).getAllBalances({owner:e.address,signal:e.signal})).map(e=>({coinType:e.coinType,balance:e.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){return{transaction:Qa(await Ga(this,za).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:Qa(await Ga(this,za).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=Ua.from(e.transaction),n=await Ga(this,za).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:Ya(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:Ya(e.owner),outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Ya(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:Ya(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:Ya(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:Ka(e.transaction),balanceChanges:n.balanceChanges.map(e=>({coinType:e.coinType,address:Xa(e.owner),amount:e.amount}))}}}async getReferenceGasPrice(e){const t=await Ga(this,za).getReferenceGasPrice({signal:e?.signal});return{referenceGasPrice:String(t)}}async getDynamicFields(e){const t=await Ga(this,za).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:Ie(e.bcsName)}})),hasNextPage:t.hasNextPage,cursor:t.nextCursor}}async verifyZkLoginSignature(e){const t=await Ga(this,za).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 Ga(this,za).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return Si(Ga(this,za))}async getMoveFunction(e){const t=await Ga(this,za).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:sn(e.packageId),moduleName:e.moduleName,name:e.name,visibility:so(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=>no(e)),returns:t.return.map(e=>no(e))}}}}function Ja(e){return{id:e.objectId,version:e.version,digest:e.digest,type:e.type,content:Promise.resolve("moveObject"===e.bcs?.dataType?Ie(e.bcs.bcsBytes):new Uint8Array),owner:Ya(e.owner),previousTransaction:e.previousTransaction??null}}function Ya(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 Xa(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 Qa(e){const t=_r.SenderSignedData.parse(Ie(e.rawTransaction))[0],n={};e.objectChanges?.forEach(e=>{"published"!==e.type&&(n[e.objectId]=e.objectType)});const r=_r.TransactionData.serialize(t.intentMessage.value).toBytes(),s=Ni.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:qa(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(n),transaction:{...s,bcs:r},signatures:t.txSignatures,balanceChanges:e.balanceChanges?.map(e=>({coinType:e.coinType,address:Xa(e.owner),amount:e.amount}))??[]}}za=new WeakMap;const eo=_r.struct("Balance",{value:_r.u64()}),to=_r.struct("Coin",{id:_r.Address,balance:eo});function no(e){if("string"!=typeof e){if("Reference"in e)return{reference:"immutable",body:ro(e.Reference)};if("MutableReference"in e)return{reference:"mutable",body:ro(e.MutableReference)}}return{reference:null,body:ro(e)}}function ro(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:ro(e.Vector)};if("Struct"in e)return{$kind:"datatype",datatype:{typeName:`${sn(e.Struct.address)}::${e.Struct.module}::${e.Struct.name}`,typeParameters:e.Struct.typeArguments.map(e=>ro(e))}};if("TypeParameter"in e)return{$kind:"typeParameter",index:e.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}function so(e){switch(e){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const io=Symbol.for("@mysten/SuiClient");class ao extends bt{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new H({url:e.url}),this.core=new Ha({jsonRpcClient:this,mvr:e.mvr})}get[io](){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||!en(sn(t)))throw new Error("Invalid Sui address");return e&&ta(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||!en(sn(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||!en(sn(e)))throw new Error("Invalid Sui address");return t&&ta(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||!en(sn(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&&ta(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&&ta(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&&Jt(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&&Jt(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&&Jt(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&&Jt(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&&Jt(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||!en(sn(e.owner)))throw new Error("Invalid Sui address");const t=e.filter?{...e.filter}:void 0;return t&&"MoveModule"in t&&Jt(t.MoveModule.package)?t.MoveModule={module:t.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveModule.package})).package}:t&&"StructType"in t&&ta(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||!tn(an(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||!tn(an(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&&Jt(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(!Xt(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(!Xt(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:Ae(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||!en(sn(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||!tn(an(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&&ta(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Jt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Jt(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(Ba(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),t=Ae(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=Ae(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:Ae(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!tn(an(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 je(Te(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(!Zt.test(n))throw new Error(`Invalid SuiNS name ${e}`);const[t,s]=n.split("@");r=[...t?t.split("."):[],s]}else{if(!Wt.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 oo 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 co(e){}function uo(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=co,onError:n=co,onRetry:r=co,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 oo(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:n(new oo(`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 lo 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(po(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(po(this),t)}}function ho(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(ho).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${ho(e.cause)}`:e.message:`${e}`}function po(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var fo,go,mo,yo,bo,wo,vo,Eo,ko,So,Oo,xo,To,Io,_o,Ao,Co,jo,Po,Bo,No,Ro,$o,Mo,Uo,Do=e=>{throw TypeError(e)},Fo=(e,t,n)=>t.has(e)||Do("Cannot "+n),Lo=(e,t,n)=>(Fo(e,t,"read from private field"),n?n.call(e):t.get(e)),Vo=(e,t,n)=>t.has(e)?Do("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Ko=(e,t,n,r)=>(Fo(e,t,"write to private field"),t.set(e,n),n),qo=(e,t,n)=>(Fo(e,t,"access private method"),n);class zo extends EventTarget{constructor(e,t){var n,r;super(),Vo(this,Io),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Vo(this,fo),Vo(this,go),Vo(this,mo),Vo(this,yo),Vo(this,bo),Vo(this,wo),Vo(this,vo),Vo(this,Eo,null),Vo(this,ko),Vo(this,So),Vo(this,Oo,null),Vo(this,xo,null),Vo(this,To,null),Vo(this,Ao,async e=>{var t;Lo(this,So).reset();const{body:n,redirected:r,status:s,headers:i}=e;if(204===s)return qo(this,Io,No).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(Ko(this,mo,r?new URL(e.url):void 0),200!==s)return void qo(this,Io,No).call(this,`Non-200 status code (${s})`,s);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void qo(this,Io,No).call(this,'Invalid content type, expected "text/event-stream"',s);if(Lo(this,fo)===this.CLOSED)return;Ko(this,fo,this.OPEN);const a=new Event("open");if(null==(t=Lo(this,To))||t.call(this,a),this.dispatchEvent(a),"object"!=typeof n||!n||!("getReader"in n))return qo(this,Io,No).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&&Lo(this,So).feed(o.decode(t,{stream:!e})),e&&(u=!1,Lo(this,So).reset(),qo(this,Io,Ro).call(this))}while(u)}),Vo(this,Co,e=>{Ko(this,ko,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&qo(this,Io,Ro).call(this,ho(e))}),Vo(this,Po,e=>{"string"==typeof e.id&&Ko(this,Eo,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Lo(this,mo)?Lo(this,mo).origin:Lo(this,go).origin,lastEventId:e.id||""});Lo(this,xo)&&(!e.event||"message"===e.event)&&Lo(this,xo).call(this,t),this.dispatchEvent(t)}),Vo(this,Bo,e=>{Ko(this,wo,e)}),Vo(this,$o,()=>{Ko(this,vo,void 0),Lo(this,fo)===this.CONNECTING&&qo(this,Io,_o).call(this)});try{if(e instanceof URL)Ko(this,go,e);else{if("string"!=typeof e)throw new Error("Invalid URL");Ko(this,go,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")}Ko(this,So,uo({onEvent:Lo(this,Po),onRetry:Lo(this,Bo)})),Ko(this,fo,this.CONNECTING),Ko(this,wo,3e3),Ko(this,bo,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),Ko(this,yo,null!=(r=null==t?void 0:t.withCredentials)&&r),qo(this,Io,_o).call(this)}get readyState(){return Lo(this,fo)}get url(){return Lo(this,go).href}get withCredentials(){return Lo(this,yo)}get onerror(){return Lo(this,Oo)}set onerror(e){Ko(this,Oo,e)}get onmessage(){return Lo(this,xo)}set onmessage(e){Ko(this,xo,e)}get onopen(){return Lo(this,To)}set onopen(e){Ko(this,To,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(){Lo(this,vo)&&clearTimeout(Lo(this,vo)),Lo(this,fo)!==this.CLOSED&&(Lo(this,ko)&&Lo(this,ko).abort(),Ko(this,fo,this.CLOSED),Ko(this,ko,void 0))}}function Zo(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Wo(e){const t={};for(const n of Object.keys(e)){const r=Zo(n),s=e[n];t[r]=s}return t}fo=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 WeakMap,xo=new WeakMap,To=new WeakMap,Io=new WeakSet,_o=function(){Ko(this,fo,this.CONNECTING),Ko(this,ko,new AbortController),Lo(this,bo)(Lo(this,go),qo(this,Io,jo).call(this)).then(Lo(this,Ao)).catch(Lo(this,Co))},Ao=new WeakMap,Co=new WeakMap,jo=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Lo(this,Eo)?{"Last-Event-ID":Lo(this,Eo)}:void 0},cache:"no-store",signal:null==(e=Lo(this,ko))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Po=new WeakMap,Bo=new WeakMap,No=function(e,t){var n;Lo(this,fo)!==this.CLOSED&&Ko(this,fo,this.CLOSED);const r=new lo("error",{code:t,message:e});null==(n=Lo(this,Oo))||n.call(this,r),this.dispatchEvent(r)},Ro=function(e,t){var n;if(Lo(this,fo)===this.CLOSED)return;Ko(this,fo,this.CONNECTING);const r=new lo("error",{code:t,message:e});null==(n=Lo(this,Oo))||n.call(this,r),this.dispatchEvent(r),Ko(this,vo,setTimeout(Lo(this,$o),Lo(this,wo)))},$o=new WeakMap,zo.CONNECTING=0,zo.OPEN=1,zo.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}(Mo||(Mo={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Uo||(Uo={}));const Go=Mo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ho=e=>{switch(typeof e){case"undefined":return Go.undefined;case"string":return Go.string;case"number":return Number.isNaN(e)?Go.nan:Go.number;case"boolean":return Go.boolean;case"function":return Go.function;case"bigint":return Go.bigint;case"symbol":return Go.symbol;case"object":return Array.isArray(e)?Go.array:null===e?Go.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Go.promise:"undefined"!=typeof Map&&e instanceof Map?Go.map:"undefined"!=typeof Set&&e instanceof Set?Go.set:"undefined"!=typeof Date&&e instanceof Date?Go.date:Go.object;default:return Go.unknown}},Jo=Mo.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 Yo 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 Yo))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mo.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()}}Yo.create=e=>new Yo(e);var Xo=(e,t)=>{let n;switch(e.code){case Jo.invalid_type:n=e.received===Go.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Jo.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Mo.jsonStringifyReplacer)}`;break;case Jo.unrecognized_keys:n=`Unrecognized key(s) in object: ${Mo.joinValues(e.keys,", ")}`;break;case Jo.invalid_union:n="Invalid input";break;case Jo.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Mo.joinValues(e.options)}`;break;case Jo.invalid_enum_value:n=`Invalid enum value. Expected ${Mo.joinValues(e.options)}, received '${e.received}'`;break;case Jo.invalid_arguments:n="Invalid function arguments";break;case Jo.invalid_return_type:n="Invalid function return type";break;case Jo.invalid_date:n="Invalid date";break;case Jo.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}"`:Mo.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Jo.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 Jo.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 Jo.custom:n="Invalid input";break;case Jo.invalid_intersection_types:n="Intersection results could not be merged";break;case Jo.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Jo.not_finite:n="Number must be finite";break;default:n=t.defaultError,Mo.assertNever(e)}return{message:n}};let Qo=Xo;function ec(e,t){const n=Qo,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===Xo?void 0:Xo].filter(e=>!!e)});e.common.issues.push(r)}class tc{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 nc;"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 tc.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 nc;if("aborted"===s.status)return nc;"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 nc=Object.freeze({status:"aborted"}),rc=e=>({status:"dirty",value:e}),sc=e=>({status:"valid",value:e}),ic=e=>"aborted"===e.status,ac=e=>"dirty"===e.status,oc=e=>"valid"===e.status,cc=e=>"undefined"!=typeof Promise&&e instanceof Promise;var uc;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(uc||(uc={}));class dc{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 lc=(e,t)=>{if(oc(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 Yo(e.common.issues);return this._error=t,this._error}}};function hc(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 pc{get description(){return this._def.description}_getType(e){return Ho(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ho(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tc,ctx:{common:e.parent.common,data:e.data,parsedType:Ho(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(cc(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:Ho(e)},r=this._parseSync({data:e,path:n.path,parent:n});return lc(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ho(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return oc(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=>oc(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:Ho(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(cc(r)?r:Promise.resolve(r));return lc(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:Jo.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 hu({schema:this,typeName:Eu.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 pu.create(this,this._def)}nullable(){return fu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jc.create(this)}promise(){return lu.create(this,this._def)}or(e){return Qc.create([this,e],this._def)}and(e){return tu.create(this,e,this._def)}transform(e){return new hu({...hc(this._def),schema:this,typeName:Eu.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new gu({...hc(this._def),innerType:this,defaultValue:t,typeName:Eu.ZodDefault})}brand(){return new bu({typeName:Eu.ZodBranded,type:this,...hc(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mu({...hc(this._def),innerType:this,catchValue:t,typeName:Eu.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return wu.create(this,e)}readonly(){return vu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fc=/^c[^\s-]{8,}$/i,gc=/^[0-9a-z]+$/,mc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yc=/^[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,bc=/^[a-z0-9_-]{21}$/i,wc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vc=/^[-+]?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)?)??$/,Ec=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let kc;const Sc=/^(?:(?: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])$/,Oc=/^(?:(?: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])$/,xc=/^(([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]))$/,Tc=/^(([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])$/,Ic=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_c=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ac="((\\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])))",Cc=new RegExp(`^${Ac}$`);function jc(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 Pc(e){return new RegExp(`^${jc(e)}$`)}function Bc(e){let t=`${Ac}T${jc(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 Nc(e,t){return!("v4"!==t&&t||!Sc.test(e))||!("v6"!==t&&t||!xc.test(e))}function Rc(e,t){if(!wc.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 $c(e,t){return!("v4"!==t&&t||!Oc.test(e))||!("v6"!==t&&t||!Tc.test(e))}class Mc extends pc{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Go.string){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.string,received:t.parsedType}),nc}const t=new tc;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),ec(n,{code:Jo.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),ec(n,{code:Jo.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?ec(n,{code:Jo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):i&&ec(n,{code:Jo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)Ec.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"email",code:Jo.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)kc||(kc=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),kc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"emoji",code:Jo.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)yc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"uuid",code:Jo.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)bc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"nanoid",code:Jo.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)fc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"cuid",code:Jo.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)gc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"cuid2",code:Jo.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)mc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"ulid",code:Jo.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),ec(n,{validation:"url",code:Jo.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),ec(n,{validation:"regex",code:Jo.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),ec(n,{code:Jo.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),ec(n,{code:Jo.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),ec(n,{code:Jo.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){Bc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{code:Jo.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Cc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{code:Jo.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Pc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{code:Jo.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?vc.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"duration",code:Jo.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?Nc(e.data,r.version)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"ip",code:Jo.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Rc(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"jwt",code:Jo.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?$c(e.data,r.version)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"cidr",code:Jo.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Ic.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"base64",code:Jo.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?_c.test(e.data)||(n=this._getOrReturnCtx(e,n),ec(n,{validation:"base64url",code:Jo.invalid_string,message:r.message}),t.dirty()):Mo.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Jo.invalid_string,...uc.errToObj(n)})}_addCheck(e){return new Mc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...uc.errToObj(e)})}url(e){return this._addCheck({kind:"url",...uc.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...uc.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...uc.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...uc.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...uc.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...uc.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...uc.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...uc.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...uc.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...uc.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...uc.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...uc.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,...uc.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,...uc.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...uc.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...uc.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...uc.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...uc.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...uc.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...uc.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...uc.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...uc.errToObj(t)})}nonempty(e){return this.min(1,uc.errToObj(e))}trim(){return new Mc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Mc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Mc({...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 Uc(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}Mc.create=e=>new Mc({checks:[],typeName:Eu.ZodString,coerce:e?.coerce??!1,...hc(e)});class Dc extends pc{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)!==Go.number){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.number,received:t.parsedType}),nc}let t;const n=new tc;for(const r of this._def.checks)if("int"===r.kind)Mo.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ec(t,{code:Jo.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),ec(t,{code:Jo.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),ec(t,{code:Jo.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==Uc(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),ec(t,{code:Jo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ec(t,{code:Jo.not_finite,message:r.message}),n.dirty()):Mo.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,uc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,uc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,uc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,uc.toString(t))}setLimit(e,t,n,r){return new Dc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:uc.toString(r)}]})}_addCheck(e){return new Dc({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:uc.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:uc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:uc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:uc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:uc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:uc.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:uc.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:uc.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:uc.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&&Mo.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)}}Dc.create=e=>new Dc({checks:[],typeName:Eu.ZodNumber,coerce:e?.coerce||!1,...hc(e)});class Fc extends pc{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)!==Go.bigint)return this._getInvalidInput(e);let t;const n=new tc;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),ec(t,{code:Jo.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),ec(t,{code:Jo.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),ec(t,{code:Jo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Mo.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.bigint,received:t.parsedType}),nc}gte(e,t){return this.setLimit("min",e,!0,uc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,uc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,uc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,uc.toString(t))}setLimit(e,t,n,r){return new Fc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:uc.toString(r)}]})}_addCheck(e){return new Fc({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:uc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:uc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:uc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:uc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:uc.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}}Fc.create=e=>new Fc({checks:[],typeName:Eu.ZodBigInt,coerce:e?.coerce??!1,...hc(e)});class Lc extends pc{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Go.boolean){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.boolean,received:t.parsedType}),nc}return sc(e.data)}}Lc.create=e=>new Lc({typeName:Eu.ZodBoolean,coerce:e?.coerce||!1,...hc(e)});class Vc extends pc{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Go.date){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.date,received:t.parsedType}),nc}if(Number.isNaN(e.data.getTime())){return ec(this._getOrReturnCtx(e),{code:Jo.invalid_date}),nc}const t=new tc;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),ec(n,{code:Jo.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),ec(n,{code:Jo.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Mo.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Vc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:uc.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:uc.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}}Vc.create=e=>new Vc({checks:[],coerce:e?.coerce||!1,typeName:Eu.ZodDate,...hc(e)});class Kc extends pc{_parse(e){if(this._getType(e)!==Go.symbol){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.symbol,received:t.parsedType}),nc}return sc(e.data)}}Kc.create=e=>new Kc({typeName:Eu.ZodSymbol,...hc(e)});class qc extends pc{_parse(e){if(this._getType(e)!==Go.undefined){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.undefined,received:t.parsedType}),nc}return sc(e.data)}}qc.create=e=>new qc({typeName:Eu.ZodUndefined,...hc(e)});class zc extends pc{_parse(e){if(this._getType(e)!==Go.null){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.null,received:t.parsedType}),nc}return sc(e.data)}}zc.create=e=>new zc({typeName:Eu.ZodNull,...hc(e)});class Zc extends pc{constructor(){super(...arguments),this._any=!0}_parse(e){return sc(e.data)}}Zc.create=e=>new Zc({typeName:Eu.ZodAny,...hc(e)});class Wc extends pc{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sc(e.data)}}Wc.create=e=>new Wc({typeName:Eu.ZodUnknown,...hc(e)});class Gc extends pc{_parse(e){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.never,received:t.parsedType}),nc}}Gc.create=e=>new Gc({typeName:Eu.ZodNever,...hc(e)});class Hc extends pc{_parse(e){if(this._getType(e)!==Go.undefined){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.void,received:t.parsedType}),nc}return sc(e.data)}}Hc.create=e=>new Hc({typeName:Eu.ZodVoid,...hc(e)});class Jc extends pc{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==Go.array)return ec(t,{code:Jo.invalid_type,expected:Go.array,received:t.parsedType}),nc;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(ec(t,{code:e?Jo.too_big:Jo.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&&(ec(t,{code:Jo.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&&(ec(t,{code:Jo.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 dc(t,e,t.path,n)))).then(e=>tc.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new dc(t,e,t.path,n)));return tc.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new Jc({...this._def,minLength:{value:e,message:uc.toString(t)}})}max(e,t){return new Jc({...this._def,maxLength:{value:e,message:uc.toString(t)}})}length(e,t){return new Jc({...this._def,exactLength:{value:e,message:uc.toString(t)}})}nonempty(e){return this.min(1,e)}}function Yc(e){if(e instanceof Xc){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=pu.create(Yc(r))}return new Xc({...e._def,shape:()=>t})}return e instanceof Jc?new Jc({...e._def,type:Yc(e.element)}):e instanceof pu?pu.create(Yc(e.unwrap())):e instanceof fu?fu.create(Yc(e.unwrap())):e instanceof nu?nu.create(e.items.map(e=>Yc(e))):e}Jc.create=(e,t)=>new Jc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Eu.ZodArray,...hc(t)});class Xc extends pc{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=Mo.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Go.object){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.object,received:t.parsedType}),nc}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Gc&&"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 dc(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Gc){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&&(ec(n,{code:Jo.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 dc(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=>tc.mergeObjectSync(t,e)):tc.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return uc.errToObj,new Xc({...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:uc.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new Xc({...this._def,unknownKeys:"strip"})}passthrough(){return new Xc({...this._def,unknownKeys:"passthrough"})}extend(e){return new Xc({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Xc({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Eu.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Xc({...this._def,catchall:e})}pick(e){const t={};for(const n of Mo.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Xc({...this._def,shape:()=>t})}omit(e){const t={};for(const n of Mo.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Xc({...this._def,shape:()=>t})}deepPartial(){return Yc(this)}partial(e){const t={};for(const n of Mo.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new Xc({...this._def,shape:()=>t})}required(e){const t={};for(const n of Mo.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof pu;)e=e._def.innerType;t[n]=e}return new Xc({...this._def,shape:()=>t})}keyof(){return cu(Mo.objectKeys(this.shape))}}Xc.create=(e,t)=>new Xc({shape:()=>e,unknownKeys:"strip",catchall:Gc.create(),typeName:Eu.ZodObject,...hc(t)}),Xc.strictCreate=(e,t)=>new Xc({shape:()=>e,unknownKeys:"strict",catchall:Gc.create(),typeName:Eu.ZodObject,...hc(t)}),Xc.lazycreate=(e,t)=>new Xc({shape:e,unknownKeys:"strip",catchall:Gc.create(),typeName:Eu.ZodObject,...hc(t)});class Qc extends pc{_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 Yo(e.ctx.common.issues));return ec(t,{code:Jo.invalid_union,unionErrors:n}),nc});{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 Yo(e));return ec(t,{code:Jo.invalid_union,unionErrors:s}),nc}}get options(){return this._def.options}}function eu(e,t){const n=Ho(e),r=Ho(t);if(e===t)return{valid:!0,data:e};if(n===Go.object&&r===Go.object){const n=Mo.objectKeys(t),r=Mo.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=eu(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===Go.array&&r===Go.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=eu(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===Go.date&&r===Go.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Qc.create=(e,t)=>new Qc({options:e,typeName:Eu.ZodUnion,...hc(t)});class tu extends pc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ic(e)||ic(r))return nc;const s=eu(e.value,r.value);return s.valid?((ac(e)||ac(r))&&t.dirty(),{status:t.value,value:s.data}):(ec(n,{code:Jo.invalid_intersection_types}),nc)};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}))}}tu.create=(e,t,n)=>new tu({left:e,right:t,typeName:Eu.ZodIntersection,...hc(n)});class nu extends pc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Go.array)return ec(n,{code:Jo.invalid_type,expected:Go.array,received:n.parsedType}),nc;if(n.data.length<this._def.items.length)return ec(n,{code:Jo.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),nc;!this._def.rest&&n.data.length>this._def.items.length&&(ec(n,{code:Jo.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 dc(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>tc.mergeArray(t,e)):tc.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new nu({...this._def,rest:e})}}nu.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nu({items:e,typeName:Eu.ZodTuple,rest:null,...hc(t)})};class ru extends pc{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!==Go.object)return ec(n,{code:Jo.invalid_type,expected:Go.object,received:n.parsedType}),nc;const r=[],s=this._def.keyType,i=this._def.valueType;for(const e in n.data)r.push({key:s._parse(new dc(n,e,n.path,e)),value:i._parse(new dc(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?tc.mergeObjectAsync(t,r):tc.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new ru(t instanceof pc?{keyType:e,valueType:t,typeName:Eu.ZodRecord,...hc(n)}:{keyType:Mc.create(),valueType:e,typeName:Eu.ZodRecord,...hc(t)})}}class su extends pc{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!==Go.map)return ec(n,{code:Jo.invalid_type,expected:Go.map,received:n.parsedType}),nc;const r=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([e,t],i)=>({key:r._parse(new dc(n,e,n.path,[i,"key"])),value:s._parse(new dc(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 nc;"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 nc;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}su.create=(e,t,n)=>new su({valueType:t,keyType:e,typeName:Eu.ZodMap,...hc(n)});class iu extends pc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Go.set)return ec(n,{code:Jo.invalid_type,expected:Go.set,received:n.parsedType}),nc;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(ec(n,{code:Jo.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&&(ec(n,{code:Jo.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 nc;"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 dc(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new iu({...this._def,minSize:{value:e,message:uc.toString(t)}})}max(e,t){return new iu({...this._def,maxSize:{value:e,message:uc.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}iu.create=(e,t)=>new iu({valueType:e,minSize:null,maxSize:null,typeName:Eu.ZodSet,...hc(t)});class au extends pc{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})}}au.create=(e,t)=>new au({getter:e,typeName:Eu.ZodLazy,...hc(t)});class ou extends pc{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ec(t,{received:t.data,code:Jo.invalid_literal,expected:this._def.value}),nc}return{status:"valid",value:e.data}}get value(){return this._def.value}}function cu(e,t){return new uu({values:e,typeName:Eu.ZodEnum,...hc(t)})}ou.create=(e,t)=>new ou({value:e,typeName:Eu.ZodLiteral,...hc(t)});class uu extends pc{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return ec(t,{expected:Mo.joinValues(n),received:t.parsedType,code:Jo.invalid_type}),nc}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 ec(t,{received:t.data,code:Jo.invalid_enum_value,options:n}),nc}return sc(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 uu.create(e,{...this._def,...t})}exclude(e,t=this._def){return uu.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}uu.create=cu;class du extends pc{_parse(e){const t=Mo.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Go.string&&n.parsedType!==Go.number){const e=Mo.objectValues(t);return ec(n,{expected:Mo.joinValues(e),received:n.parsedType,code:Jo.invalid_type}),nc}if(this._cache||(this._cache=new Set(Mo.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Mo.objectValues(t);return ec(n,{received:n.data,code:Jo.invalid_enum_value,options:e}),nc}return sc(e.data)}get enum(){return this._def.values}}du.create=(e,t)=>new du({values:e,typeName:Eu.ZodNativeEnum,...hc(t)});class lu extends pc{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Go.promise&&!1===t.common.async)return ec(t,{code:Jo.invalid_type,expected:Go.promise,received:t.parsedType}),nc;const n=t.parsedType===Go.promise?t.data:Promise.resolve(t.data);return sc(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}lu.create=(e,t)=>new lu({type:e,typeName:Eu.ZodPromise,...hc(t)});class hu extends pc{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Eu.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=>{ec(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 nc;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?nc:"dirty"===r.status||"dirty"===t.value?rc(r.value):r});{if("aborted"===t.value)return nc;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?nc:"dirty"===r.status||"dirty"===t.value?rc(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?nc:("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?nc:("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(!oc(e))return nc;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=>oc(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):nc)}Mo.assertNever(r)}}hu.create=(e,t,n)=>new hu({schema:e,typeName:Eu.ZodEffects,effect:t,...hc(n)}),hu.createWithPreprocess=(e,t,n)=>new hu({schema:t,effect:{type:"preprocess",transform:e},typeName:Eu.ZodEffects,...hc(n)});class pu extends pc{_parse(e){return this._getType(e)===Go.undefined?sc(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pu.create=(e,t)=>new pu({innerType:e,typeName:Eu.ZodOptional,...hc(t)});class fu extends pc{_parse(e){return this._getType(e)===Go.null?sc(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fu.create=(e,t)=>new fu({innerType:e,typeName:Eu.ZodNullable,...hc(t)});class gu extends pc{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Go.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}gu.create=(e,t)=>new gu({innerType:e,typeName:Eu.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...hc(t)});class mu extends pc{_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 cc(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Yo(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Yo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}mu.create=(e,t)=>new mu({innerType:e,typeName:Eu.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...hc(t)});class yu extends pc{_parse(e){if(this._getType(e)!==Go.nan){const t=this._getOrReturnCtx(e);return ec(t,{code:Jo.invalid_type,expected:Go.nan,received:t.parsedType}),nc}return{status:"valid",value:e.data}}}yu.create=e=>new yu({typeName:Eu.ZodNaN,...hc(e)});class bu extends pc{_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 wu extends pc{_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?nc:"dirty"===e.status?(t.dirty(),rc(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?nc:"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 wu({in:e,out:t,typeName:Eu.ZodPipeline})}}class vu extends pc{_parse(e){const t=this._def.innerType._parse(e),n=e=>(oc(e)&&(e.value=Object.freeze(e.value)),e);return cc(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Eu;vu.create=(e,t)=>new vu({innerType:e,typeName:Eu.ZodReadonly,...hc(t)}),Xc.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"}(Eu||(Eu={}));const ku=Mc.create,Su=Dc.create;yu.create,Fc.create;const Ou=Lc.create;Vc.create,Kc.create,qc.create,zc.create,Zc.create,Wc.create,Gc.create;const xu=Hc.create,Tu=Jc.create,Iu=Xc.create;Xc.strictCreate,Qc.create,tu.create,nu.create;const _u=ru.create;su.create,iu.create,au.create,ou.create;const Au=uu.create;function Cu(e,t){let n={...e};for(let e of t)delete n[e];return n}du.create,lu.create,hu.create,pu.create,fu.create,hu.createWithPreprocess;var ju=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;function Pu(e){let t=e.url,n=e.params;return n&&(t=t.replace(ju,(e,t)=>t in n?`${n[t]}`:e)),t}function Bu(e,t,n){return e.find(e=>e.method===t&&e.path===n)}var Nu=class extends Error{constructor(e,t,n,r){super(e),this.config=t,this.data=n,this.cause=r}},Ru={name:"form-data",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new Nu("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 $u={name:"form-url",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new Nu("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 Mu(e,t){return{request:async(n,r)=>({...r,headers:{...r.headers,[e]:t}})}}function Uu(e){return[!0,"response","all"].includes(e)}function Du(e){return[!0,"request","all"].includes(e)}var Fu=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 Lu(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 Vu=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||{}}Lu(this.api),this.options={validate:!0,transform:!0,sendDefaults:!1,...r},this.options.axiosInstance?this.axiosInstance=this.options.axiosInstance:this.axiosInstance=l.default.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:Du(e)?async(e,r)=>{let s=Bu(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=Du(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 Nu(`Zodios: Invalid ${i} parameter '${t}'`,r,a,e.error);u&&c[i](t,e.data)}}return a}:void 0,response:Uu(e)?async(e,n,r)=>{var s,i,a,o;let c=Bu(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 Nu(`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);Uu(t)&&(r.data=e.data)}return r}:void 0}}(this.options))}initPlugins(){this.endpointPlugins.set("any-any",new Fu("any","any")),this.api.forEach(e=>{let t=new Fu(e.method,e.path);switch(e.requestFormat){case"binary":t.use(Mu("Content-Type","application/octet-stream"));break;case"form-data":t.use(Ru);break;case"form-url":t.use($u);break;case"text":t.use(Mu("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({...Cu(t,["params","queries"]),url:Pu(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 Ku=Au(["crypto","fx","equity","metal","rates","crypto_redemption_rate","commodities","crypto_index","crypto_nav"]),qu=Ku.nullish(),zu=ku(),Zu=Iu({attributes:_u(ku()),id:zu}).passthrough(),Wu=ku(),Gu=Au(["hex","base64"]),Hu=Iu({data:Tu(ku()),encoding:Gu}).passthrough(),Ju=Iu({conf:ku(),expo:Su().int(),price:ku(),publish_time:Su().int()}).passthrough(),Yu=Iu({prev_publish_time:Su().int().nullable(),proof_available_time:Su().int().nullable(),slot:Su().int().gte(0).nullable()}).partial().passthrough(),Xu=Iu({ema_price:Ju,id:zu,metadata:Yu,price:Ju}).passthrough(),Qu=Iu({binary:Hu,parsed:Tu(Xu).nullish()}).passthrough(),ed=Iu({cap:Su().int().gte(0),publisher:ku()}).passthrough(),td=Iu({publisher_stake_caps:Tu(ed)}).passthrough(),nd=Iu({binary:Hu,parsed:Tu(td).nullish()}).passthrough(),rd=Iu({down_slots_ratio:ku(),end_timestamp:Su().int(),id:zu,start_timestamp:Su().int(),twap:Ju}).passthrough(),sd=Iu({binary:Hu,parsed:Tu(rd).nullish()}).passthrough(),id={AssetType:Ku,asset_type:qu,RpcPriceIdentifier:zu,PriceFeedMetadata:Zu,PriceIdInput:Wu,EncodingType:Gu,BinaryUpdate:Hu,RpcPrice:Ju,RpcPriceFeedMetadataV2:Yu,ParsedPriceUpdate:Xu,PriceUpdate:Qu,ParsedPublisherStakeCap:ed,ParsedPublisherStakeCapsUpdate:td,LatestPublisherStakeCapsUpdateDataResponse:nd,ParsedPriceFeedTwap:rd,TwapsResponse:sd};var ad;new Vu((Lu(ad=[{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:ku().nullish()},{name:"asset_type",type:"Query",schema:qu}],response:Tu(Zu)},{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:Su().int()},{name:"ids[]",type:"Query",schema:Tu(Wu)},{name:"encoding",type:"Query",schema:Au(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Ou().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Ou().optional()}],response:Qu,errors:[{status:404,description:"Price ids not found",schema:xu()}]},{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:Tu(Wu)},{name:"encoding",type:"Query",schema:Au(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Ou().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Ou().optional()}],response:Qu,errors:[{status:404,description:"Price ids not found",schema:xu()}]},{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:Tu(Wu)},{name:"encoding",type:"Query",schema:Au(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Ou().optional()},{name:"allow_unordered",type:"Query",schema:Ou().optional()},{name:"benchmarks_only",type:"Query",schema:Ou().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Ou().optional()}],response:Qu,errors:[{status:404,description:"Price ids not found",schema:xu()}]},{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:Au(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Ou().optional()}],response:nd},{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:Su().int().gte(0)},{name:"ids[]",type:"Query",schema:Tu(Wu)},{name:"encoding",type:"Query",schema:Au(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Ou().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Ou().optional()}],response:sd,errors:[{status:404,description:"Price ids not found",schema:xu()}]}]),ad));class od{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=Wo(t);this.appendUrlSearchParams(n,e)}return await this.httpRequest(n.toString(),id.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(),id.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=Wo(t);this.appendUrlSearchParams(r,e)}return this.httpRequest(r.toString(),id.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=Wo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),id.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=Wo(t);this.appendUrlSearchParams(n,e)}return new zo(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=Wo(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),id.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 cd extends od{async getPriceFeedsUpdateData(e){return(await this.getLatestPriceUpdates(e,{encoding:"base64",parsed:!1})).binary.data.map(e=>n.Buffer.from(e,"base64"))}}const ud=16384;class dd{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(_r.vector(_r.U8).serialize([...s],{maxSize:ud}).toBytes()),t.object(is)]});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(_r.vector(_r.U8).serialize([...t[0]],{maxSize:ud}).toBytes()),s[0],e.object(is)]});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(is)]}),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(_r.vector(_r.U8).serialize([...t[0]],{maxSize:ud}).toBytes()),s[0],e.object(is)]})}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:r}=await this.getPriceTableInfo(),s=await this.provider.getDynamicFieldObject({parentId:e,name:{type:`${r}::price_identifier::PriceIdentifier`,value:{bytes:[...n.Buffer.from(t,"hex")]}}});if(!s.data?.content)return;if("moveObject"!==s.data.content.dataType)throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(t,s.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 ld={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"},hd='{"onboardingUrl":"dipcoin.io"}',pd={USDC:6,SUI:9,DEFAULT:18},fd={mainnet:{wormholeStateId:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pythStateId:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",priceServiceUrl:"https://hermes.pyth.network/"},testnet:{wormholeStateId:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",pythStateId:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",priceServiceUrl:"https://hermes-beta.pyth.network"}};class gd{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((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}`);r&&c.push("-d",r);const u=s.spawn("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())}}var md,yd;exports.OrderSide=void 0,(md=exports.OrderSide||(exports.OrderSide={})).BUY="BUY",md.SELL="SELL",exports.OrderType=void 0,(yd=exports.OrderType||(exports.OrderType={})).MARKET="MARKET",yd.LIMIT="LIMIT";const bd=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]),wd=new Uint32Array(64);class vd extends zs{constructor(e=32){super(64,e,8,!1),this.A=0|Zs[0],this.B=0|Zs[1],this.C=0|Zs[2],this.D=0|Zs[3],this.E=0|Zs[4],this.F=0|Zs[5],this.G=0|Zs[6],this.H=0|Zs[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)wd[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=wd[e-15],n=wd[e-2],r=ys(t,7)^ys(t,18)^t>>>3,s=ys(n,17)^ys(n,19)^n>>>10;wd[e]=s+wd[e-7]+r+wd[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+(ys(a,6)^ys(a,11)^ys(a,25))+Ks(a,o,c)+bd[e]+wd[e]|0,d=(ys(n,2)^ys(n,13)^ys(n,22))+qs(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(){gs(wd)}destroy(){this.set(0,0,0,0,0,0,0,0),gs(this.buffer)}}const Ed=(()=>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}=Ys(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))))(),kd=(()=>Ed[0])(),Sd=(()=>Ed[1])(),Od=new Uint32Array(80),xd=new Uint32Array(80);class Td extends zs{constructor(e=64){super(128,e,16,!1),this.Ah=0|Gs[0],this.Al=0|Gs[1],this.Bh=0|Gs[2],this.Bl=0|Gs[3],this.Ch=0|Gs[4],this.Cl=0|Gs[5],this.Dh=0|Gs[6],this.Dl=0|Gs[7],this.Eh=0|Gs[8],this.El=0|Gs[9],this.Fh=0|Gs[10],this.Fl=0|Gs[11],this.Gh=0|Gs[12],this.Gl=0|Gs[13],this.Hh=0|Gs[14],this.Hl=0|Gs[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)Od[n]=e.getUint32(t),xd[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Od[e-15],n=0|xd[e-15],r=ei(t,n,1)^ei(t,n,8)^Xs(t,0,7),s=ti(t,n,1)^ti(t,n,8)^Qs(t,n,7),i=0|Od[e-2],a=0|xd[e-2],o=ei(i,a,19)^ni(i,a,61)^Xs(i,0,6),c=ti(i,a,19)^ri(i,a,61)^Qs(i,a,6),u=ci(s,c,xd[e-7],xd[e-16]),d=ui(u,r,o,Od[e-7],Od[e-16]);Od[e]=0|d,xd[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=ei(d,l,14)^ei(d,l,18)^ni(d,l,41),b=ti(d,l,14)^ti(d,l,18)^ri(d,l,41),w=d&h^~d&f,v=di(y,b,l&p^~l&g,Sd[e],xd[e]),E=li(v,m,t,w,kd[e],Od[e]),k=0|v,S=ei(n,r,28)^ni(n,r,34)^ni(n,r,39),O=ti(n,r,28)^ri(n,r,34)^ri(n,r,39),x=n&s^n&a^s&a,T=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}=ii(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 I=ai(k,O,T);n=oi(I,E,S,x),r=0|I}({h:n,l:r}=ii(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=ii(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=ii(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=ii(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l:l}=ii(0|this.Eh,0|this.El,0|d,0|l)),({h:h,l:p}=ii(0|this.Fh,0|this.Fl,0|h,0|p)),({h:f,l:g}=ii(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=ii(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(){gs(Od,xd)}destroy(){gs(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Id extends Td{constructor(){super(48),this.Ah=0|Ws[0],this.Al=0|Ws[1],this.Bh=0|Ws[2],this.Bl=0|Ws[3],this.Ch=0|Ws[4],this.Cl=0|Ws[5],this.Dh=0|Ws[6],this.Dl=0|Ws[7],this.Eh=0|Ws[8],this.El=0|Ws[9],this.Fh=0|Ws[10],this.Fl=0|Ws[11],this.Gh=0|Ws[12],this.Gl=0|Ws[13],this.Hh=0|Ws[14],this.Hl=0|Ws[15]}}const _d=Ds(()=>new vd),Ad=Ds(()=>new Td),Cd=Ds(()=>new Id),jd=BigInt(0),Pd=BigInt(1);function Bd(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Nd(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Rd(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?jd:BigInt("0x"+e)}function $d(e){return Rd(xs(e))}function Md(e){return ds(e),Rd(xs(Uint8Array.from(e).reverse()))}function Ud(e,t){return Bs(e.toString(16).padStart(2*t,"0"))}function Dd(e,t){return Ud(e,t).reverse()}function Fd(e,t,n){let r;if("string"==typeof t)try{r=Bs(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!cs(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 Ld=e=>"bigint"==typeof e&&jd<=e;function Vd(e,t,n,r){if(!function(e,t,n){return Ld(e)&&Ld(t)&&Ld(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Kd(e){let t;for(t=0;e>jd;e>>=Pd,t+=1);return t}const qd=e=>(Pd<<BigInt(e))-Pd;function zd(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 Wd=BigInt(0),Gd=BigInt(1),Hd=BigInt(2),Jd=BigInt(3),Yd=BigInt(4),Xd=BigInt(5),Qd=BigInt(7),el=BigInt(8),tl=BigInt(9),nl=BigInt(16);function rl(e,t){const n=e%t;return n>=Wd?n:t+n}function sl(e,t,n){let r=e;for(;t-- >Wd;)r*=r,r%=n;return r}function il(e,t){if(e===Wd)throw new Error("invert: expected non-zero number");if(t<=Wd)throw new Error("invert: expected positive modulus, got "+t);let n=rl(e,t),r=t,s=Wd,i=Gd;for(;n!==Wd;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==Gd)throw new Error("invert: does not exist");return rl(s,t)}function al(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ol(e,t){const n=(e.ORDER+Gd)/Yd,r=e.pow(t,n);return al(e,r,t),r}function cl(e,t){const n=(e.ORDER-Xd)/el,r=e.mul(t,Hd),s=e.pow(r,n),i=e.mul(t,s),a=e.mul(e.mul(i,Hd),s),o=e.mul(i,e.sub(a,e.ONE));return al(e,o,t),o}function ul(e){if(e<Jd)throw new Error("sqrt is not defined for small field");let t=e-Gd,n=0;for(;t%Hd===Wd;)t/=Hd,n++;let r=Hd;const s=gl(e);for(;1===fl(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ol;let i=s.pow(r,t);const a=(t+Gd)/Hd;return function(e,r){if(e.is0(r))return r;if(1!==fl(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=Gd<<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 dl(e){return e%Yd===Jd?ol:e%el===Xd?cl:e%nl===tl?function(e){const t=gl(e),n=ul(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),a=(e+Qd)/nl;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 al(e,p,t),p}}(e):ul(e)}const ll=(e,t)=>(rl(e,t)&Gd)===Gd,hl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function pl(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 fl(e,t){const n=(e.ORDER-Gd)/Hd,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 gl(e,t,n=!1,r={}){if(e<=Wd)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&&us(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:qd(c),ZERO:Wd,ONE:Gd,allowedLengths:a,create:t=>rl(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Wd<=t&&t<e},is0:e=>e===Wd,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Gd)===Gd,neg:t=>rl(-t,e),eql:(e,t)=>e===t,sqr:t=>rl(t*t,e),add:(t,n)=>rl(t+n,e),sub:(t,n)=>rl(t-n,e),mul:(t,n)=>rl(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Wd)throw new Error("invalid exponent, negatives unsupported");if(n===Wd)return e.ONE;if(n===Gd)return t;let r=e.ONE,s=t;for(;n>Wd;)n&Gd&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Gd;return r}(l,e,t),div:(t,n)=>rl(t*il(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>il(t,e),sqrt:i||(t=>(d||(d=dl(e)),d(l,t))),toBytes:e=>n?Dd(e,u):Ud(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?Md(t):$d(t);if(o&&(s=rl(s,e)),!r&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>pl(l,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(l)}function ml(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 yl(e){const t=ml(e);return t+Math.ceil(t/2)}const bl=BigInt(0),wl=BigInt(1);function vl(e,t){const n=t.negate();return e?n:t}function El(e,t){const n=pl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function kl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Sl(e,t){kl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:qd(e),maxNumber:n,shiftBy:BigInt(e)}}function Ol(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+=wl);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 xl=new WeakMap,Tl=new WeakMap;function Il(e){return Tl.get(e)||1}function _l(e){if(e!==bl)throw new Error("invalid wNAF")}class Al{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>bl;)t&wl&&(n=n.add(r)),r=r.double(),t>>=wl;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Sl(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=Sl(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=Ol(n,e,i);n=a,c?s=s.add(vl(d,t[l])):r=r.add(vl(u,t[o]))}return _l(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Sl(e,this.bits);for(let e=0;e<s.windows&&n!==bl;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=Ol(n,e,s);if(n=i,!o){const e=t[a];r=r.add(c?e.negate():e)}}return _l(n),r}getPrecomputes(e,t,n){let r=xl.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),xl.set(t,r))),r}cached(e,t,n){const r=Il(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=Il(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){kl(t,this.bits),Tl.set(e,t),xl.delete(e)}hasCache(e){return 1!==Il(e)}}function Cl(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=Kd(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=qd(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 jl(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=hl.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});zd(e,t)}(t),t}return gl(e)}function Pl(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>bl))throw new Error(`CURVE.${e} must be positive bigint`)}const r=jl(t.p,n.Fp),s=jl(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 Bl=BigInt(0),Nl=BigInt(1),Rl=BigInt(2),$l=BigInt(8);class Ml{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 xs(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 Ul(e,t,n){if("function"!=typeof t)throw new Error('"hash" function param is required');zd(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||Ls,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Bd("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(Md(e))}function p(e){const{head:n,prefix:r,scalar:a}=function(e){const n=i.BYTES;e=Fd("private key",e,n);const r=Fd("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=Ms(...n);return h(t(d(s,Fd("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(Nl+n,Nl-n):i.div(n-Nl,n+Nl);return i.toBytes(s)},toMontgomeryPriv(e){ds(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=Fd("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);Vd("signature.s",f,Bl,o);const m=i.BYTES;return Fd("result",Ms(h,Dd(f,m)),2*m)},verify:function(t,n,a,o=m){const{context:c,zip215:u}=o,d=i.BYTES;t=Fd("signature",t,2*d),n=Fd("message",n),a=Fd("publicKey",a,d),void 0!==u&&Bd("zip215",u),r&&(n=r(n));const l=Md(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 Dl(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:gl(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}=Pl("edwards",e,t),{h:s,n:i}=e;zd(t,{},{uvRatio:"function"});const a=Rl<<BigInt(8*r.BYTES)-Nl,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:Bl}}});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 Vd("coordinate "+e,t,n?Nl:Bl,a),t}function d(e){if(!(e instanceof p))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?$l:n.inv(i));const c=o(r*t),u=o(s*t),d=n.mul(i,t);if(a)return{x:Bl,y:Nl};if(d!==Nl)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),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 El(p,e)}static msm(e,t){return Cl(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,Nl,o(t*n))}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(Rl),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(Rl*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,E=b+y,k=o(m-n*g),S=o(w*v),O=o(E*k),x=o(w*k),T=o(v*E);return new p(S,O,T,x)}subtract(e){return this.add(e.negate())}multiply(e){const t=e;Vd("scalar",t,Nl,i);const{p:n,f:r}=f.cached(this,t,e=>El(p,e));return El(p,[n,r])[0]}multiplyUnsafe(e,t=p.ZERO){const n=e;return Vd("scalar",n,Bl,i),n===Bl?p.ZERO:this.is0()||n===Nl?this:f.unsafe(this,n,e=>El(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===Nl?this:this.multiplyUnsafe(s)}static fromBytes(e,t=!1){return ds(e),p.fromHex(e,t)}static fromHex(t,r=!1){const{d:s,a:i}=e,u=n.BYTES;t=Fd("pointHex",t,u),Bd("zip215",r);const d=t.slice(),l=t[u-1];d[u-1]=-129&l;const h=Md(d),f=r?a:n.ORDER;Vd("pointHex.y",h,Bl,f);const g=o(h*h),m=o(g-Nl),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&Nl)===Nl,E=!!(128&l);if(!r&&w===Bl&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=o(-w)),p.fromAffine({x:w,y:h})}toBytes(){const{x:e,y:t}=this.toAffine(),r=Dd(t,n.BYTES);return r[r.length-1]|=e&Nl?128:0,r}toRawBytes(){return this.toBytes()}toHex(){return xs(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}p.BASE=new p(e.Gx,e.Gy,Nl,o(e.Gx*e.Gy)),p.ZERO=new p(Bl,Nl,Nl,Bl),p.Fp=n,p.Fn=r;const f=new Al(p,8*r.BYTES);return p}(t,n);return function(e,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:e})}(e,Ul(i,r,s))}const Fl=BigInt(0),Ll=BigInt(1),Vl=BigInt(2);BigInt(3);const Kl=BigInt(5),ql=BigInt(8),zl={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ql,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 Wl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Gl(e,t){const n=zl.p,r=rl(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=zl.p,a=e*e%i*e%i,o=sl(a,Vl,i)*a%i,c=sl(o,Ll,i)*e%i,u=sl(c,Kl,i)*c%i,d=sl(u,t,i)*u%i,l=sl(d,n,i)*d%i,h=sl(l,r,i)*l%i,p=sl(h,s,i)*h%i,f=sl(p,s,i)*h%i,g=sl(f,t,i)*u%i;return{pow_p_5_8:sl(g,Vl,i)*e%i,b2:a}}(e*rl(r*r*t,n)).pow_p_5_8;let i=rl(e*r*s,n);const a=rl(t*i*i,n),o=i,c=rl(i*Wl,n),u=a===e,d=a===rl(-e,n),l=a===rl(-e*Wl,n);return u&&(i=o),(d||l)&&(i=c),ll(i,n)&&(i=rl(-i,n)),{isValid:u||d,value:i}}const Hl=(()=>gl(zl.p,{isLE:!0}))(),Jl=(()=>gl(zl.n,{isLE:!0}))(),Yl=(()=>({...zl,Fp:Hl,hash:Ad,adjustScalarBytes:Zl,uvRatio:Gl}))(),Xl=(()=>Dl(Yl))(),Ql=Wl,eh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),th=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),nh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),sh=e=>Gl(Ll,e),ih=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ah=e=>Xl.CURVE.Fp.create(Md(e)&ih);function oh(e){const{d:t}=Xl.CURVE,n=Xl.CURVE.Fp.ORDER,r=Xl.CURVE.Fp.create,s=r(Ql*e*e),i=r((s+Ll)*nh);let a=BigInt(-1);const o=r((a-t*s)*r(s+t));let{isValid:c,value:u}=Gl(i,o),d=r(u*e);ll(d,n)||(d=r(-d)),c||(u=d),c||(a=s);const l=r(a*(s-Ll)*rh-o),h=u*u,p=r((u+u)*o),f=r(l*eh),g=r(Ll-h),m=r(Ll+h);return new Xl.Point(r(p*m),r(g*f),r(f*m),r(p*g))}class ch extends Ml{constructor(e){super(e)}static fromAffine(e){return new ch(Xl.Point.fromAffine(e))}assertSame(e){if(!(e instanceof ch))throw new Error("RistrettoPoint expected")}init(e){return new ch(e)}static hashToCurve(e){return function(e){ds(e,64);const t=oh(ah(e.subarray(0,32))),n=oh(ah(e.subarray(32,64)));return new ch(t.add(n))}(Fd("ristrettoHash",e,64))}static fromBytes(e){ds(e,32);const{a:t,d:n}=Xl.CURVE,r=Hl.ORDER,s=Hl.create,i=ah(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}(Dd(i,32),e)||ll(i,r))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Ll+t*a),c=s(Ll-t*a),u=s(o*o),d=s(c*c),l=s(t*n*u-d),{isValid:h,value:p}=sh(s(l*d)),f=s(p*c),g=s(p*f*l);let m=s((i+i)*f);ll(m,r)&&(m=s(-m));const y=s(o*g),b=s(m*y);if(!h||ll(b,r)||y===Fl)throw new Error("invalid ristretto255 encoding 2");return new ch(new Xl.Point(m,y,Ll,b))}static fromHex(e){return ch.fromBytes(Fd("ristrettoHex",e,32))}static msm(e,t){return Cl(ch,Xl.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep;const s=Hl.ORDER,i=Hl.create,a=i(i(n+t)*i(n-t)),o=i(e*t),c=i(o*o),{value:u}=sh(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*r);let p;if(ll(r*h,s)){let n=i(t*Ql),r=i(e*Ql);e=n,t=r,p=i(d*th)}else p=l;ll(e*h,s)&&(t=i(-t));let f=i((n-t)*p);return ll(f,s)&&(f=i(-f)),Dd(f,32)}equals(e){this.assertSame(e);const{X:t,Y:n}=this.ep,{X:r,Y:s}=e.ep,i=Hl.create,a=i(t*s)===i(n*r),o=i(n*s)===i(t*r);return a||o}is0(){return this.equals(ch.ZERO)}}function uh(e,t){return _r.IntentMessage(_r.bytes(t.length)).serialize({intent:{scope:{[e]:!0},version:{V0:!0},appId:{Sui:!0}},value:t}).toBytes()}ch.BASE=(()=>new ch(Xl.Point.BASE))(),ch.ZERO=(()=>new ch(Xl.Point.ZERO))(),ch.Fp=Hl,ch.Fn=Jl;const dh={ED25519:0,Secp256k1:1,Secp256r1:2,MultiSig:3,ZkLogin:5,Passkey:6},lh={ED25519:32,Secp256k1:33,Secp256r1:33,Passkey:33},hh={0:"ED25519",1:"Secp256k1",2:"Secp256r1",3:"MultiSig",5:"ZkLogin",6:"Passkey"};class ph extends Us{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ls(e);const n=Rs(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),gs(s)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),ds(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 fh=(e,t,n)=>new ph(e,t).update(n).digest();fh.create=(e,t)=>new ph(e,t);const gh=(e,t)=>(e+(e>=0?t:-t)/Eh)/t;function mh(e){void 0!==e.lowS&&Bd("lowS",e.lowS),void 0!==e.prehash&&Bd("prehash",e.prehash)}class yh extends Error{constructor(e=""){super(e)}}const bh={Err:yh,_tlv:{encode:(e,t)=>{const{Err:n}=bh;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=Nd(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Nd(s.length/2|128):"";return Nd(e)+i+s+t},decode(e,t){const{Err:n}=bh;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}=bh;if(e<wh)throw new t("integer: negative integers are not allowed");let n=Nd(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}=bh;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 $d(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=bh,s=Fd("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}=bh,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},wh=BigInt(0),vh=BigInt(1),Eh=BigInt(2),kh=BigInt(3),Sh=BigInt(4);function Oh(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=Fd("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 xh(e,t={}){const{Fp:n,Fn:r}=Pl("weierstrass",e,t),{h:s,n:i}=e;zd(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(Bd("isCompressed",r),r){o();return Ms(Th(!n.isOdd(i)),a)}return Ms(Uint8Array.of(4),a,n.toBytes(i))},u=t.fromBytes||function(e){ds(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,kh),Sh),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=gh(a*e,n),c=gh(-s*e,n);let u=e-o*r-c*i,d=-o*s-c*a;const l=u<wh,h=d<wh;l&&(u=-u),h&&(d=-d);const p=qd(Math.ceil(Kd(n)/2))+vh;if(u<wh||u>=p||d<wh||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=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=vl(s,t),r=vl(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 El(v,e)}static fromBytes(e){return ds(e),v.fromHex(e)}static fromHex(e){const t=v.fromAffine(u(Fd("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(Oh(r,e))}static msm(e,t){return Cl(v,r,e,t)}_setWindowSize(e){this.precompute(e)}precompute(e=8,t=!0){return k.createCache(this,e),t||this.multiply(kh),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,kh),{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,kh);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 E=n.add(a,c);return w=n.mul(w,E),E=n.add(f,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(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(E,w),u=n.mul(b,u),u=n.sub(u,f),f=n.mul(b,m),l=n.mul(E,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=>k.cached(this,e,e=>El(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 El(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===wh||s.is0())return v.ZERO;if(e===vh)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>bl||r>bl;)n&wl&&(i=i.add(s)),r&wl&&(a=a.add(s)),s=s.double(),n>>=wl,r>>=wl;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===vh||(e?e(v,this):k.unsafe(this,i).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===vh?this:e?e(v,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Bd("isCompressed",e),this.assertValidity(),c(v,this,e)}toRawBytes(e=!0){return this.toBytes(e)}toHex(e=!0){return xs(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 Al(v,t.endo?Math.ceil(E/2):E);return v}function Th(e){return Uint8Array.of(e?2:3)}function Ih(e,t,n={}){ls(t),zd(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Ls,s=n.hmac||((e,...n)=>fh(t,e,Ms(...n))),{Fp:i,Fn:a}=e,{ORDER:o,BITS:c}=a,u=yl(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>>vh}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;ds(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){ds(e);const{r:t,s:n}=bh.toSig(e);return new p(t,n)}throw new Error("invalid format")}static fromHex(e,t){return this.fromBytes(Bs(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*Eh<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(Ms(Th(!(1&c)),d)),h=a.inv(u),p=v(Fd("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 Ms(a.toBytes(this.r),a.toBytes(this.s));if("der"===e)return Bs(bh.hexFromSig(this));throw new Error("invalid format")}toHex(e){return xs(this.toBytes(e))}assertValidity(){}static fromCompact(e){return p.fromBytes(Fd("sig",e),"compact")}static fromDER(e){return p.fromBytes(Fd("sig",e),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return xs(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return xs(this.toBytes("compact"))}}function f(e){try{return!!Oh(a,e)}catch(e){return!1}}function g(e=r(u)){return function(e,t,n=!1){const r=e.length,s=ml(t),i=yl(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=rl(n?Md(e):$d(e),t-Gd)+Gd;return n?Dd(a,s):Ud(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=>Oh(a,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};function y(t,n=!0){return e.BASE.multiply(Oh(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=Fd("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=$d(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=qd(c);function k(e){return Vd("num < 2^"+c,e,wh,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=Fd("msgHash",n),mh(i),c&&(n=Fd("prehashed msgHash",t(n)));const h=v(n),f=Oh(a,s),g=[k(f),k(h)];if(null!=u&&!1!==u){const e=!0===u?r(d.secret):u;g.push(Fd("extraEntropy",e))}const m=Ms(...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===wh)return;const c=a.create(r*a.create(y+i*f));if(c===wh)return;let u=(s.x===i?0:2)|Number(s.y&vh),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 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 Ms(...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=Fd("msgHash",r),s=Fd("publicKey",s),mh(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||cs(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 bh.Err))throw e}if(!l)try{l=p.fromCompact(o)}catch(e){return!1}}}else if("compact"===d||"der"===d){if("string"!=typeof o&&!cs(o))throw new Error('"der" / "compact" format expects Uint8Array signature');l=p.fromBytes(Fd("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=Oh(a,t);return e.fromHex(n).multiply(s).toBytes(r)},utils:m,Point:e,Signature:p,info:{type:"weierstrass",lengths:d,publicKeyHasPrefix:!0}})}function _h(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:gl(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 Ah(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=_h(e);return function(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}(e,Ih(xh(t,n),r,s))}function Ch(e,t){const n=t=>Ah({...e,hash:t});return{...n(t),create:n}}const jh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Ph={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Bh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Nh=gl(jh.p),Rh=gl(Ph.p),$h=gl(Bh.p),Mh=Ch({...jh,Fp:Nh,lowS:!1},_d);Ch({...Ph,Fp:Rh,lowS:!1},Cd),Ch({...Bh,Fp:$h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Ad);const Uh=Mh,Dh=_d;function Fh(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 Lh{equals(e){return Fh(this.toRawBytes(),e.toRawBytes())}toBase64(){return Ae(this.toRawBytes())}toString(){throw new Error("`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.")}toSuiPublicKey(){return Ae(this.toSuiBytes())}verifyWithIntent(e,t,n){const r=uh(n,e),s=bi(r,{dkLen:32});return this.verify(s,t)}verifyPersonalMessage(e,t){return this.verifyWithIntent(_r.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 sn(xs(bi(this.toSuiBytes(),{dkLen:32})).slice(0,64))}}function Vh(e){const t=Ie(e),n=hh[t[0]];switch(n){case"ED25519":case"Secp256k1":case"Secp256r1":const r=lh[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 Kh(e){const t="string"==typeof e?Ie(e):e;if(t[0]!==dh.Passkey)throw new Error("Invalid signature scheme");const n=ur.parse(t.slice(1));return{signatureScheme:"Passkey",serializedSignature:Ae(t),signature:t,authenticatorData:n.authenticatorData,clientDataJson:n.clientDataJson,userSignature:new Uint8Array(n.userSignature),publicKey:new Uint8Array(n.userSignature.slice(65))}}function qh(e,t){if(!Boolean(e))throw new Error(t)}(class extends Lh{constructor(e){if(super(),"string"==typeof e?this.data=Ie(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 dh.Passkey}async verify(e,t){const n=Kh(t),r=JSON.parse(n.clientDataJson);if("webauthn.get"!==r.type)return!1;if(!Fh(e,Ie(r.challenge.replace(/-/g,"+").replace(/_/g,"/"))))return!1;const s=n.userSignature.slice(65);if(!Fh(this.toRawBytes(),s))return!1;const i=new Uint8Array([...n.authenticatorData,...Dh(n.clientDataJson)]),a=n.userSignature.slice(1,65);return Uh.verify(a,Dh(i),s)}}).SIZE=33;const zh={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(zh));function Wh(e){const t=null==e?void 0:e.kind;return"string"==typeof t&&Zh.has(t)}var Gh,Hh;function Jh(e){return 9===e||32===e}!function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"}(Gh||(Gh={})),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"}(Hh||(Hh={}));function Yh(e){return Xh(e,[])}function Xh(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:Xh(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(Xh(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+": "+Xh(n,t));return"{ "+r.join(", ")+" }"}(e,n)}(e,t);default:return String(e)}}const Qh=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function ep(e){return tp[e.charCodeAt(0)]}const tp=["\\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"],np=Object.freeze({});function rp(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 sp(e){return function(e,t,n=zh){const r=new Map;for(const e of Object.values(Hh))r.set(e,rp(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;Wh(l)||qh(!1,`Invalid AST Node: ${Yh(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===np)break;if(!1===b){if(!e){h.pop();continue}}else if(void 0!==b&&(d.push([i,b]),!e)){if(!Wh(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,ip)}const ip={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>ap(e.definitions,"\n\n")},OperationDefinition:{leave(e){const t=dp(e.variableDefinitions)?cp("(\n",ap(e.variableDefinitions,"\n"),"\n)"):cp("(",ap(e.variableDefinitions,", "),")"),n=cp("",e.description,"\n")+ap([e.operation,ap([e.name,t]),ap(e.directives," ")]," ");return("query"===n?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r,description:s})=>cp("",s,"\n")+e+": "+t+cp(" = ",n)+cp(" ",ap(r," "))},SelectionSet:{leave:({selections:e})=>op(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:s}){const i=cp("",e,": ")+t;let a=i+cp("(",ap(n,", "),")");return a.length>80&&(a=i+cp("(\n",up(ap(n,"\n")),"\n)")),ap([a,ap(r," "),s]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+cp(" ",ap(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>ap(["...",cp("on ",e),ap(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:s,description:i})=>cp("",i,"\n")+`fragment ${e}${cp("(",ap(n,", "),")")} `+`on ${t} ${cp("",ap(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||Jh(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&&Jh(e.charCodeAt(0));return(d&&!h||i)&&(l+="\n"),l+=n,(d||u)&&(l+="\n"),'"""'+l+'"""'}(e):`"${e.replace(Qh,ep)}"`},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+ap(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+ap(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+cp("(",ap(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>cp("",e,"\n")+ap(["schema",ap(t," "),op(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>cp("",e,"\n")+ap(["scalar",t,ap(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>cp("",e,"\n")+ap(["type",t,cp("implements ",ap(n," & ")),ap(r," "),op(s)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:s})=>cp("",e,"\n")+t+(dp(n)?cp("(\n",up(ap(n,"\n")),"\n)"):cp("(",ap(n,", "),")"))+": "+r+cp(" ",ap(s," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:s})=>cp("",e,"\n")+ap([t+": "+n,cp("= ",r),ap(s," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>cp("",e,"\n")+ap(["interface",t,cp("implements ",ap(n," & ")),ap(r," "),op(s)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>cp("",e,"\n")+ap(["union",t,ap(n," "),cp("= ",ap(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>cp("",e,"\n")+ap(["enum",t,ap(n," "),op(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>cp("",e,"\n")+ap([t,ap(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>cp("",e,"\n")+ap(["input",t,ap(n," "),op(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:s})=>cp("",e,"\n")+"directive @"+t+(dp(n)?cp("(\n",up(ap(n,"\n")),"\n)"):cp("(",ap(n,", "),")"))+(r?" repeatable":"")+" on "+ap(s," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>ap(["extend schema",ap(e," "),op(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>ap(["extend scalar",e,ap(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>ap(["extend type",e,cp("implements ",ap(t," & ")),ap(n," "),op(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>ap(["extend interface",e,cp("implements ",ap(t," & ")),ap(n," "),op(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>ap(["extend union",e,ap(t," "),cp("= ",ap(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>ap(["extend enum",e,ap(t," "),op(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>ap(["extend input",e,ap(t," "),op(n)]," ")},TypeCoordinate:{leave:({name:e})=>e},MemberCoordinate:{leave:({name:e,memberName:t})=>ap([e,cp(".",t)])},ArgumentCoordinate:{leave:({name:e,fieldName:t,argumentName:n})=>ap([e,cp(".",t),cp("(",n,":)")])},DirectiveCoordinate:{leave:({name:e})=>ap(["@",e])},DirectiveArgumentCoordinate:{leave:({name:e,argumentName:t})=>ap(["@",e,cp("(",t,":)")])}};function ap(e,t=""){var n;return null!==(n=null==e?void 0:e.filter(e=>e).join(t))&&void 0!==n?n:""}function op(e){return cp("{\n",up(ap(e,"\n")),"\n}")}function cp(e,t,n=""){return null!=t&&""!==t?e+t+n:""}function up(e){return cp(" ",e.replace(/\n/g,"\n "))}function dp(e){var t;return null!==(t=null==e?void 0:e.some(e=>e.includes("\n")))&&void 0!==t&&t}var lp=(e=>(e.PersonalMessage="PERSONAL_MESSAGE",e.TransactionData="TRANSACTION_DATA",e))(lp||{});class hp extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t}toString(){return this.value}}new hp("\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 hp("\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 hp("\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 hp("\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 pp=new hp("\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 "),fp=new hp('\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 '),gp=new hp('\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}'),mp=new hp("\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 "),yp=new hp("\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 "),bp=new hp("\n query getReferenceGasPrice {\n epoch {\n referenceGasPrice\n }\n}\n "),wp=new hp("\n query defaultSuinsName($address: SuiAddress!) {\n address(address: $address) {\n defaultSuinsName\n }\n}\n "),vp=new hp("\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}"),Ep=new hp("\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}"),kp=new hp("\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}"),Sp=new hp("\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}"),Op=new hp("\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}"),xp=new hp("\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 Tp,Ip,_p,Ap=e=>{throw TypeError(e)},Cp=(e,t,n)=>t.has(e)||Ap("Cannot "+n),jp=(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),Pp=(e,t,n)=>(Cp(e,t,"access private method"),n);class Bp extends Fa{constructor({graphqlClient:e,mvr:t}){var n,r,s,i;super({network:e.network,base:e,mvr:t}),jp(this,Ip),jp(this,Tp),s=e,Cp(n=this,r=Tp,"write to private field"),i?i.call(n,s):r.set(n,s)}async getObjects(e){const t=Pe(e.objectIds,50),n=[];for(const e of t){const t=await Pp(this,Ip,_p).call(this,{query:Ep,variables:{objectKeys:e.map(e=>({address:e}))}},e=>e.multiGetObjects);n.push(...e.map(e=>sn(e)).map(e=>t.find(t=>t?.address===e)??new Va("notFound",`Object ${e} not found`)).map(e=>e instanceof Va?e:{id:e.address,version:e.version?.toString(),digest:e.digest,owner:Rp(e.owner),type:e.asMoveObject?.contents?.type?.repr,content:Promise.resolve(e.asMoveObject?.contents?.bcs?Ie(e.asMoveObject.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}return{objects:n}}async getOwnedObjects(e){const t=await Pp(this,Ip,_p).call(this,{query:vp,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:Rp(e.owner),type:e.contents?.type?.repr,content:Promise.resolve(e.contents?.bcs?Ie(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 Pp(this,Ip,_p).call(this,{query:gp,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:Rp(e.owner),type:e.contents?.type?.repr,balance:e.contents?.json?.balance,content:Promise.resolve(e.contents?.bcs?Ie(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}}async getBalance(e){const t=await Pp(this,Ip,_p).call(this,{query:fp,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 Pp(this,Ip,_p).call(this,{query:pp,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:$p(await Pp(this,Ip,_p).call(this,{query:Op,variables:{digest:e.digest}},e=>e.transaction))}}async executeTransaction(e){const t=await Pp(this,Ip,_p).call(this,{query:Sp,variables:{transactionDataBcs:Ae(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:$p(t.effects?.transaction)}}async dryRunTransaction(e){const t=await Pp(this,Ip,_p).call(this,{query:kp,variables:{transaction:{bcs:{value:Ae(e.transaction)}}}},e=>e.simulateTransaction);if(t.error)throw new Error(t.error);return{transaction:$p(t.effects?.transaction)}}async getReferenceGasPrice(){return{referenceGasPrice:await Pp(this,Ip,_p).call(this,{query:bp},e=>e.epoch?.referenceGasPrice)}}async getDynamicFields(e){const t=await Pp(this,Ip,_p).call(this,{query:mp,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:wi(e.parentId,t.name?.type?.repr,Ie(t.name?.bcs)),type:rn("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:Ie(t.name?.bcs)},valueType:n}}),cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage}}async verifyZkLoginSignature(e){const t="TransactionData"===e.intentScope?lp.TransactionData:lp.PersonalMessage,n=await Pp(this,Ip,_p).call(this,{query:xp,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 Pp(this,Ip,_p).call(this,{query:wp,signal:e.signal,variables:{address:e.address}},e=>e.address?.defaultSuinsName??null)}}}async getMoveFunction(e){const t=await Pp(this,Ip,_p).call(this,{query:yp,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:sn(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=>Mp(e.signature))??[],returns:t.return?.map(({signature:e})=>Mp(e))??[]}}}resolveTransactionPlugin(){throw new Error("GraphQL client does not support transaction resolution yet")}}Tp=new WeakMap,Ip=new WeakSet,_p=async function(e,t){const{data:n,errors:r}=await(s=this,i=Tp,Cp(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 Np(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 Np extends Error{constructor(e){super(e.message),this.locations=e.locations}}function Rp(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 $p(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:qa(Ie(e.effects?.effectsBcs)),epoch:e.effects?.epoch?.epochId?.toString()??null,objectTypes:Promise.resolve(t),transaction:Ka(Ie(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 Mp(e){let t=null;return"&"===e.ref?t="immutable":"&mut"===e.ref&&(t="mutable"),{reference:t,body:Up(e.body)}}function Up(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:Up(e.vector)};if("datatype"in e)return{$kind:"datatype",datatype:{typeName:`${sn(e.datatype.package)}::${e.datatype.module}::${e.datatype.type}`,typeParameters:e.datatype.typeParameters.map(e=>Up(e))}};if("typeParameter"in e)return{$kind:"typeParameter",index:e.typeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}var Dp,Fp,Lp,Vp,Kp=e=>{throw TypeError(e)},qp=(e,t,n)=>t.has(e)||Kp("Cannot "+n),zp=(e,t,n)=>(qp(e,t,"read from private field"),n?n.call(e):t.get(e)),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),Wp=(e,t,n,r)=>(qp(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class Gp extends Error{}class Hp extends bt{constructor({url:e,fetch:t=fetch,headers:n={},queries:r={},network:s="unknown",mvr:i}){super({network:s}),Zp(this,Dp),Zp(this,Fp),Zp(this,Lp),Zp(this,Vp),Wp(this,Dp,e),Wp(this,Fp,r),Wp(this,Lp,n),Wp(this,Vp,(...e)=>t(...e)),this.core=new Bp({graphqlClient:this,mvr:i})}async query(e){const t=await zp(this,Vp).call(this,zp(this,Dp),{method:"POST",headers:{"Content-Type":"application/json",...zp(this,Lp)},body:JSON.stringify({query:"string"==typeof e.query||e.query instanceof String?String(e.query):sp(e.query),variables:e.variables,extensions:e.extensions,operationName:e.operationName}),signal:e.signal});if(!t.ok)throw new Gp(`GraphQL request failed: ${t.statusText} (${t.status})`);return await t.json()}async execute(e,t){return this.query({...t,query:zp(this,Fp)[e]})}}function Jp(e,t){return Bs(e.toString(16).padStart(2*t,"0").slice(2*-t))}function Yp(e,t){const n=Jp(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 Xp(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 Qp(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=Xp(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 ef(e,t){const n=Qp(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}Dp=new WeakMap,Fp=new WeakMap,Lp=new WeakMap,Vp=new WeakMap;const tf=ut.struct("ZkLoginSignature",{inputs:ut.struct("ZkLoginSignatureInputs",{proofPoints:ut.struct("ZkLoginSignatureInputsProofPoints",{a:ut.vector(ut.string()),b:ut.vector(ut.vector(ut.string())),c:ut.vector(ut.string())}),issBase64Details:ut.struct("ZkLoginSignatureInputsClaim",{value:ut.string(),indexMod4:ut.u8()}),headerBase64:ut.string(),addressSeed:ut.string()}),maxEpoch:ut.u64(),userSignature:ut.byteVector()});var nf,rf,sf,af,of,cf=e=>{throw TypeError(e)},uf=(e,t,n)=>t.has(e)||cf("Cannot "+n),df=(e,t,n)=>(uf(e,t,"read from private field"),n?n.call(e):t.get(e)),lf=(e,t,n)=>t.has(e)?cf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),hf=(e,t,n,r)=>(uf(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),pf=(e,t,n)=>(uf(e,t,"access private method"),n);nf=new WeakMap,rf=new WeakMap,sf=new WeakMap,af=new WeakSet,of=function(){const e=mf(df(this,nf),!0),t=new Uint8Array(e.length+1);return t[0]=this.flag(),t.set(e,1),sn(xs(bi(t,{dkLen:32})).slice(0,64))};let ff=class e extends Lh{constructor(e,{client:t}={}){super(),lf(this,af),lf(this,nf),lf(this,rf),lf(this,sf),hf(this,rf,t),"string"==typeof e?hf(this,nf,Ie(e)):e instanceof Uint8Array?hf(this,nf,e):hf(this,nf,Uint8Array.from(e)),hf(this,sf,df(this,nf).length!==df(this,nf)[0]+1+32),df(this,sf)&&hf(this,nf,mf(df(this,nf)))}static fromBytes(t,{client:n,address:r,legacyAddress:s}={}){let i;if(!0===s?i=new e(mf(t,!0),{client:n}):!1===s?i=new e(mf(t,!1),{client:n}):r?(i=new e(mf(t,!1),{client:n}),i.toSuiAddress()!==r&&(i=new e(mf(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=ef(n,"iss"),i=gf(BigInt(r),s,{legacyAddress:!0});if(i.toSuiAddress()===e)return i;const a=gf(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 df(this,sf)?pf(this,af,of).call(this):super.toSuiAddress()}toRawBytes(){return df(this,nf)}flag(){return dh.ZkLogin}async verify(e,t){throw Error("does not support")}verifyPersonalMessage(t,n){const r=bf(n);return yf({address:new e(r.publicKey).toSuiAddress(),bytes:Ae(t),signature:r.serializedSignature,intentScope:"PersonalMessage",client:df(this,rf)})}verifyTransaction(t,n){const r=bf(n);return yf({address:new e(r.publicKey).toSuiAddress(),bytes:Ae(t),signature:r.serializedSignature,intentScope:"TransactionData",client:df(this,rf)})}verifyAddress(e){return e===super.toSuiAddress()||e===pf(this,af,of).call(this)}};function gf(e,t,n){const r=n?.legacyAddress?Yp(e,32):Jp(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 ff(i,n)}function mf(e,t=!1){const n=e[0]+1,r=BigInt(`0x${je(e.slice(n))}`),s=t?Yp(r,32):Jp(r,32),i=new Uint8Array(n+s.length);return i.set(e.slice(0,n),0),i.set(s,n),i}async function yf({address:e,bytes:t,signature:n,intentScope:r,client:s=new Hp({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 bf(e){const t="string"==typeof e?Ie(e):e;if(t[0]!==dh.ZkLogin)throw new Error("Invalid signature scheme");const n=t.slice(1),{inputs:r,maxEpoch:s,userSignature:i}=function(e){return tf.parse("string"==typeof e?Ie(e):e)}(n),{issBase64Details:a,addressSeed:o}=r,c=ef(a,"iss"),u=gf(BigInt(o),c);return{serializedSignature:Ae(t),signatureScheme:"ZkLogin",zkLogin:{inputs:r,maxEpoch:s,userSignature:i,iss:c,addressSeed:BigInt(o)},signature:t,publicKey:u.toRawBytes()}}function wf(e){const t=Ie(e),n=hh[t[0]];switch(n){case"Passkey":return Kh(e);case"MultiSig":return{serializedSignature:e,signatureScheme:n,multisig:_r.MultiSig.parse(t.slice(1)),bytes:t,signature:void 0};case"ZkLogin":return bf(e);case"ED25519":case"Secp256k1":case"Secp256r1":return Vh(e);default:throw new Error("Unsupported signature scheme")}}const vf="suiprivkey";class Ef{async signWithIntent(e,t){const n=uh(t,e),r=bi(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([dh[t]]),s.set(e,1),s.set(r,1+e.length),Ae(s)}({signature:await this.sign(r),signatureScheme:this.getKeyScheme(),publicKey:this.getPublicKey()}),bytes:Ae(e)}}async signTransaction(e){return this.signWithIntent(e,"TransactionData")}async signPersonalMessage(e){const{signature:t}=await this.signWithIntent(ut.byteVector().serialize(e).toBytes(),"PersonalMessage");return{bytes:Ae(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 kf extends Ef{}function Sf(e){const{prefix:t,words:n}=Oe.decode(e);if(t!==vf)throw new Error("invalid private key prefix");const r=new Uint8Array(Oe.fromWords(n)),s=r.slice(1),i=hh[r[0]];return{scheme:i,schema:i,secretKey:s}}function Of(e,t){if(32!==e.length)throw new Error("Invalid bytes length");const n=dh[t],r=new Uint8Array(e.length+1);return r.set([n]),r.set(e,1),Oe.encode(vf,Oe.toWords(r))}function xf(e,t,n,r){ls(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(us(i),us(a),us(o),i<1)throw new Error("iterations (c) should be >= 1");const c=$s(t),u=$s(n),d=new Uint8Array(a),l=fh.create(e,c),h=l._cloneInto().update(u);return{c:i,dkLen:a,asyncTick:o,DK:d,PRF:l,PRFSalt:h}}function Tf(e,t,n,r){const{c:s,dkLen:i,DK:a,PRF:o,PRFSalt:c}=xf(e,t,n,r);let u;const d=new Uint8Array(4),l=ms(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(),gs(s),n}(o,c,a,u,h)}function If(e){if("string"!=typeof e)throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function _f(e,t=""){return Tf(Ad,function(e){const t=If(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=>If("mnemonic"+e))(t),{c:2048,dkLen:64})}function Af(e){return!!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(e)}function Cf(e){return!!new RegExp("^m\\/(54|74)'\\/784'\\/[0-9]+'\\/[0-9]+\\/[0-9]+$").test(e)}function jf(e){return _f(e,"")}const Pf=Ad,Bf=new RegExp("^m(\\/[0-9]+')+$"),Nf=e=>e.replace("'",""),Rf=(e,t,n=2147483648)=>{if(!(e=>!!Bf.test(e)&&!e.split("/").slice(1).map(Nf).some(isNaN))(e))throw new Error("Invalid derivation path");const{key:r,chainCode:s}=(e=>{const t=fh.create(Pf,"ed25519 seed").update(Ce(e)).digest();return{key:t.slice(0,32),chainCode:t.slice(32)}})(t);return e.split("/").slice(1).map(Nf).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=fh.create(Pf,t).update(s).digest();return{key:i.slice(0,32),chainCode:i.slice(32)}})(e,t+n),{key:r,chainCode:s})};class $f extends Lh{constructor(e){if(super(),"string"==typeof e?this.data=Ie(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 dh.ED25519}async verify(e,t){let n;if("string"==typeof t){const e=Vh(t);if("ED25519"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Fh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Xl.verify(n,e,this.toRawBytes())}}$f.SIZE=32;const Mf="m/44'/784'/0'/0'/0'";class Uf extends kf{constructor(e){if(super(),e)this.keypair={publicKey:e.publicKey,secretKey:e.secretKey.slice(0,32)};else{const e=Xl.utils.randomPrivateKey();this.keypair={publicKey:Xl.getPublicKey(e),secretKey:e}}}getKeyScheme(){return"ED25519"}static generate(){const e=Xl.utils.randomPrivateKey();return new Uf({publicKey:Xl.getPublicKey(e),secretKey:e})}static fromSecretKey(e,t){if("string"==typeof e){const n=Sf(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:Xl.getPublicKey(e),secretKey:e};if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),n=Xl.sign(t,e);if(!Xl.verify(n,t,r.publicKey))throw new Error("provided secretKey is invalid")}return new Uf(r)}getPublicKey(){return new $f(this.keypair.publicKey)}getSecretKey(){return Of(this.keypair.secretKey.slice(0,32),this.getKeyScheme())}async sign(e){return Xl.sign(e,this.keypair.secretKey)}static deriveKeypair(e,t){if(null==t&&(t=Mf),!Af(t))throw new Error("Invalid derivation path");const{key:n}=Rf(t,function(e){return je(jf(e))}(e));return Uf.fromSecretKey(n)}static deriveKeypairFromSeed(e,t){if(null==t&&(t=Mf),!Af(t))throw new Error("Invalid derivation path");const{key:n}=Rf(t,e);return Uf.fromSecretKey(n)}}const Df={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ff={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Lf=BigInt(2);const Vf=gl(Df.p,void 0,void 0,{sqrt:function(e){const t=Df.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=sl(d,n,t)*d%t,h=sl(l,n,t)*d%t,p=sl(h,Lf,t)*u%t,f=sl(p,s,t)*p%t,g=sl(f,i,t)*f%t,m=sl(g,o,t)*g%t,y=sl(m,c,t)*m%t,b=sl(y,o,t)*g%t,w=sl(b,n,t)*d%t,v=sl(w,a,t)*f%t,E=sl(v,r,t)*u%t,k=sl(E,Lf,t);if(!Vf.eql(Vf.sqr(k),e))throw new Error("Cannot find square root");return k}}),Kf=Ch({...Df,Fp:Vf,lowS:!0,endo:Ff},_d),qf=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),zf=(()=>Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)))(),Zf=(()=>zf.map(e=>(9*e+5)%16))(),Wf=(()=>{const e=[[zf],[Zf]];for(let t=0;t<4;t++)for(let n of e)n.push(n[t].map(e=>qf[e]));return e})(),Gf=(()=>Wf[0])(),Hf=(()=>Wf[1])(),Jf=[[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)),Yf=Gf.map((e,t)=>e.map(e=>Jf[t][e])),Xf=Hf.map((e,t)=>e.map(e=>Jf[t][e])),Qf=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),eg=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function tg(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 ng=new Uint32Array(16);class rg extends zs{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)ng[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=Qf[e],p=eg[e],f=Gf[e],g=Hf[e],m=Yf[e],y=Xf[e];for(let t=0;t<16;t++){const r=bs(n+tg(e,s,a,c)+ng[f[t]]+h,m[t])+d|0;n=d,d=c,c=0|bs(a,10),a=s,s=r}for(let e=0;e<16;e++){const n=bs(r+tg(t,i,o,u)+ng[g[e]]+p,y[e])+l|0;r=l,l=u,u=0|bs(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(){gs(ng)}destroy(){this.destroyed=!0,gs(this.buffer),this.set(0,0,0,0,0)}}const sg=Ds(()=>new rg),ig=Kf.ProjectivePoint,ag=(e=>{return se((n=t=>e(e(t)),ee(t=4),X(n),{encode(e){if(!J(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(!J(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}}),be);var t,n})(_d);function og(e){ds(e);const t=0===e.length?"0":xs(e);return BigInt("0x"+t)}const cg=Ns("Bitcoin seed"),ug={private:76066276,public:76067358},dg=2147483648,lg=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 ms(t).setUint32(0,e,!1),t};class hg{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return ms(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 ag.encode(this.serialize(this.versions.private,Ms(new Uint8Array([0]),e)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return ag.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(e,t=ug){if(ds(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=fh(Ad,cg,e);return new hg({versions:t,chainCode:n.slice(32),privateKey:n.slice(0,32)})}static fromExtendedKey(e,t=ug){const n=ag.decode(e),r=ms(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 hg(o?{...i,privateKey:a.slice(1)}:{...i,publicKey:a})}static fromJSON(e){return hg.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||ug,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(!Kf.utils.isValidPrivateKey(e.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof e.privateKey?e.privateKey:og(e.privateKey),this.privKeyBytes=function(e){if("bigint"!=typeof e)throw new Error("bigint expected");return Bs(e.toString(16).padStart(64,"0"))}(this.privKey),this.pubKey=Kf.getPublicKey(e.privateKey,!0)}else{if(!e.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=ig.fromHex(e.publicKey).toRawBytes(!0)}var t;this.pubHash=(t=this.pubKey,sg(_d(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>=dg)throw new Error("Invalid index");"'"===t[2]&&(s+=dg),n=n.deriveChild(s)}return n}deriveChild(e){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let t=lg(e);if(e>=dg){const e=this.privateKey;if(!e)throw new Error("Could not derive hardened child key");t=Ms(new Uint8Array([0]),e,t)}else t=Ms(this.pubKey,t);const n=fh(Ad,this.chainCode,t),r=og(n.slice(0,32)),s=n.slice(32);if(!Kf.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=rl(this.privKey+r,Kf.CURVE.n);if(!Kf.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=ig.fromHex(this.pubKey).add(ig.fromPrivateKey(r));if(e.equals(ig.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=e.toRawBytes(!0)}return new hg(i)}catch(t){return this.deriveChild(e+1)}}sign(e){if(!this.privateKey)throw new Error("No privateKey set!");return ds(e,32),Kf.sign(e,this.privKey).toCompactRawBytes()}verify(e,t){if(ds(e,32),ds(t,64),!this.publicKey)throw new Error("No publicKey set!");let n;try{n=Kf.Signature.fromCompact(t)}catch(e){return!1}return Kf.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 ds(t,33),Ms(lg(e),new Uint8Array([this.depth]),lg(this.parentFingerprint),lg(this.index),this.chainCode,t)}}class pg extends Lh{constructor(e){if(super(),"string"==typeof e?this.data=Ie(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 dh.Secp256k1}async verify(e,t){let n;if("string"==typeof t){const e=Vh(t);if("Secp256k1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Fh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Kf.verify(Kf.Signature.fromCompact(n),Dh(e),this.toRawBytes())}}pg.SIZE=33;class fg extends kf{constructor(e){if(super(),e)this.keypair=e;else{const e=Kf.utils.randomPrivateKey(),t=Kf.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256k1"}static generate(){return new fg}static fromSecretKey(e,t){if("string"==typeof e){const n=Sf(e);if("Secp256k1"!==n.schema)throw new Error(`Expected a Secp256k1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=Kf.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=xs(bi(t,{dkLen:32})),s=Kf.sign(r,e);if(!Kf.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new fg({publicKey:n,secretKey:e})}static fromSeed(e){const t=Kf.getPublicKey(e,!0);return new fg({publicKey:t,secretKey:e})}getPublicKey(){return new pg(this.keypair.publicKey)}getSecretKey(){return Of(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Dh(e);return Kf.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/54'/784'/0'/0/0"),!Cf(t))throw new Error("Invalid derivation path");const n=hg.fromMasterSeed(jf(e)).derive(t);if(null==n.publicKey||null==n.privateKey)throw new Error("Invalid key");return new fg({publicKey:n.publicKey,secretKey:n.privateKey})}}class gg extends Lh{constructor(e){if(super(),"string"==typeof e?this.data=Ie(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 dh.Secp256r1}async verify(e,t){let n;if("string"==typeof t){const e=wf(t);if("Secp256r1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Fh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Uh.verify(Uh.Signature.fromCompact(n),Dh(e),this.toRawBytes())}}gg.SIZE=33;class mg extends kf{constructor(e){if(super(),e)this.keypair=e;else{const e=Uh.utils.randomPrivateKey(),t=Uh.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256r1"}static generate(){return new mg}static fromSecretKey(e,t){if("string"==typeof e){const n=Sf(e);if("Secp256r1"!==n.schema)throw new Error(`Expected a Secp256r1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=Uh.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=xs(bi(t,{dkLen:32})),s=Uh.sign(r,e,{lowS:!0});if(!Uh.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new mg({publicKey:n,secretKey:e})}static fromSeed(e){const t=Uh.getPublicKey(e,!0);return new mg({publicKey:t,secretKey:e})}getPublicKey(){return new gg(this.keypair.publicKey)}getSecretKey(){return Of(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Dh(e);return Uh.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/74'/784'/0'/0/0"),!Cf(t))throw new Error("Invalid derivation path");const n=hg.fromMasterSeed(jf(e)).derive(t).privateKey;return mg.fromSecretKey(n)}}var yg;function bg(e,t=!1){let n,r;if("object"==typeof e){if(!t)throw new Error("Invalid secret key format");r=Ie(e.privateKey),n=e.schema}else{const t=Sf(e);n=t.schema,r=t.secretKey}switch(n){case"ED25519":{let e=r;return 64===r.length&&(e=r.slice(0,32)),Uf.fromSecretKey(e)}case"Secp256k1":return fg.fromSecretKey(r);case"Secp256r1":return mg.fromSecretKey(r);default:throw new Error(`Invalid keypair schema: ${n}`)}}async function wg(e,t){const n=await e.signPersonalMessage(t);return vg("string"==typeof n?n:n.signature,!0)}function vg(e,t=!1){const n=wf(e);let r=i.Buffer.from(n.signature).toString("hex"),s=i.Buffer.from(n.publicKey).toString("base64"),a=exports.SignerTypes.KP_SECP256;if("Secp256k1"===n.signatureScheme||"Secp256r1"===n.signatureScheme)a=exports.SignerTypes.KP_SECP256;else if("ED25519"===n.signatureScheme)a=t?exports.SignerTypes.KP_ED25519:exports.SignerTypes.UI_ED25519;else{if("ZkLogin"!==n.signatureScheme)throw new Error(`Unsupported signature scheme: ${n.signatureScheme}`);a=exports.SignerTypes.ZK_ED25519}return`${r}${a}${s}`}function Eg(e,t=18){if(!e&&0!==e)return"0";try{const n=new d.default(e);if(n.isNaN())return"0";return n.multipliedBy(new d.default(10).pow(t)).integerValue(d.default.ROUND_DOWN).toString(10)}catch(e){return"0"}}function kg(e,t=18){return new d.default(e).multipliedBy(new d.default(10).pow(t))}function Sg(e){return e instanceof Error?e.message:"string"==typeof e?e:String(e)}function Og(e){const t=function(){try{if(void 0!=={url:"undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href}&&("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href)){const e=c.fileURLToPath("undefined"==typeof document?new(require("url").URL)("file:"+e).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href);return p.default.dirname(e)}}catch(e){}return"undefined"!=typeof __dirname?__dirname:process.cwd()}();let n=null;if(p.default.isAbsolute(e))n=e;else{const r=p.default.resolve(t,".."),s=p.default.resolve(r,e);if(h.default.existsSync(s))n=s;else{const r=function(e){let t=e;const n=p.default.parse(t).root;for(;t!==n;){const e=p.default.join(t,"package.json");if(h.default.existsSync(e))try{if("@dipcoinlab/perp-client-ts"===JSON.parse(h.default.readFileSync(e,"utf-8")).name)return t}catch(e){}const n=p.default.dirname(t);if(n===t)break;t=n}return null}(t);if(r){const t=p.default.resolve(r,"dist",e);h.default.existsSync(t)&&(n=t)}if(!n){const t=p.default.resolve(process.cwd(),e);h.default.existsSync(t)&&(n=t)}}}if(!n||!h.default.existsSync(n))return{packages:[]};const r=JSON.parse(h.default.readFileSync(n).toString());return r.packages&&Array.isArray(r.packages)||(r.packages=[]),r}exports.SignerTypes=void 0,(yg=exports.SignerTypes||(exports.SignerTypes={})).KP_SECP256="0",yg.KP_ED25519="1",yg.UI_ED25519="2",yg.ZK_ED25519="3";class xg{httpClient;keypair;subKeypair;walletAddress;subAddress;options;jwtToken;subJwtToken;isAuthenticating=!1;isSubAuthenticating=!1;exchangeOnChain;deploymentConfig;suiClient;transactionBuilder;priceServiceConnection;pythClient;tradingPairsCache;tradingPairsCacheTimestamp;constructor(t,n){this.options=n,this.httpClient=new gd(n.apiBaseUrl),this.keypair="string"==typeof t?bg(t):t,n.subAccountKey&&(this.subKeypair=bg(n.subAccountKey),this.subAddress=this.subKeypair.getPublicKey().toSuiAddress()),this.walletAddress=this.keypair.getPublicKey().toSuiAddress(),this.httpClient.setWalletAddress(this.walletAddress),this.deploymentConfig=Og(`config/deployed/${n.network}/main_contract.json`);const r=n.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}`)}}(n.network);this.suiClient=new ao({url:r}),this.exchangeOnChain=new e.ExchangeOnChain(this.deploymentConfig,this.suiClient,this.keypair);const s=this.getDeploymentPackageId(),i=this.getDeploymentProtocolConfigId();this.transactionBuilder=new e.TransactionBuilder(s,i,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(hd),t=await wg(this.keypair,e),n=await this.httpClient.post(ld.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:Sg(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(hd),t=await wg(this.subKeypair,e),n=this.subKeypair.getPublicKey().toSuiAddress(),r=await this.httpClient.post(ld.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:Sg(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(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===exports.OrderType.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:l=!1,clientId:h="",creator:p,tpTriggerPrice:f,tpOrderType:g=exports.OrderType.MARKET,tpOrderPrice:m="",slTriggerPrice:y,slOrderType:b=exports.OrderType.MARKET,slOrderPrice:w=""}=t,v=p||this.walletAddress,E=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?kg(o):new d.default(0),S=kg(a),O=kg(c),x=new d.default(0),T=new d.default(+new Date),I={market:u,creator:v,isLong:s===exports.OrderSide.BUY,reduceOnly:l,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:i===exports.OrderType.LIMIT?k:new d.default(0),leverage:O,expiration:x,salt:T};let _=null,A=null;f&&(A=new d.default(Date.now()+1),_={market:I.market,creator:v,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:g===exports.OrderType.LIMIT?kg(m||f):kg(""),leverage:O,expiration:x,salt:A});let C=null,j=null;y&&(j=new d.default(Date.now()+2),C={market:I.market,creator:v,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:b===exports.OrderType.LIMIT?kg(w||y):kg(""),leverage:O,expiration:x,salt:j});const P=e.OrderSigner.getOrderMessageForUIWallet(I),B=(new TextEncoder).encode(P),N=await wg(E,B);let R,$;if(_){const t=e.OrderSigner.getOrderMessageForUIWallet(_),n=(new TextEncoder).encode(t);R=await wg(E,n)}if(C){const t=e.OrderSigner.getOrderMessageForUIWallet(C),n=(new TextEncoder).encode(t);$=await wg(E,n)}const M={symbol:r,side:s,orderType:i,quantity:Eg(a),price:Eg(o||""),leverage:Eg(c),salt:T.toString(),creator:v,clientId:h,reduceOnly:l,orderSignature:N};f&&R&&(M.tpOrderSignature=R,M.tpTriggerPrice=Eg(f),M.tpOrderType=g,M.tpOrderPrice=g===exports.OrderType.LIMIT?Eg(m||f):Eg(""),M.tpSalt=A?.toString(),M.triggerWay="oracle"),y&&$&&(M.slOrderSignature=$,M.slTriggerPrice=Eg(y),M.slOrderType=b,M.slOrderPrice=b===exports.OrderType.LIMIT?Eg(w||y):Eg(""),M.slSalt=j?.toString());const U=await this.httpClient.post(ld.PLACE_ORDER,M);if(1e3===U.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(ld.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:Sg(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 wg(i,o),parentAddress:s},u=await this.httpClient.post(ld.CANCEL_ORDER,c);if(1e3===u.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(ld.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:Sg(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:Eg(r)};let a=await this.httpClient.post(ld.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(ld.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:Sg(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(ld.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(ld.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:Sg(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:l=!0,postOnly:h=!1,orderbookOnly:p=!0,ioc:f=!1,tp:g,sl:m}=t;if(!this.isPositiveNumber(u))return{status:!1,error:"Quantity must be greater than zero"};const y=this.hasTpSlOrderConfig(g,u),b=this.hasTpSlOrderConfig(m,u);if(!y&&!b)return{status:!1,error:"At least one TP or SL configuration is required"};const w=kg(c),v=Eg(c),E=new d.default(0),k=new d.default(+new Date),S=k.plus(1),O={symbol:s,side:a,leverage:v,creator:this.walletAddress},x=async e=>{let t=await this.httpClient.post(ld.PLAN_CLOSE_ORDER,e);if(1e3===t.code){this.clearAuth();(await this.authenticate()).status&&(t=await this.httpClient.post(ld.PLAN_CLOSE_ORDER,e))}return t},T={};let I,_;if(y&&g){if(!this.isPositiveNumber(g.triggerPrice))return{status:!1,error:"TP trigger price must be greater than zero"};const t=g.salt?new d.default(g.salt):k,n=kg(g.quantity??u),s=(g.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?kg(g.orderPrice??g.triggerPrice??"0"):new d.default(0),a={market:i,creator:this.walletAddress,isLong:o,reduceOnly:l,postOnly:h,orderbookOnly:p,ioc:f,quantity:n,price:s,leverage:w,expiration:E,salt:t},c=e.OrderSigner.getOrderMessageForUIWallet(a),m=await wg(r,(new TextEncoder).encode(c));I={...O,tpOrderType:g.orderType||exports.OrderType.MARKET,tpTpslType:g.tpslType||"position",tpTriggerPrice:Eg(g.triggerPrice),tpOrderPrice:(g.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?Eg(g.orderPrice??g.triggerPrice??"0"):"0",tpQuantity:Eg(g.quantity??u),tpTriggerWay:g.triggerWay||"oracle",tpSalt:t.toString(),tpOrderSignature:m},void 0!==g.planId&&(I.tpPlanId=g.planId)}if(b&&m){if(!this.isPositiveNumber(m.triggerPrice))return{status:!1,error:"SL trigger price must be greater than zero"};const t=m.salt?new d.default(m.salt):S,n=kg(m.quantity??u),s=(m.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?kg(m.orderPrice??m.triggerPrice??"0"):new d.default(0),a={market:i,creator:this.walletAddress,isLong:o,reduceOnly:l,postOnly:h,orderbookOnly:p,ioc:f,quantity:n,price:s,leverage:w,expiration:E,salt:t},c=e.OrderSigner.getOrderMessageForUIWallet(a),g=await wg(r,(new TextEncoder).encode(c));_={...O,slOrderType:m.orderType||exports.OrderType.MARKET,slTpslType:m.tpslType||"position",slTriggerPrice:Eg(m.triggerPrice),slOrderPrice:(m.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?Eg(m.orderPrice??m.triggerPrice??"0"):"0",slQuantity:Eg(m.quantity??u),slTriggerWay:m.triggerWay||"oracle",slSalt:t.toString(),slOrderSignature:g},void 0!==m.planId&&(_.slPlanId=m.planId)}if(y&&b&&I&&_){const e={...I,..._},t=await x(e);T.tpResult=t,T.slResult=t}else y&&I?T.tpResult=await x(I):b&&_&&(T.slResult=await x(_));return[T.tpResult,T.slResult].some(e=>e&&200===e.code)?(this.restoreMainAuth(),{status:!0,data:T}):(this.restoreMainAuth(),{status:!1,data:T,error:T.tpResult?.message||T.slResult?.message||"Failed to place TP/SL order"})}catch(e){return this.restoreMainAuth(),{status:!1,error:Sg(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(ld.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(ld.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:Sg(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(ld.GET_ACCOUNT_INFO,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ld.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:Sg(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(ld.GET_POSITIONS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ld.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:Sg(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(ld.GET_TRADING_PAIRS);if(1e3===t.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ld.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:Sg(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(ld.GET_OPEN_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(ld.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:Sg(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(ld.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:Sg(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 d.default(e);return n.isNaN()||n.isZero()?"0":n.dividedBy(new d.default(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(ld.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:Sg(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 d.default(e).gt(0)}catch{return!1}}processTickerData(e){let t;if(e.bestAskPrice&&e.bestBidPrice){const n=new d.default(e.bestAskPrice),r=new d.default(e.bestBidPrice);t=n.plus(r).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(ld.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(ld.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:Sg(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(ld.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(ld.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:Sg(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(ld.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(ld.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:Sg(e)}}}async getOraclePrice(e){try{if(!e)return{status:!1,error:"Symbol is required"};await this.authenticate().catch(()=>{});const t=await this.httpClient.get(ld.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:Sg(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:r,symbol:s,market:i,perpId:a,subAccountsMapId:o,gasBudget:c,txHash:u}=e;if(!this.isPositiveNumber(n))throw new Error(`Amount must be greater than zero to ${t} margin`);const l=new d.default(n).toNumber();if(!Number.isFinite(l))throw new Error("Amount is too large to represent as a number");const h=i||s,p=h?h.toUpperCase():void 0,f=a||(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:r||this.walletAddress,market:p,perpID:f,subAccountsMapID:o,gasBudget:c,txHash:u}}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 Ua;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 Ua,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=fd[this.options.network];e&&(this.priceServiceConnection||(this.priceServiceConnection=new cd(e.priceServiceUrl)),this.pythClient||(this.pythClient=new dd(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:Eg(e,pd.USDC),accountAddress:this.address},this.keypair)}async withdrawFromBank(e){return await this.exchangeOnChain.withdrawFromBank({amount:Eg(e,pd.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:Sg(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:Sg(e)}}}}exports.API_ENDPOINTS=ld,exports.DECIMALS=pd,exports.DEFAULT_API_URLS=f,exports.DEFAULT_SLIPPAGE=.05,exports.DipCoinPerpSDK=xg,exports.HttpClient=gd,exports.ONBOARDING_MESSAGE=hd,exports.PYTH_CONFIG=fd,exports.buildSignature=vg,exports.default=xg,exports.formatError=Sg,exports.formatNormalToWei=Eg,exports.formatNormalToWeiBN=kg,exports.fromExportedKeypair=bg,exports.initDipCoinPerpSDK=function(e,t){const n=g(t);return new xg(e,n)},exports.initSDKOptions=g,exports.readFile=Og,exports.signMessage=wg;
3
+ function X(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Q(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function ee(e){if("function"!=typeof e)throw new Error("function expected");return!0}function te(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function ne(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function re(e){if(!Array.isArray(e))throw new Error("array expected")}function se(e,t){if(!Q(!0,t))throw new Error(`${e}: array of strings expected`)}function ie(e,t){if(!Q(!1,t))throw new Error(`${e}: array of numbers expected`)}function ae(...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 oe(e){const t="string"==typeof e?e.split(""):e,n=t.length;se("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(re(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=>(re(t),t.map(t=>{te("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function ce(e=""){return te("join",e),{encode:t=>(se("join.decode",t),t.join(e)),decode:t=>(te("join.decode",t),t.split(e))}}function ue(e,t="="){return ne(e),te("padding",t),{encode(n){for(se("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){se("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 de(e){return ee(e),{encode:e=>e,decode:t=>e(t)}}function le(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(re(e),!e.length)return[];let r=0;const s=[],i=Array.from(e,e=>{if(ne(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()}F=new WeakMap,L=new WeakMap,K=new WeakMap,q=new WeakSet,z=function(){if(!G(this,K)){const e=G(this,L).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");J(this,K,new U(G(this,L).websocket?.url??G(this,L).url,{WebSocketConstructor:e,...G(this,L).websocket}))}return G(this,K)};const he=(e,t)=>0===t?e:he(t,e%t),pe=(e,t)=>e+(t-he(e,t)),fe=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function ge(e,t,n,r){if(re(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(pe(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${pe(t,n)}`);let s=0,i=0;const a=fe[t],o=fe[n]-1,c=[];for(const r of e){if(ne(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=fe[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 me(e,t=!1){if(ne(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(pe(8,e)>32||pe(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!X(n))throw new Error("radix2.encode input should be Uint8Array");return ge(Array.from(n),8,e,!t)},decode:n=>(ie("radix2.decode",n),Uint8Array.from(ge(n,e,8,t)))}}function ye(e){return ee(e),function(...t){try{return e.apply(null,t)}catch(e){}}}ae(me(4),oe("0123456789ABCDEF"),ce("")),ae(me(5),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ue(5),ce("")),ae(me(5),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ce("")),ae(me(5),oe("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ue(5),ce("")),ae(me(5),oe("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ce("")),ae(me(5),oe("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ce(""),de(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const be=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();be||ae(me(6),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ue(6),ce("")),ae(me(6),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ce("")),be||ae(me(6),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ue(6),ce("")),ae(me(6),oe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ce(""));const we=e=>{return ae((ne(t=58),{encode:e=>{if(!X(e))throw new Error("radix.encode input should be Uint8Array");return le(Array.from(e),256,t)},decode:e=>(ie("radix.decode",e),Uint8Array.from(le(e,t,256)))}),oe(e),ce(""));var t},ve=we("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");we("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),we("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const ke=ae(oe("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ce("")),Ee=[996825010,642813549,513874426,1027748829,705979059];function Se(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<Ee.length;e++)1==(t>>e&1)&&(n^=Ee[e]);return n}function xe(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=Se(s)^n>>5}s=Se(s);for(let t=0;t<r;t++)s=Se(s)^31&e.charCodeAt(t);for(let e of t)s=Se(s)^e;for(let e=0;e<6;e++)s=Se(s);return s^=n,ke.encode(ge([s%fe[30]],30,5,!1))}function Oe(e){const t="bech32"===e?1:734539939,n=me(5),r=n.decode,s=n.encode,i=ye(r);function a(e,n,r=90){te("bech32.encode prefix",e),X(n)&&(n=Array.from(n)),ie("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=xe(a,n,t);return`${a}1${ke.encode(n)}${o}`}function o(e,n=90){te("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=ke.decode(o).slice(0,-6),u=xe(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:ye(o),fromWords:r,fromWordsUnsafe:i,toWords:s}}const Te=Oe("bech32");Oe("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||ae(me(4),oe("0123456789abcdef"),ce(""),de(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 Ie=e=>ve.encode(e),_e=e=>ve.decode(e);function Ae(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}const Ce=8192;function je(e){if(e.length<Ce)return btoa(String.fromCharCode(...e));let t="";for(var n=0;n<e.length;n+=Ce){const r=e.slice(n,n+Ce);t+=String.fromCharCode(...r)}return btoa(t)}function Pe(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 Be(e){return e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Ne(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}class Re{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 $e;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 Ue(t);let n;try{n=e._batchLoadFn(t.keys)}catch(n){return De(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 De(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(!Ve(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)}`);Ue(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=>{De(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(!Ve(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 $e="object"==typeof process&&"function"==typeof process.nextTick?function(e){Me||(Me=Promise.resolve()),Me.then(()=>{process.nextTick(e)})}:"function"==typeof setImmediate?function(e){setImmediate(e)}:function(e){setTimeout(e)};let Me;function De(e,t,n){Ue(t);for(let r=0;r<t.keys.length;r++)e.clear(t.keys[r]),t.callbacks[r].reject(n)}function Ue(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Ve(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 Fe(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 Le{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 Ke(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 qe{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 ze(BigInt(e),8).forEach(e=>this.write8(e)),this}write128(e){return ze(BigInt(e),16).forEach(e=>this.write8(e)),this}write256(e){return ze(BigInt(e),32).forEach(e=>this.write8(e)),this}writeULEB(e){return Fe(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 Ie(e);case"base64":return je(e);case"hex":return Be(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}(this.toBytes(),e)}}function ze(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 Ze,We,Ge,He,Je=e=>{throw TypeError(e)},Ye=(e,t,n)=>t.has(e)||Je("Cannot "+n),Xe=(e,t,n)=>(Ye(e,t,"read from private field"),n?n.call(e):t.get(e)),Qe=(e,t,n)=>t.has(e)?Je("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),et=(e,t,n,r)=>(Ye(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);Ze=new WeakMap,We=new WeakMap;let tt=class e{constructor(e){Qe(this,Ze),Qe(this,We),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),et(this,Ze,e.write),et(this,We,e.serialize??((e,t)=>{const n=new qe({initialSize:this.serializedSize(e)??void 0,...t});return Xe(this,Ze).call(this,e,n),n.toBytes()})),this.validate=e.validate??(()=>{})}write(e,t){this.validate(e),Xe(this,Ze).call(this,e,t)}serialize(e,t){return this.validate(e),new st(this,Xe(this,We).call(this,e,t))}parse(e){const t=new Le(e);return this.read(t)}fromHex(e){return this.parse(Pe(e))}fromBase58(e){return this.parse(_e(e))}fromBase64(e){return this.parse(Ae(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)=>Xe(this,Ze).call(this,n?n(e):e,t),serializedSize:e=>this.serializedSize(n?n(e):e),serialize:(e,t)=>Xe(this,We).call(this,n?n(e):e,t),validate:e=>{s?.(e),this.validate(n?n(e):e)}})}};const nt=Symbol.for("@mysten/serialized-bcs");function rt(e){return!!e&&"object"==typeof e&&!0===e[nt]}class st{constructor(e,t){Qe(this,Ge),Qe(this,He),et(this,Ge,e),et(this,He,t)}get[nt](){return!0}toBytes(){return Xe(this,He)}toHex(){return Be(Xe(this,He))}toBase64(){return je(Xe(this,He))}toBase58(){return Ie(Xe(this,He))}parse(){return Xe(this,Ge).parse(Xe(this,He))}}function it({size:e,...t}){return new tt({...t,serializedSize:()=>e})}function at({readMethod:e,writeMethod:t,...n}){return it({...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 ot({readMethod:e,writeMethod:t,...n}){return it({...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)}})}Ge=new WeakMap,He=new WeakMap;class ct extends tt{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 ut extends tt{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 dt extends tt{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 lt={u8:e=>at({readMethod:"read8",writeMethod:"write8",size:1,maxValue:255,...e,name:e?.name??"u8"}),u16:e=>at({readMethod:"read16",writeMethod:"write16",size:2,maxValue:65535,...e,name:e?.name??"u16"}),u32:e=>at({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:e?.name??"u32"}),u64:e=>ot({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:e?.name??"u64"}),u128:e=>ot({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:e?.name??"u128"}),u256:e=>ot({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:e?.name??"u256"}),bool:e=>it({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 tt({...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(Fe(e)),...e,name:e?.name??"uleb128"}),bytes:(e,t)=>it({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 tt({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:Fe(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 tt({...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=Fe(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 tt({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 lt.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 tt({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 dt({fields:e,...t}),struct:(e,t,n)=>new ct({name:e,fields:t,...n}),enum:(e,t,n)=>new ut({name:e,fields:t,...n}),map:function(e,t){return lt.vector(lt.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 tt({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 ht,pt,ft=e=>{throw TypeError(e)},gt=(e,t,n)=>t.has(e)||ft("Cannot "+n),mt=(e,t,n)=>(gt(e,t,"read from private field"),n?n.call(e):t.get(e)),yt=(e,t,n)=>t.has(e)?ft("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),bt=(e,t,n,r)=>(gt(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);ht=new WeakMap,pt=new WeakMap;let wt=class e{constructor({prefix:e,cache:t}={}){yt(this,ht),yt(this,pt),bt(this,ht,e??[]),bt(this,pt,t??new Map)}read(e,t){const n=[mt(this,ht),...e].join(":");if(mt(this,pt).has(n))return mt(this,pt).get(n);const r=t();return mt(this,pt).set(n,r),"object"==typeof r&&null!==r&&"then"in r?Promise.resolve(r).then(e=>(mt(this,pt).set(n,e),e)).catch(e=>{throw mt(this,pt).delete(n),e}):r}readSync(e,t){const n=[mt(this,ht),...e].join(":");if(mt(this,pt).has(n))return mt(this,pt).get(n);const r=t();return mt(this,pt).set(n,r),r}clear(e){const t=[...mt(this,ht),...e??[]].join(":");if(t)for(const e of mt(this,pt).keys())e.startsWith(t)&&mt(this,pt).delete(e);else mt(this,pt).clear()}scope(t){return new e({prefix:[...mt(this,ht),...Array.isArray(t)?t:[t]],cache:mt(this,pt)})}};class vt{constructor({network:e,base:t,cache:n=t?.cache??new wt}){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 kt(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 Et(e,t,n,r,s){const i=s&&"input"in s?s.input:n.value,a=s?.expected??e.expects??null,o=s?.received??kt(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 St(e,t){return Object.hasOwn(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}var xt=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function Ot(e,t){return{kind:"validation",type:"check",reference:Ot,async:!1,expects:null,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement(e.value)&&Et(this,"input",e,t),e}}}function Tt(e){return{kind:"validation",type:"integer",reference:Tt,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(e,t){return e.typed&&!this.requirement(e.value)&&Et(this,"integer",e,t),e}}}function It(e){return{kind:"transformation",type:"transform",reference:It,async:!1,operation:e,_run(e){return e.value=this.operation(e.value),e}}}function _t(e,t,n){return"function"==typeof e.default?e.default(t,n):e.default}function At(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function Ct(e,t){return{kind:"schema",type:"array",reference:Ct,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 Et(this,"type",e,t);return e}}}function jt(e){return{kind:"schema",type:"bigint",reference:jt,expects:"bigint",async:!1,message:e,_run(e,t){return"bigint"==typeof e.value?e.typed=!0:Et(this,"type",e,t),e}}}function Pt(e){return{kind:"schema",type:"boolean",reference:Pt,expects:"boolean",async:!1,message:e,_run(e,t){return"boolean"==typeof e.value?e.typed=!0:Et(this,"type",e,t),e}}}function Bt(e){return{kind:"schema",type:"lazy",reference:Bt,expects:"unknown",async:!1,getter:e,_run(e,t){return this.getter(e.value)._run(e,t)}}}function Nt(e,t){return{kind:"schema",type:"literal",reference:Nt,expects:kt(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:Et(this,"type",e,t),e}}}function Rt(e,...t){const n={kind:"schema",type:"nullable",reference:Rt,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(e,t){return null===e.value&&("default"in this&&(e.value=_t(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 $t(e,...t){const n={kind:"schema",type:"nullish",reference:$t,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=_t(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 Mt(e){return{kind:"schema",type:"number",reference:Mt,expects:"number",async:!1,message:e,_run(e,t){return"number"!=typeof e.value||isNaN(e.value)?Et(this,"type",e,t):e.typed=!0,e}}}function Dt(e,t){return{kind:"schema",type:"object",reference:Dt,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 Et(this,"type",e,t);return e}}}function Ut(e,...t){const n={kind:"schema",type:"optional",reference:Ut,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(e,t){return void 0===e.value&&("default"in this&&(e.value=_t(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 Vt(e,t,n){return{kind:"schema",type:"record",reference:Vt,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(St(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 Et(this,"type",e,t);return e}}}function Ft(e){return{kind:"schema",type:"string",reference:Ft,expects:"string",async:!1,message:e,_run(e,t){return"string"==typeof e.value?e.typed=!0:Et(this,"type",e,t),e}}}function Lt(e,t){return{kind:"schema",type:"tuple",reference:Lt,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 Et(this,"type",e,t);return e}}}function Kt(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function qt(e,t){return{kind:"schema",type:"union",reference:qt,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];Et(this,"type",e,t,{issues:Kt(r)}),e.typed=!0}else{if(1===s?.length)return s[0];Et(this,"type",e,t,{issues:Kt(s)})}return e}}}function zt(){return{kind:"schema",type:"unknown",reference:zt,expects:"unknown",async:!1,_run:e=>(e.typed=!0,e)}}function Zt(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 xt(r.issues);return r.value}function Wt(...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 Gt=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Ht=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i;const Jt=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,Yt=/^\d+$/,Xt=e=>{const t=e.split("/");if(t.length<2||t.length>3)return!1;const[n,r,s]=t;return!(void 0!==s&&!Yt.test(s))&&(!!function(e){return!(e.length>235)&&(e.includes("@")?Gt.test(e):Ht.test(e))}(n)&&(Jt.test(r)&&r.length<64))},Qt=e=>{const t=e.split(/::|<|>|,/);for(const e of t)if(e.includes("/")&&!Xt(e))return!1;return!0};function en(e){try{return 32===_e(e).length}catch{return!1}}const tn=32;function nn(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)===tn}function rn(e){return nn(e)}function sn(e){const[t,n]=e.split("::"),r=Xt(t),s=e.slice(t.length+n.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?Ke(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(e=>function(e){return e.includes("::")?sn(e):e}(e.trim())):[];return{address:r?t:on(t),module:n,name:i,typeParams:a}}function an(e){const{address:t,module:n,name:r,typeParams:s}="string"==typeof e?sn(e):e;return`${t}::${n}::${r}${s?.length>0?`<${s.map(e=>"string"==typeof e?e:an(e)).join(",")}>`:""}`}function on(e,t=!1){let n=e.toLowerCase();return!t&&n.startsWith("0x")&&(n=n.slice(2)),`0x${n.padStart(64,"0")}`}function cn(e,t=!1){return on(e,t)}function un(e){return Wt(qt(Object.entries(e).map(([e,t])=>Dt({[e]:t}))),It(e=>({...e,$kind:Object.keys(e)[0]})))}const dn=Wt(Ft(),It(e=>on(e)),Ot(nn)),ln=dn,hn=Ft(),pn=Wt(qt([Ft(),Wt(Mt(),Tt())]),Ot(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),fn=Dt({objectId:dn,version:pn,digest:Ft()}),gn=Wt(qt([Dt({GasCoin:Nt(!0)}),Dt({Input:Wt(Mt(),Tt()),type:Ut(Nt("pure"))}),Dt({Input:Wt(Mt(),Tt()),type:Ut(Nt("object"))}),Dt({Result:Wt(Mt(),Tt())}),Dt({NestedResult:Lt([Wt(Mt(),Tt()),Wt(Mt(),Tt())])})]),It(e=>({...e,$kind:Object.keys(e)[0]}))),mn=Dt({budget:Rt(pn),price:Rt(pn),owner:Rt(dn),payment:Rt(Ct(fn))}),yn=qt([Nt("address"),Nt("bool"),Nt("u8"),Nt("u16"),Nt("u32"),Nt("u64"),Nt("u128"),Nt("u256"),Dt({vector:Bt(()=>yn)}),Dt({datatype:Dt({package:Ft(),module:Ft(),type:Ft(),typeParameters:Ct(Bt(()=>yn))})}),Dt({typeParameter:Wt(Mt(),Tt())})]),bn=Dt({ref:Rt(qt([Nt("&"),Nt("&mut")])),body:yn}),wn=Dt({package:ln,module:Ft(),function:Ft(),typeArguments:Ct(Ft()),arguments:Ct(gn),_argumentTypes:Ut(Rt(Ct(bn)))}),vn=Dt({name:Ft(),inputs:Vt(Ft(),qt([gn,Ct(gn)])),data:Vt(Ft(),zt())}),kn=un({MoveCall:wn,TransferObjects:Dt({objects:Ct(gn),address:gn}),SplitCoins:Dt({coin:gn,amounts:Ct(gn)}),MergeCoins:Dt({destination:gn,sources:Ct(gn)}),Publish:Dt({modules:Ct(hn),dependencies:Ct(ln)}),MakeMoveVec:Dt({type:Rt(Ft()),elements:Ct(gn)}),Upgrade:Dt({modules:Ct(hn),dependencies:Ct(ln),package:ln,ticket:gn}),$Intent:vn}),En=un({ImmOrOwnedObject:fn,SharedObject:Dt({objectId:ln,initialSharedVersion:pn,mutable:Pt()}),Receiving:fn}),Sn=un({Object:En,Pure:Dt({bytes:hn}),UnresolvedPure:Dt({value:zt()}),UnresolvedObject:Dt({objectId:ln,version:Ut(Rt(pn)),digest:Ut(Rt(Ft())),initialSharedVersion:Ut(Rt(pn)),mutable:Ut(Rt(Pt()))})}),xn=un({Object:En,Pure:Dt({bytes:hn})}),On=un({None:Nt(!0),Epoch:pn}),Tn=Dt({version:Nt(2),sender:$t(dn),expiration:$t(On),gasData:mn,inputs:Ct(Sn),commands:Ct(kn)}),In={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=>Zt(gn,e)),address:Zt(gn,t)}}),SplitCoins:(e,t)=>({$kind:"SplitCoins",SplitCoins:{coin:Zt(gn,e),amounts:t.map(e=>Zt(gn,e))}}),MergeCoins:(e,t)=>({$kind:"MergeCoins",MergeCoins:{destination:Zt(gn,e),sources:t.map(e=>Zt(gn,e))}}),Publish:({modules:e,dependencies:t})=>({$kind:"Publish",Publish:{modules:e.map(e=>"string"==typeof e?e:je(new Uint8Array(e))),dependencies:t.map(e=>cn(e))}}),Upgrade:({modules:e,dependencies:t,package:n,ticket:r})=>({$kind:"Upgrade",Upgrade:{modules:e.map(e=>"string"==typeof e?e:je(new Uint8Array(e))),dependencies:t.map(e=>cn(e)),package:n,ticket:Zt(gn,r)}}),MakeMoveVec:({type:e,elements:t})=>({$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(e=>Zt(gn,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=>Zt(gn,e)):Zt(gn,t)])),data:n}})},_n=/^vector<(.+)>$/,An=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Cn{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(_n);if(n)return{vector:Cn.parseFromStr(n[1],t)};const r=e.match(An);if(r){return{struct:{address:t?on(r[1]):r[1],module:r[2],name:r[3],typeParams:void 0===r[5]?[]:Cn.parseStructTypeArgs(r[5],t)}}}throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,t=!1){return Ke(e).map(e=>Cn.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<${Cn.tagToString(e.vector)}>`;if("struct"in e){const t=e.struct,n=t.typeParams.map(Cn.tagToString).join(", ");return`${t.address}::${t.module}::${t.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}const jn=lt.bytes(tn).transform({validate:e=>{const t="string"==typeof e?e:Be(e);if(!t||!nn(on(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>"string"==typeof e?Pe(on(e)):e,output:e=>on(Be(e))}),Pn=lt.byteVector().transform({name:"ObjectDigest",input:e=>_e(e),output:e=>Ie(new Uint8Array(e)),validate:e=>{if(32!==_e(e).length)throw new Error("ObjectDigest must be 32 bytes")}}),Bn=lt.struct("SuiObjectRef",{objectId:jn,version:lt.u64(),digest:Pn}),Nn=lt.struct("SharedObjectRef",{objectId:jn,initialSharedVersion:lt.u64(),mutable:lt.bool()}),Rn=lt.enum("ObjectArg",{ImmOrOwnedObject:Bn,SharedObject:Nn,Receiving:Bn}),$n=lt.enum("Owner",{AddressOwner:jn,ObjectOwner:jn,Shared:lt.struct("Shared",{initialSharedVersion:lt.u64()}),Immutable:null,ConsensusAddressOwner:lt.struct("ConsensusAddressOwner",{owner:jn,startVersion:lt.u64()})}),Mn=lt.enum("CallArg",{Pure:lt.struct("Pure",{bytes:lt.byteVector().transform({input:e=>"string"==typeof e?Ae(e):e,output:e=>je(new Uint8Array(e))})}),Object:Rn}),Dn=lt.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:lt.lazy(()=>Dn),struct:lt.lazy(()=>Gn),u16:null,u32:null,u256:null}),Un=Dn.transform({input:e=>"string"==typeof e?Cn.parseFromStr(e,!0):e,output:e=>Cn.tagToString(e)}),Vn=lt.enum("Argument",{GasCoin:null,Input:lt.u16(),Result:lt.u16(),NestedResult:lt.tuple([lt.u16(),lt.u16()])}),Fn=lt.struct("ProgrammableMoveCall",{package:jn,module:lt.string(),function:lt.string(),typeArguments:lt.vector(Un),arguments:lt.vector(Vn)}),Ln=lt.enum("Command",{MoveCall:Fn,TransferObjects:lt.struct("TransferObjects",{objects:lt.vector(Vn),address:Vn}),SplitCoins:lt.struct("SplitCoins",{coin:Vn,amounts:lt.vector(Vn)}),MergeCoins:lt.struct("MergeCoins",{destination:Vn,sources:lt.vector(Vn)}),Publish:lt.struct("Publish",{modules:lt.vector(lt.byteVector().transform({input:e=>"string"==typeof e?Ae(e):e,output:e=>je(new Uint8Array(e))})),dependencies:lt.vector(jn)}),MakeMoveVec:lt.struct("MakeMoveVec",{type:(Kn=Un,lt.enum("Option",{None:null,Some:Kn})).transform({input:e=>null===e?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:lt.vector(Vn)}),Upgrade:lt.struct("Upgrade",{modules:lt.vector(lt.byteVector().transform({input:e=>"string"==typeof e?Ae(e):e,output:e=>je(new Uint8Array(e))})),dependencies:lt.vector(jn),package:jn,ticket:Vn})});var Kn;const qn=lt.struct("ProgrammableTransaction",{inputs:lt.vector(Mn),commands:lt.vector(Ln)}),zn=lt.enum("TransactionKind",{ProgrammableTransaction:qn,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),Zn=lt.enum("TransactionExpiration",{None:null,Epoch:lt.u64({name:"unsafe_u64",...Wn}).transform({input:e=>e,output:e=>Number(e)})});var Wn;const Gn=lt.struct("StructTag",{address:jn,module:lt.string(),name:lt.string(),typeParams:lt.vector(Dn)}),Hn=lt.struct("GasData",{payment:lt.vector(Bn),owner:jn,price:lt.u64(),budget:lt.u64()}),Jn=lt.struct("TransactionDataV1",{kind:zn,sender:jn,gasData:Hn,expiration:Zn}),Yn=lt.enum("TransactionData",{V1:Jn}),Xn=lt.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Qn=lt.enum("IntentVersion",{V0:null}),er=lt.enum("AppId",{Sui:null}),tr=lt.struct("Intent",{scope:Xn,version:Qn,appId:er});function nr(e){return lt.struct(`IntentMessage<${e.name}>`,{intent:tr,value:e})}const rr=lt.enum("CompressedSignature",{ED25519:lt.bytes(64),Secp256k1:lt.bytes(64),Secp256r1:lt.bytes(64),ZkLogin:lt.byteVector(),Passkey:lt.byteVector()}),sr=lt.enum("PublicKey",{ED25519:lt.bytes(32),Secp256k1:lt.bytes(33),Secp256r1:lt.bytes(33),ZkLogin:lt.byteVector(),Passkey:lt.bytes(33)}),ir=lt.struct("MultiSigPkMap",{pubKey:sr,weight:lt.u8()}),ar=lt.struct("MultiSigPublicKey",{pk_map:lt.vector(ir),threshold:lt.u16()}),or=lt.struct("MultiSig",{sigs:lt.vector(rr),bitmap:lt.u16(),multisig_pk:ar}),cr=lt.byteVector().transform({input:e=>"string"==typeof e?Ae(e):e,output:e=>je(new Uint8Array(e))}),ur=lt.struct("SenderSignedTransaction",{intentMessage:nr(Yn),txSignatures:lt.vector(cr)}),dr=lt.vector(ur,{name:"SenderSignedData"}),lr=lt.struct("PasskeyAuthenticator",{authenticatorData:lt.byteVector(),clientDataJson:lt.string(),userSignature:lt.byteVector()}),hr=lt.enum("PackageUpgradeError",{UnableToFetchPackage:lt.struct("UnableToFetchPackage",{packageId:jn}),NotAPackage:lt.struct("NotAPackage",{objectId:jn}),IncompatibleUpgrade:null,DigestDoesNotMatch:lt.struct("DigestDoesNotMatch",{digest:lt.byteVector()}),UnknownUpgradePolicy:lt.struct("UnknownUpgradePolicy",{policy:lt.u8()}),PackageIDDoesNotMatch:lt.struct("PackageIDDoesNotMatch",{packageId:jn,ticketId:jn})}),pr=lt.struct("ModuleId",{address:jn,name:lt.string()}),fr=lt.struct("MoveLocation",{module:pr,function:lt.u16(),instruction:lt.u16(),functionName:lt.option(lt.string())}),gr=lt.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:lt.struct("IndexOutOfBounds",{idx:lt.u16()}),SecondaryIndexOutOfBounds:lt.struct("SecondaryIndexOutOfBounds",{resultIdx:lt.u16(),secondaryIdx:lt.u16()}),InvalidResultArity:lt.struct("InvalidResultArity",{resultIdx:lt.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),mr=lt.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),yr=lt.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:lt.struct("MoveObjectTooBig",{objectSize:lt.u64(),maxObjectSize:lt.u64()}),MovePackageTooBig:lt.struct("MovePackageTooBig",{objectSize:lt.u64(),maxObjectSize:lt.u64()}),CircularObjectOwnership:lt.struct("CircularObjectOwnership",{object:jn}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:lt.option(fr),MoveAbort:lt.tuple([fr,lt.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:lt.struct("CommandArgumentError",{argIdx:lt.u16(),kind:gr}),TypeArgumentError:lt.struct("TypeArgumentError",{argumentIdx:lt.u16(),kind:mr}),UnusedValueWithoutDrop:lt.struct("UnusedValueWithoutDrop",{resultIdx:lt.u16(),secondaryIdx:lt.u16()}),InvalidPublicFunctionReturnType:lt.struct("InvalidPublicFunctionReturnType",{idx:lt.u16()}),InvalidTransferObject:null,EffectsTooLarge:lt.struct("EffectsTooLarge",{currentSize:lt.u64(),maxSize:lt.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:lt.struct("PackageUpgradeError",{upgradeError:hr}),WrittenObjectsTooLarge:lt.struct("WrittenObjectsTooLarge",{currentSize:lt.u64(),maxSize:lt.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:lt.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:lt.vector(jn)}),AddressDeniedForCoin:lt.struct("AddressDeniedForCoin",{address:jn,coinType:lt.string()}),CoinTypeGlobalPause:lt.struct("CoinTypeGlobalPause",{coinType:lt.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),br=lt.enum("ExecutionStatus",{Success:null,Failed:lt.struct("ExecutionFailed",{error:yr,command:lt.option(lt.u64())})}),wr=lt.struct("GasCostSummary",{computationCost:lt.u64(),storageCost:lt.u64(),storageRebate:lt.u64(),nonRefundableStorageFee:lt.u64()}),vr=lt.struct("TransactionEffectsV1",{status:br,executedEpoch:lt.u64(),gasUsed:wr,modifiedAtVersions:lt.vector(lt.tuple([jn,lt.u64()])),sharedObjects:lt.vector(Bn),transactionDigest:Pn,created:lt.vector(lt.tuple([Bn,$n])),mutated:lt.vector(lt.tuple([Bn,$n])),unwrapped:lt.vector(lt.tuple([Bn,$n])),deleted:lt.vector(Bn),unwrappedThenDeleted:lt.vector(Bn),wrapped:lt.vector(Bn),gasObject:lt.tuple([Bn,$n]),eventsDigest:lt.option(Pn),dependencies:lt.vector(Pn)}),kr=lt.tuple([lt.u64(),Pn]),Er=lt.enum("ObjectIn",{NotExist:null,Exist:lt.tuple([kr,$n])}),Sr=lt.enum("ObjectOut",{NotExist:null,ObjectWrite:lt.tuple([Pn,$n]),PackageWrite:kr}),xr=lt.enum("IDOperation",{None:null,Created:null,Deleted:null}),Or=lt.struct("EffectsObjectChange",{inputState:Er,outputState:Sr,idOperation:xr}),Tr=lt.enum("UnchangedSharedKind",{ReadOnlyRoot:kr,MutateDeleted:lt.u64(),ReadDeleted:lt.u64(),Cancelled:lt.u64(),PerEpochConfig:null}),Ir=lt.struct("TransactionEffectsV2",{status:br,executedEpoch:lt.u64(),gasUsed:wr,transactionDigest:Pn,gasObjectIndex:lt.option(lt.u32()),eventsDigest:lt.option(Pn),dependencies:lt.vector(Pn),lamportVersion:lt.u64(),changedObjects:lt.vector(lt.tuple([jn,Or])),unchangedSharedObjects:lt.vector(lt.tuple([jn,Tr])),auxDataDigest:lt.option(Pn)}),_r=lt.enum("TransactionEffects",{V1:vr,V2:Ir});function Ar(e){switch(e){case"u8":return lt.u8();case"u16":return lt.u16();case"u32":return lt.u32();case"u64":return lt.u64();case"u128":return lt.u128();case"u256":return lt.u256();case"bool":return lt.bool();case"string":return lt.string();case"id":case"address":return jn}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[e,n]=t.slice(1);return"vector"===e?lt.vector(Ar(n)):lt.option(Ar(n))}throw new Error(`Invalid Pure type name: ${e}`)}const Cr={...lt,U8:lt.u8(),U16:lt.u16(),U32:lt.u32(),U64:lt.u64(),U128:lt.u128(),U256:lt.u256(),ULEB128:lt.uleb128(),Bool:lt.bool(),String:lt.string(),Address:jn,AppId:er,Argument:Vn,CallArg:Mn,Command:Ln,CompressedSignature:rr,GasData:Hn,Intent:tr,IntentMessage:nr,IntentScope:Xn,IntentVersion:Qn,MultiSig:or,MultiSigPkMap:ir,MultiSigPublicKey:ar,ObjectArg:Rn,ObjectDigest:Pn,Owner:$n,PasskeyAuthenticator:lr,ProgrammableMoveCall:Fn,ProgrammableTransaction:qn,PublicKey:sr,SenderSignedData:dr,SenderSignedTransaction:ur,SharedObjectRef:Nn,StructTag:Gn,SuiObjectRef:Bn,TransactionData:Yn,TransactionDataV1:Jn,TransactionEffects:_r,TransactionExpiration:Zn,TransactionKind:zn,TypeTag:Un},jr=Dt({digest:Ft(),objectId:Ft(),version:qt([Wt(Mt(),Tt()),Ft(),jt()])}),Pr=un({ImmOrOwned:jr,Shared:Dt({objectId:ln,initialSharedVersion:pn,mutable:Pt()}),Receiving:jr}),Br=un({Object:Pr,Pure:Ct(Wt(Mt(),Tt()))}),Nr=qt([Dt({kind:Nt("Input"),index:Wt(Mt(),Tt()),value:zt(),type:Ut(Nt("object"))}),Dt({kind:Nt("Input"),index:Wt(Mt(),Tt()),value:zt(),type:Nt("pure")})]),Rr=qt([Dt({Epoch:Wt(Mt(),Tt())}),Dt({None:Rt(Nt(!0))})]),$r=Wt(qt([Mt(),Ft(),jt()]),Ot(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),Mr=qt([Dt({bool:Rt(Nt(!0))}),Dt({u8:Rt(Nt(!0))}),Dt({u64:Rt(Nt(!0))}),Dt({u128:Rt(Nt(!0))}),Dt({address:Rt(Nt(!0))}),Dt({signer:Rt(Nt(!0))}),Dt({vector:Bt(()=>Mr)}),Dt({struct:Bt(()=>Dr)}),Dt({u16:Rt(Nt(!0))}),Dt({u32:Rt(Nt(!0))}),Dt({u256:Rt(Nt(!0))})]),Dr=Dt({address:Ft(),module:Ft(),name:Ft(),typeParams:Ct(Mr)}),Ur=Dt({budget:Ut($r),price:Ut($r),payment:Ut(Ct(jr)),owner:Ut(Ft())}),Vr=qt([...[Nr,Dt({kind:Nt("GasCoin")}),Dt({kind:Nt("Result"),index:Wt(Mt(),Tt())}),Dt({kind:Nt("NestedResult"),index:Wt(Mt(),Tt()),resultIndex:Wt(Mt(),Tt())})]]),Fr=Dt({kind:Nt("MoveCall"),target:Wt(Ft(),Ot(e=>3===e.split("::").length)),typeArguments:Ct(Ft()),arguments:Ct(Vr)}),Lr=Dt({kind:Nt("TransferObjects"),objects:Ct(Vr),address:Vr}),Kr=Dt({kind:Nt("SplitCoins"),coin:Vr,amounts:Ct(Vr)}),qr=Dt({kind:Nt("MergeCoins"),destination:Vr,sources:Ct(Vr)}),zr=Dt({kind:Nt("MakeMoveVec"),type:qt([Dt({Some:Mr}),Dt({None:Rt(Nt(!0))})]),objects:Ct(Vr)}),Zr=qt([...[Fr,Lr,Kr,qr,Dt({kind:Nt("Publish"),modules:Ct(Ct(Wt(Mt(),Tt()))),dependencies:Ct(Ft())}),Dt({kind:Nt("Upgrade"),modules:Ct(Ct(Wt(Mt(),Tt()))),dependencies:Ct(Ft()),packageId:Ft(),ticket:Vr}),zr]]);function Wr(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(Ae(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:Cn.parseFromStr(e.MakeMoveVec.type)},objects:e.MakeMoveVec.elements.map(e=>Gr(e,t))};if(e.MergeCoins)return{kind:"MergeCoins",destination:Gr(e.MergeCoins.destination,t),sources:e.MergeCoins.sources.map(e=>Gr(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=>Gr(e,t))};if(e.Publish)return{kind:"Publish",modules:e.Publish.modules.map(e=>Array.from(Ae(e))),dependencies:e.Publish.dependencies};if(e.SplitCoins)return{kind:"SplitCoins",coin:Gr(e.SplitCoins.coin,t),amounts:e.SplitCoins.amounts.map(e=>Gr(e,t))};if(e.TransferObjects)return{kind:"TransferObjects",objects:e.TransferObjects.objects.map(e=>Gr(e,t)),address:Gr(e.TransferObjects.address,t)};if(e.Upgrade)return{kind:"Upgrade",modules:e.Upgrade.modules.map(e=>Array.from(Ae(e))),dependencies:e.Upgrade.dependencies,packageId:e.Upgrade.package,ticket:Gr(e.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(e)}`)})}}function Gr(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 Hr(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 Jr(e){return qt(Object.entries(e).map(([e,t])=>Dt({[e]:t})))}Dt({version:Nt(1),sender:Ut(Ft()),expiration:$t(Rr),gasConfig:Ur,inputs:Ct(Nr),transactions:Ct(Zr)});const Yr=Jr({GasCoin:Nt(!0),Input:Wt(Mt(),Tt()),Result:Wt(Mt(),Tt()),NestedResult:Lt([Wt(Mt(),Tt()),Wt(Mt(),Tt())])}),Xr=Dt({budget:Rt(pn),price:Rt(pn),owner:Rt(dn),payment:Rt(Ct(fn))}),Qr=Dt({package:ln,module:Ft(),function:Ft(),typeArguments:Ct(Ft()),arguments:Ct(Yr)}),es=Dt({name:Ft(),inputs:Vt(Ft(),qt([Yr,Ct(Yr)])),data:Vt(Ft(),zt())}),ts=Jr({MoveCall:Qr,TransferObjects:Dt({objects:Ct(Yr),address:Yr}),SplitCoins:Dt({coin:Yr,amounts:Ct(Yr)}),MergeCoins:Dt({destination:Yr,sources:Ct(Yr)}),Publish:Dt({modules:Ct(hn),dependencies:Ct(ln)}),MakeMoveVec:Dt({type:Rt(Ft()),elements:Ct(Yr)}),Upgrade:Dt({modules:Ct(hn),dependencies:Ct(ln),package:ln,ticket:Yr}),$Intent:es}),ns=Jr({ImmOrOwnedObject:fn,SharedObject:Dt({objectId:ln,initialSharedVersion:pn,mutable:Pt()}),Receiving:fn}),rs=Jr({Object:ns,Pure:Dt({bytes:hn}),UnresolvedPure:Dt({value:zt()}),UnresolvedObject:Dt({objectId:ln,version:Ut(Rt(pn)),digest:Ut(Rt(Ft())),initialSharedVersion:Ut(Rt(pn)),mutable:Ut(Rt(Pt()))})}),ss=Jr({None:Nt(!0),Epoch:pn}),is=Dt({version:Nt(2),sender:$t(dn),expiration:$t(ss),gasData:Xr,inputs:Ct(rs),commands:Ct(ts),digest:Ut(Rt(Ft()))});const as={Pure:function(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?je(e):e.toBase64()}}},ObjectRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:t,version:n,objectId:on(e)}}}),SharedObjectRef:({objectId:e,mutable:t,initialSharedVersion:n})=>({$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:t,initialSharedVersion:n,objectId:on(e)}}}),ReceivingRef:({objectId:e,digest:t,version:n})=>({$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:t,version:n,objectId:on(e)}}})};BigInt(1e9);const os=cn("0x6"),cs="0x2::sui::SUI";cn("0x5"),cn("0x8");const us="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ds(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ls(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function hs(e,...t){if(!ds(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 ps(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ls(e.outputLen),ls(e.blockLen)}function fs(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 gs(e,t){hs(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ms(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ys(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function bs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ws(e,t){return e<<32-t|e>>>t}function vs(e,t){return e<<t|e>>>32-t>>>0}const ks=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Es(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ss=ks?e=>e:e=>Es(e);const xs=ks?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Es(e[t]);return e},Os=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ts=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Is(e){if(hs(e),Os)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ts[e[n]];return t}const _s=48,As=57,Cs=65,js=70,Ps=97,Bs=102;function Ns(e){return e>=_s&&e<=As?e-_s:e>=Cs&&e<=js?e-(Cs-10):e>=Ps&&e<=Bs?e-(Ps-10):void 0}function Rs(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Os)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=Ns(e.charCodeAt(s)),i=Ns(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 $s(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Ms(e){return"string"==typeof e&&(e=$s(e)),hs(e),e}function Ds(e){return"string"==typeof e&&(e=$s(e)),hs(e),e}function Us(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];hs(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 Vs{}function Fs(e){const t=t=>e().update(Ms(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ls(e){const t=(t,n)=>e(n).update(Ms(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}function Ks(e=32){if(us&&"function"==typeof us.getRandomValues)return us.getRandomValues(new Uint8Array(e));if(us&&"function"==typeof us.randomBytes)return Uint8Array.from(us.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const qs=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 zs(e,t,n){return e&t^~e&n}function Zs(e,t,n){return e&t^e&n^t&n}class Ws extends Vs{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=bs(this.buffer)}update(e){fs(this),hs(e=Ms(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=bs(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){fs(this),gs(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,ys(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=bs(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 Gs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hs=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Js=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ys=BigInt(2**32-1),Xs=BigInt(32);function Qs(e,t=!1){return t?{h:Number(e&Ys),l:Number(e>>Xs&Ys)}:{h:0|Number(e>>Xs&Ys),l:0|Number(e&Ys)}}const ei=(e,t,n)=>e>>>n,ti=(e,t,n)=>e<<32-n|t>>>n,ni=(e,t,n)=>e>>>n|t<<32-n,ri=(e,t,n)=>e<<32-n|t>>>n,si=(e,t,n)=>e<<64-n|t>>>n-32,ii=(e,t,n)=>e>>>n-32|t<<64-n,ai=(e,t)=>t;function oi(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const ci=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ui=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,di=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),li=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,hi=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),pi=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,fi=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),gi=new Uint32Array(32);function mi(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=gi[2*e],u=gi[2*e+1],d=gi[2*t],l=gi[2*t+1],h=gi[2*n],p=gi[2*n+1],f=gi[2*r],g=gi[2*r+1],m=ci(c,d,a);var y;u=ui(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:ai(0,f),Dl:(y=g,y)}),({h:p,l:h}=oi(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:ni(l,d,24),Bl:ri(l,d,24)}),gi[2*e]=c,gi[2*e+1]=u,gi[2*t]=d,gi[2*t+1]=l,gi[2*n]=h,gi[2*n+1]=p,gi[2*r]=f,gi[2*r+1]=g}function yi(e,t,n,r,s,i){const a=s[i],o=s[i+1];let c=gi[2*e],u=gi[2*e+1],d=gi[2*t],l=gi[2*t+1],h=gi[2*n],p=gi[2*n+1],f=gi[2*r],g=gi[2*r+1],m=ci(c,d,a);u=ui(m,u,l,o),c=0|m,({Dh:g,Dl:f}={Dh:g^u,Dl:f^c}),({Dh:g,Dl:f}={Dh:ni(g,f,16),Dl:ri(g,f,16)}),({h:p,l:h}=oi(p,h,g,f)),({Bh:l,Bl:d}={Bh:l^p,Bl:d^h}),({Bh:l,Bl:d}={Bh:si(l,d,63),Bl:ii(l,d,63)}),gi[2*e]=c,gi[2*e+1]=u,gi[2*t]=d,gi[2*t+1]=l,gi[2*n]=h,gi[2*n+1]=p,gi[2*r]=f,gi[2*r+1]=g}class bi extends Vs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ls(e),ls(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ms(this.buffer)}update(e){fs(this),hs(e=Ms(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&&(xs(r),this.compress(r,0,!1),xs(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));xs(e);for(let n=0;o+t<s;n+=r.length,o+=t)this.length+=t,this.compress(e,n,!1);xs(e);continue}n.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c}return this}digestInto(e){fs(this),gs(e,this);const{pos:t,buffer32:n}=this;this.finished=!0,ys(this.buffer.subarray(t)),xs(n),this.compress(n,0,!0),xs(n);const r=ms(e);this.get().forEach((e,t)=>r[t]=Ss(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 wi extends bi{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|fi[0],this.v0h=0|fi[1],this.v1l=0|fi[2],this.v1h=0|fi[3],this.v2l=0|fi[4],this.v2h=0|fi[5],this.v3l=0|fi[6],this.v3h=0|fi[7],this.v4l=0|fi[8],this.v4h=0|fi[9],this.v5l=0|fi[10],this.v5h=0|fi[11],this.v6l=0|fi[12],this.v6h=0|fi[13],this.v7l=0|fi[14],this.v7h=0|fi[15],function(e,t={},n,r,s){if(ls(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=Ms(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==s){s=Ms(s);const e=ms(s);this.v4l^=Ss(e[0]),this.v4h^=Ss(e[1]),this.v5l^=Ss(e[2]),this.v5h^=Ss(e[3])}if(void 0!==r){r=Ms(r);const e=ms(r);this.v6l^=Ss(e[0]),this.v6h^=Ss(e[1]),this.v7l^=Ss(e[2]),this.v7h^=Ss(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)=>gi[t]=e),gi.set(fi,16);let{h:r,l:s}=Qs(BigInt(this.length));gi[24]=fi[8]^s,gi[25]=fi[9]^r,n&&(gi[28]=~gi[28],gi[29]=~gi[29]);let i=0;const a=qs;for(let n=0;n<12;n++)mi(0,4,8,12,e,t+2*a[i++]),yi(0,4,8,12,e,t+2*a[i++]),mi(1,5,9,13,e,t+2*a[i++]),yi(1,5,9,13,e,t+2*a[i++]),mi(2,6,10,14,e,t+2*a[i++]),yi(2,6,10,14,e,t+2*a[i++]),mi(3,7,11,15,e,t+2*a[i++]),yi(3,7,11,15,e,t+2*a[i++]),mi(0,5,10,15,e,t+2*a[i++]),yi(0,5,10,15,e,t+2*a[i++]),mi(1,6,11,12,e,t+2*a[i++]),yi(1,6,11,12,e,t+2*a[i++]),mi(2,7,8,13,e,t+2*a[i++]),yi(2,7,8,13,e,t+2*a[i++]),mi(3,4,9,14,e,t+2*a[i++]),yi(3,4,9,14,e,t+2*a[i++]);this.v0l^=gi[0]^gi[16],this.v0h^=gi[1]^gi[17],this.v1l^=gi[2]^gi[18],this.v1h^=gi[3]^gi[19],this.v2l^=gi[4]^gi[20],this.v2h^=gi[5]^gi[21],this.v3l^=gi[6]^gi[22],this.v3h^=gi[7]^gi[23],this.v4l^=gi[8]^gi[24],this.v4h^=gi[9]^gi[25],this.v5l^=gi[10]^gi[26],this.v5h^=gi[11]^gi[27],this.v6l^=gi[12]^gi[28],this.v6h^=gi[13]^gi[29],this.v7l^=gi[14]^gi[30],this.v7h^=gi[15]^gi[31],ys(gi)}destroy(){this.destroyed=!0,ys(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const vi=Ls(e=>new wi(e));function ki(e,t,n){const r=Cr.Address.serialize(e).toBytes(),s=Cr.TypeTag.serialize(t).toBytes(),i=Cr.u64().serialize(n.length).toBytes(),a=vi.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(r),a.update(i),a.update(n),a.update(s),`0x${Be(a.digest().slice(0,32))}`}function Ei(e){if("string"==typeof e)switch(e){case"address":return Cr.Address;case"bool":return Cr.Bool;case"u8":return Cr.U8;case"u16":return Cr.U16;case"u32":return Cr.U32;case"u64":return Cr.U64;case"u128":return Cr.U128;case"u256":return Cr.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if("u8"===e.vector)return Cr.byteVector().transform({input:e=>"string"==typeof e?(new TextEncoder).encode(e):e,output:e=>e});const t=Ei(e.vector);return t?Cr.vector(t):null}if("datatype"in e){const t=on(e.datatype.package);if(t===on("0x1")){if("ascii"===e.datatype.module&&"String"===e.datatype.type)return Cr.String;if("string"===e.datatype.module&&"String"===e.datatype.type)return Cr.String;if("option"===e.datatype.module&&"Option"===e.datatype.type){const t=Ei(e.datatype.typeParameters[0]);return t?Cr.vector(t):null}}if(t===on("0x2")&&"object"===e.datatype.module&&"ID"===e.datatype.type)return Cr.Address}return null}function Si(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:Si(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(Si)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const xi=5e10;function Oi(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:Si(e.Reference)}:"object"==typeof e&&"MutableReference"in e?{ref:"&mut",body:Si(e.MutableReference)}:{ref:null,body:Si(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&&on(t.package)===on("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=Ei(e.body);if(o)return s.type="pure",void(n[n.indexOf(i)]=as.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=>cn(e.UnresolvedObject.objectId)))],s=r.length?Ne(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=on(n.UnresolvedObject.objectId),i=u.get(s);n.UnresolvedObject.initialSharedVersion??i?.initialSharedVersion?r=as.SharedObjectRef({objectId:s,initialSharedVersion:n.UnresolvedObject.initialSharedVersion||i?.initialSharedVersion,mutable:n.UnresolvedObject.mutable||Ti(e,t)}):Ii(e,t)&&(r=as.ReceivingRef({objectId:s,digest:n.UnresolvedObject.digest??i?.digest,version:n.UnresolvedObject.version??i?.version})),e.inputs[e.inputs.indexOf(n)]=r??as.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(xi),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:cs})).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=>Zt(fn,e))}}(t,e)),await r()}}function Ti(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 Ii(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 _i(e,t){return!!e.inputs.some(e=>e.UnresolvedObject||e.UnresolvedPure)||!(t.onlyTransactionKind||e.gasConfig.price&&e.gasConfig.budget&&e.gasConfig.payment)}async function Ai(e,t,n){if(function(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(t=>{ji(t,Cr.U64,e)});break;case"TransferObjects":ji(t.TransferObjects.address,Cr.Address,e)}}(e),!_i(e,t))return await Ci(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()??Oi(r))(e,t,async()=>{await Ci(e),await n()})}function Ci(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 ji(e,t,n){if("Input"!==e.$kind)return;const r=n.inputs[e.Input];"UnresolvedPure"===r.$kind&&(n.inputs[e.Input]=as.Pure(t.serialize(r.UnresolvedPure.value)))}function Pi(e){function t(t,n){if("string"==typeof t)return e(Ar(t).serialize(n));if(t instanceof Uint8Array||rt(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(Cr.U8.serialize(t)),t.u16=t=>e(Cr.U16.serialize(t)),t.u32=t=>e(Cr.U32.serialize(t)),t.u64=t=>e(Cr.U64.serialize(t)),t.u128=t=>e(Cr.U128.serialize(t)),t.u256=t=>e(Cr.U256.serialize(t)),t.bool=t=>e(Cr.Bool.serialize(t)),t.string=t=>e(Cr.String.serialize(t)),t.address=t=>e(Cr.Address.serialize(t)),t.id=t.address,t.vector=(t,n)=>e(Cr.vector(Ar(t)).serialize(n)),t.option=(t,n)=>e(Cr.option(Ar(t)).serialize(n)),t}function Bi(e){return"string"==typeof e?on(e):e.Object?e.Object.ImmOrOwnedObject?on(e.Object.ImmOrOwnedObject.objectId):e.Object.Receiving?on(e.Object.Receiving.objectId):on(e.Object.SharedObject.objectId):e.UnresolvedObject?on(e.UnresolvedObject.objectId):void 0}function Ni(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 Ri(e){return on(e).replace("0x","")}class $i{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=Cr.TransactionKind.parse(e).ProgrammableTransaction;if(!t)throw new Error("Unable to deserialize from bytes.");return $i.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=Cr.TransactionData.parse(e),n=t?.V1,r=n.kind.ProgrammableTransaction;if(!n||!r)throw new Error("Unable to deserialize from bytes.");return $i.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 $i(Zt(Tn,e)):new $i(Zt(Tn,function(e){return Zt(Tn,{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(At(Br,e.value)){const t=Zt(Br,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:je(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?Cn.tagToString(e.type.Some):null,elements:e.objects.map(e=>Hr(e))}};case"MergeCoins":return{MergeCoins:{destination:Hr(e.destination),sources:e.sources.map(e=>Hr(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=>Hr(e))}}}case"Publish":return{Publish:{modules:e.modules.map(e=>je(Uint8Array.from(e))),dependencies:e.dependencies}};case"SplitCoins":return{SplitCoins:{coin:Hr(e.coin),amounts:e.amounts.map(e=>Hr(e))}};case"TransferObjects":return{TransferObjects:{objects:e.objects.map(e=>Hr(e)),address:Hr(e.address)}};case"Upgrade":return{Upgrade:{modules:e.modules.map(e=>je(Uint8Array.from(e))),dependencies:e.dependencies,package:e.packageId,ticket:Hr(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),vi(r,{dkLen:32})}("TransactionData",e);return Ie(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 Cr.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:Ri(o),expiration:a||{None:!0},gasData:{payment:c.payment,owner:Ri(this.gasData.owner??o),price:BigInt(c.price),budget:BigInt(c.budget)},kind:{ProgrammableTransaction:{inputs:r,commands:s}}};return Cr.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 Zt(gn,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=Bi(r);let i=-1;if(void 0!==s&&(i=this.inputs.findIndex(e=>Bi(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]);Ni(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 $i.getDigestFromBytes(e)}snapshot(){return Zt(Tn,this)}shallowClone(){return new $i({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(on(e.objectId)!==on(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(on(e.objectId)!==on(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 Mi,Di,Ui,Vi,Fi,Li,Ki,qi,zi,Zi,Wi=e=>{throw TypeError(e)},Gi=(e,t,n)=>t.has(e)||Wi("Cannot "+n),Hi=(e,t,n)=>(Gi(e,t,"read from private field"),n?n.call(e):t.get(e)),Ji=(e,t,n)=>t.has(e)?Wi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Yi=(e,t,n,r)=>(Gi(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Xi=(e,t,n)=>(Gi(e,t,"access private method"),n);const Qi={"Mvr-Source":`@mysten/sui@${b}`};class ea{constructor({cache:e,url:t,pageSize:n=50,overrides:r}){Ji(this,Fi),Ji(this,Mi),Ji(this,Di),Ji(this,Ui),Ji(this,Vi),Yi(this,Mi,e),Yi(this,Di,t),Yi(this,Ui,n),Yi(this,Vi,{packages:r?.packages,types:r?.types}),function(e){if(e?.packages)for(const[t,n]of Object.entries(e.packages)){if(!Xt(t))throw new Error(`Invalid package name: ${t}`);if(!nn(on(n)))throw new Error(`Invalid package ID: ${n}`)}if(e?.types)for(const[t,n]of Object.entries(e.types)){if(sn(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(!nn(sn(n).address))throw new Error(`Invalid type: ${n}`)}}(Hi(this,Vi))}async resolvePackage({package:e}){if(!ra(e))return{package:e};return{package:await Hi(this,Fi,Li).load(e)}}async resolveType({type:e}){if(!ra(e))return{type:e};const t=[...ta(e)],n=await Hi(this,Fi,Ki).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:na(e,r)}}async resolve({types:e=[],packages:t=[]}){const n=new Set;for(const t of e??[])ta(t,n);const r=[...n],[s,i]=await Promise.all([r.length>0?Hi(this,Fi,Ki).loadMany(r):[],t.length>0?Hi(this,Fi,Li).loadMany(t):[]]),a={...Hi(this,Vi)?.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=na(t,a);o[t]={type:e}}const c={};for(const[e,n]of(t??[]).entries()){const t=Hi(this,Vi)?.packages?.[n]??i[e];if(t instanceof Error)throw t;c[n]={package:t}}return{types:o,packages:c}}}function ta(e,t=new Set){if("string"==typeof e&&!ra(e))return t;const n=sa(e)?e:sn(e);ra(n.address)&&t.add(`${n.address}::${n.module}::${n.name}`);for(const e of n.typeParams)ta(e,t);return t}function na(e,t){const n=sa(e)?e:sn(e),r=`${n.address}::${n.module}::${n.name}`,s=t[r];return an({...n,address:s?s.split("::")[0]:n.address,typeParams:n.typeParams.map(e=>na(e,t))})}function ra(e){return e.includes("/")||e.includes("@")||e.includes(".sui")}function sa(e){return"object"==typeof e&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function ia(e){const t=new Set;for(const n of e)if(ra(n)){if(!Qt(n))throw new Error(`Invalid type with names: ${n}`);t.add(n)}return t}Mi=new WeakMap,Di=new WeakMap,Ui=new WeakMap,Vi=new WeakMap,Fi=new WeakSet,Li=function(){return Hi(this,Mi).readSync(["#mvrPackageDataLoader",Hi(this,Di)??""],()=>{const e=new Re(async e=>{if(!Hi(this,Di))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Xi(this,Fi,qi).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve package: ${e}`))}),t=Hi(this,Vi)?.packages;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},Ki=function(){return Hi(this,Mi).readSync(["#mvrTypeDataLoader",Hi(this,Di)??""],()=>{const e=new Re(async e=>{if(!Hi(this,Di))throw new Error(`MVR Api URL is not set for the current client (resolving ${e.join(", ")})`);const t=await Xi(this,Fi,zi).call(this,e);return e.map(e=>t[e]??new Error(`Failed to resolve type: ${e}`))}),t=Hi(this,Vi)?.types;if(t)for(const[n,r]of Object.entries(t))e.prime(n,r);return e})},qi=async function(e){if(0===e.length)return{};const t=Ne(e,Hi(this,Ui)),n={};return await Promise.all(t.map(async e=>{const t=await Xi(this,Fi,Zi).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},zi=async function(e){if(0===e.length)return{};const t=Ne(e,Hi(this,Ui)),n={};return await Promise.all(t.map(async e=>{const t=await Xi(this,Fi,Zi).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},Zi=async function(e,t){if(!Hi(this,Di))throw new Error("MVR Api URL is not set for the current client");const n=await fetch(`${Hi(this,Di)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...Qi},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 aa=new WeakMap,oa=e=>{let t;if(e){const n=e.overrides??{packages:{},types:{}};aa.has(n)||aa.set(n,new wt),t=new ea({cache:aa.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&&ia([r.MakeMoveVec.type]).forEach(e=>{n.add(e)});break;case"MoveCall":const e=r.MoveCall,s=e.package.split("::")[0];if(ra(s)){if(!Xt(s))throw new Error(`Invalid package name: ${s}`);t.add(s)}ia(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(!ra(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(ra(s)&&!t.packages[s])throw new Error(`No address found for package: ${s}`);ra(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(ra(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 ca,ua,da,la,ha,pa,fa,ga,ma,ya,ba,wa,va,ka,Ea,Sa,xa,Oa,Ta,Ia=e=>{throw TypeError(e)},_a=(e,t,n)=>t.has(e)||Ia("Cannot "+n),Aa=(e,t,n)=>(_a(e,t,"read from private field"),n?n.call(e):t.get(e)),Ca=(e,t,n)=>t.has(e)?Ia("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ja=(e,t,n,r)=>(_a(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Pa=(e,t,n)=>(_a(e,t,"access private method"),n);function Ba(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 Na=Symbol.for("@mysten/transaction");function Ra(e){return!!e&&"object"==typeof e&&!0===e[Na]}const $a={buildPlugins:new Map,serializationPlugins:new Map},Ma=Symbol.for("@mysten/transaction/registry");function Da(){try{const e=globalThis;return e[Ma]||(e[Ma]=$a),e[Ma]}catch{return $a}}const Ua=class e{constructor(){Ca(this,ya),Ca(this,ca),Ca(this,ua),Ca(this,da,new Map),Ca(this,la,[]),Ca(this,ha,[]),Ca(this,pa,new Set),Ca(this,fa,new Set),Ca(this,ga,new Map),Ca(this,ma),this.object=function(e){function t(t){return e(t)}return t.system=e=>{const n=e?.mutable;return t(void 0!==n?as.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},t.clock=()=>t(as.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&&At(gn,e))return e;const t=Bi(e),n=Aa(this,ma).inputs.find(e=>t===Bi(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:Aa(this,ma).inputs.indexOf(n),type:"object"}:Pa(this,ya,va).call(this,"object","string"==typeof e?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:on(e)}}:e)});const e=Da();ja(this,ma,new $i),ja(this,ua,[...e.buildPlugins.values()]),ja(this,ca,[...e.serializationPlugins.values()])}static fromKind(t){const n=new e;return ja(n,ma,$i.fromKindBytes("string"==typeof t?Ae(t):t)),ja(n,la,Aa(n,ma).inputs.slice()),ja(n,ha,Aa(n,ma).commands.slice()),ja(n,pa,new Set(Aa(n,ha).map((e,t)=>t))),n}static from(t){const n=new e;return Ra(t)?ja(n,ma,$i.restore(t.getData())):"string"==typeof t&&t.startsWith("{")?ja(n,ma,$i.restore(JSON.parse(t))):ja(n,ma,$i.fromBytes("string"==typeof t?Ae(t):t)),ja(n,la,Aa(n,ma).inputs.slice()),ja(n,ha,Aa(n,ma).commands.slice()),ja(n,pa,new Set(Aa(n,ha).map((e,t)=>t))),n}static registerGlobalSerializationPlugin(e,t){Da().serializationPlugins.set(e,t??e)}static unregisterGlobalSerializationPlugin(e){Da().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,t){Da().buildPlugins.set(e,t??e)}static unregisterGlobalBuildPlugin(e){Da().buildPlugins.delete(e)}addSerializationPlugin(e){Aa(this,ca).push(e)}addBuildPlugin(e){Aa(this,ua).push(e)}addIntentResolver(e,t){if(Aa(this,da).has(e)&&Aa(this,da).get(e)!==t)throw new Error(`Intent resolver for ${e} already exists`);Aa(this,da).set(e,t)}setSender(e){Aa(this,ma).sender=e}setSenderIfNotSet(e){Aa(this,ma).sender||(Aa(this,ma).sender=e)}setExpiration(e){Aa(this,ma).expiration=e?Zt(On,e):null}setGasPrice(e){Aa(this,ma).gasConfig.price=String(e)}setGasBudget(e){Aa(this,ma).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){null==Aa(this,ma).gasData.budget&&(Aa(this,ma).gasConfig.budget=String(e))}setGasOwner(e){Aa(this,ma).gasConfig.owner=e}setGasPayment(e){Aa(this,ma).gasConfig.payment=e.map(e=>Zt(fn,e))}get blockData(){return Wr(Aa(this,ma).snapshot())}getData(){return Aa(this,ma).snapshot()}get[Na](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:Pi(e=>rt(e)?Pa(this,ya,va).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):Pa(this,ya,va).call(this,"pure",At(xn,e)?Zt(xn,e):e instanceof Uint8Array?as.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(as.ObjectRef(...e))}receivingRef(...e){return this.object(as.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(as.SharedObjectRef(...e))}add(e){if("function"==typeof e){if(Aa(this,ga).has(e))return Aa(this,ga).get(e);const t=Pa(this,ya,ba).call(this),n=e(t);if(!n||"object"!=typeof n||!("then"in n))return ja(this,pa,Aa(t,pa)),Aa(this,ga).set(e,n),n;const r=Pa(this,ya,wa).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Aa(this,ma).commands.length,result:null}}});Aa(this,fa).add(Promise.resolve(n).then(e=>{r.$Intent.data.result=e}));const s=Ba(()=>r.$Intent.data.resultIndex);return Aa(this,ga).set(e,s),s}return Pa(this,ya,wa).call(this,e),Ba(Aa(this,ma).commands.length-1)}splitCoins(e,t){const n=In.SplitCoins("string"==typeof e?this.object(e):Pa(this,ya,Ea).call(this,e),t.map(e=>"number"==typeof e||"bigint"==typeof e||"string"==typeof e?this.pure.u64(e):Pa(this,ya,ka).call(this,e)));return Pa(this,ya,wa).call(this,n),Ba(Aa(this,ma).commands.length-1,t.length)}mergeCoins(e,t){return this.add(In.MergeCoins(this.object(e),t.map(e=>this.object(e))))}publish({modules:e,dependencies:t}){return this.add(In.Publish({modules:e,dependencies:t}))}upgrade({modules:e,dependencies:t,package:n,ticket:r}){return this.add(In.Upgrade({modules:e,dependencies:t,package:n,ticket:this.object(r)}))}moveCall({arguments:e,...t}){return this.add(In.MoveCall({...t,arguments:e?.map(e=>Pa(this,ya,ka).call(this,e))}))}transferObjects(e,t){return this.add(In.TransferObjects(e.map(e=>this.object(e)),"string"==typeof t?this.pure.address(t):Pa(this,ya,ka).call(this,t)))}makeMoveVec({type:e,elements:t}){return this.add(In.MakeMoveVec({type:e,elements:t.map(e=>this.object(e))}))}serialize(){return JSON.stringify(Wr(Aa(this,ma).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const t=this.isFullyResolved();return JSON.stringify(Zt(is,t?{...Aa(this,ma).snapshot(),digest:Aa(this,ma).getDigest()}:Aa(this,ma).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!!Aa(this,ma).sender&&(!(Aa(this,fa).size>0)&&(!Aa(this,ma).commands.some(e=>e.$Intent)&&!_i(Aa(this,ma),{})))}async build(e={}){return await this.prepareForSerialization(e),await Pa(this,ya,Sa).call(this,e),Aa(this,ma).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await Pa(this,ya,Sa).call(this,e),Aa(this,ma).getDigest()}async prepareForSerialization(e){await Pa(this,ya,Oa).call(this),Pa(this,ya,Ta).call(this);const t=new Set;for(const e of Aa(this,ma).commands)e.$Intent&&t.add(e.$Intent.name);const n=[...Aa(this,ca)];for(const r of t)if(!e.supportedIntents?.includes(r)){if(!Aa(this,da).has(r))throw new Error(`Missing intent resolver for ${r}`);n.push(Aa(this,da).get(r))}n.push(oa()),await Pa(this,ya,xa).call(this,n,e)}};ca=new WeakMap,ua=new WeakMap,da=new WeakMap,la=new WeakMap,ha=new WeakMap,pa=new WeakMap,fa=new WeakMap,ga=new WeakMap,ma=new WeakMap,ya=new WeakSet,ba=function(){const e=new Ua;return ja(e,ma,Aa(this,ma)),ja(e,ca,Aa(this,ca)),ja(e,ua,Aa(this,ua)),ja(e,da,Aa(this,da)),ja(e,fa,Aa(this,fa)),ja(e,pa,new Set(Aa(this,pa))),ja(e,ga,Aa(this,ga)),Aa(this,la).push(Aa(e,la)),Aa(this,ha).push(Aa(e,ha)),e},wa=function(e){const t=Aa(this,ma).commands.length;return Aa(this,ha).push(e),Aa(this,pa).add(t),Aa(this,ma).commands.push(e),Aa(this,ma).mapCommandArguments(t,e=>{if("Result"===e.$kind&&!Aa(this,pa).has(e.Result))throw new Error(`Result { Result: ${e.Result} } is not available to use in the current transaction`);if("NestedResult"===e.$kind&&!Aa(this,pa).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>=Aa(this,ma).inputs.length)throw new Error(`Input { Input: ${e.Input} } references an input that does not exist in the current transaction`);return e}),e},va=function(e,t){return Aa(this,la).push(t),Aa(this,ma).addInput(e,t)},ka=function(e){return rt(e)?this.pure(e):Pa(this,ya,Ea).call(this,e)},Ea=function(e){if("function"==typeof e){const t=this.add(e);return"function"==typeof t?Pa(this,ya,Ea).call(this,t):Zt(gn,t)}return Zt(gn,e)},Sa=async function(e){if(!e.onlyTransactionKind&&!Aa(this,ma).sender)throw new Error("Missing transaction sender");await Pa(this,ya,xa).call(this,[...Aa(this,ua),Ai],e)},xa=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(Aa(this,ma),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{ja(this,la,Aa(this,ma).inputs.slice()),ja(this,ha,Aa(this,ma).commands.slice())}},Oa=async function(){for(;Aa(this,fa).size>0;){const e=Promise.all(Aa(this,fa));Aa(this,fa).clear(),Aa(this,fa).add(e),await e,Aa(this,fa).delete(e)}},Ta=function(){const e=Aa(this,ma).commands,t=Aa(this,ma).inputs,n=Aa(this,ha).flat(1/0),r=Aa(this,la).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}Aa(this,ma).commands=s,Aa(this,ma).inputs=r,ja(this,ha,s),ja(this,la,r),ja(this,pa,new Set(s.map((e,t)=>t))),Aa(this,ma).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 Va=Ua;const Fa={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class La extends vt{constructor(e){super(e),this.core=this,this.mvr=new ea({cache:this.cache.scope("core.mvr"),url:e.mvr?.url??Fa[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=Cn.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=ki(e.parentId,t,e.name.bcs),{objects:[r]}=await this.getObjects({objectIds:[n],signal:e.signal});if(r instanceof Error)throw r;const s=sn(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]:an(s.typeParams[0]),bcs:e.name.bcs},value:{type:"string"==typeof s.typeParams[1]?s.typeParams[1]:an(s.typeParams[1]),bcs:i.slice(tn+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 Ka extends Error{}class qa extends Ka{constructor(e,t){super(t),this.code=e}static fromResponse(e,t){switch(e.code){case"notExists":return new qa(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new qa(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new qa(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new qa(e.code,`Display error: ${e.error}`);default:return new qa(e.code,"Unknown error while loading object"+(t?` ${t}`:""))}}}function za(e){return{...$i.fromBytes(e).snapshot(),bcs:e}}function Za(e){const t=Cr.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 Wa,Ga=e=>{throw TypeError(e)},Ha=(e,t,n)=>t.has(e)||Ga("Cannot "+n),Ja=(e,t,n)=>(Ha(e,t,"read from private field"),n?n.call(e):t.get(e));class Ya extends La{constructor({jsonRpcClient:e,mvr:t}){var n,r,s;super({network:e.network,base:e,mvr:t}),n=this,(r=Wa).has(n)?Ga("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(n):r.set(n,s),((e,t,n,r)=>{Ha(e,t,"write to private field"),r?r.call(e,n):t.set(e,n)})(this,Wa,e)}async getObjects(e){const t=Ne(e.objectIds,50),n=[];for(const r of t){const t=await Ja(this,Wa).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(qa.fromResponse(s.error,r[e])):n.push(Xa(s.data))}return{objects:n}}async getOwnedObjects(e){const t=await Ja(this,Wa).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 qa.fromResponse(e.error);return Xa(e.data)}),hasNextPage:t.hasNextPage,cursor:t.nextCursor??null}}async getCoins(e){const t=await Ja(this,Wa).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(ro.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 Ja(this,Wa).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:t.coinType,balance:t.totalBalance}}}async getAllBalances(e){return{balances:(await Ja(this,Wa).getAllBalances({owner:e.address,signal:e.signal})).map(e=>({coinType:e.coinType,balance:e.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){return{transaction:to(await Ja(this,Wa).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:to(await Ja(this,Wa).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=Va.from(e.transaction),n=await Ja(this,Wa).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:Qa(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:Qa(e.owner),outputState:"ObjectWrite",outputVersion:e.version,outputDigest:e.digest,outputOwner:Qa(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:Qa(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:Qa(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:za(e.transaction),balanceChanges:n.balanceChanges.map(e=>({coinType:e.coinType,address:eo(e.owner),amount:e.amount}))}}}async getReferenceGasPrice(e){const t=await Ja(this,Wa).getReferenceGasPrice({signal:e?.signal});return{referenceGasPrice:String(t)}}async getDynamicFields(e){const t=await Ja(this,Wa).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:Ae(e.bcsName)}})),hasNextPage:t.hasNextPage,cursor:t.nextCursor}}async verifyZkLoginSignature(e){const t=await Ja(this,Wa).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 Ja(this,Wa).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return Oi(Ja(this,Wa))}async getMoveFunction(e){const t=await Ja(this,Wa).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:on(e.packageId),moduleName:e.moduleName,name:e.name,visibility:ao(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=>so(e)),returns:t.return.map(e=>so(e))}}}}function Xa(e){return{id:e.objectId,version:e.version,digest:e.digest,type:e.type,content:Promise.resolve("moveObject"===e.bcs?.dataType?Ae(e.bcs.bcsBytes):new Uint8Array),owner:Qa(e.owner),previousTransaction:e.previousTransaction??null}}function Qa(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 eo(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 to(e){const t=Cr.SenderSignedData.parse(Ae(e.rawTransaction))[0],n={};e.objectChanges?.forEach(e=>{"published"!==e.type&&(n[e.objectId]=e.objectType)});const r=Cr.TransactionData.serialize(t.intentMessage.value).toBytes(),s=$i.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:Za(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(n),transaction:{...s,bcs:r},signatures:t.txSignatures,balanceChanges:e.balanceChanges?.map(e=>({coinType:e.coinType,address:eo(e.owner),amount:e.amount}))??[]}}Wa=new WeakMap;const no=Cr.struct("Balance",{value:Cr.u64()}),ro=Cr.struct("Coin",{id:Cr.Address,balance:no});function so(e){if("string"!=typeof e){if("Reference"in e)return{reference:"immutable",body:io(e.Reference)};if("MutableReference"in e)return{reference:"mutable",body:io(e.MutableReference)}}return{reference:null,body:io(e)}}function io(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:io(e.Vector)};if("Struct"in e)return{$kind:"datatype",datatype:{typeName:`${on(e.Struct.address)}::${e.Struct.module}::${e.Struct.name}`,typeParameters:e.Struct.typeArguments.map(e=>io(e))}};if("TypeParameter"in e)return{$kind:"typeParameter",index:e.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}function ao(e){switch(e){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const oo=Symbol.for("@mysten/SuiClient");class co extends vt{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new Y({url:e.url}),this.core=new Ya({jsonRpcClient:this,mvr:e.mvr})}get[oo](){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||!nn(on(t)))throw new Error("Invalid Sui address");return e&&ra(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||!nn(on(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||!nn(on(e)))throw new Error("Invalid Sui address");return t&&ra(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||!nn(on(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&&ra(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&&ra(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&&Xt(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&&Xt(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&&Xt(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&&Xt(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&&Xt(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||!nn(on(e.owner)))throw new Error("Invalid Sui address");const t=e.filter?{...e.filter}:void 0;return t&&"MoveModule"in t&&Xt(t.MoveModule.package)?t.MoveModule={module:t.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveModule.package})).package}:t&&"StructType"in t&&ra(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||!rn(cn(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||!rn(cn(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&&Xt(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(!en(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(!en(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:je(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||!nn(on(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||!rn(cn(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&&ra(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Xt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Xt(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(Ra(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),t=je(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=je(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:je(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!rn(cn(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 Be(_e(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(!Gt.test(n))throw new Error(`Invalid SuiNS name ${e}`);const[t,s]=n.split("@");r=[...t?t.split("."):[],s]}else{if(!Ht.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 uo 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 lo(e){}function ho(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=lo,onError:n=lo,onRetry:r=lo,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 uo(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:n(new uo(`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 po 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(go(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(go(this),t)}}function fo(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(fo).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${fo(e.cause)}`:e.message:`${e}`}function go(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var mo,yo,bo,wo,vo,ko,Eo,So,xo,Oo,To,Io,_o,Ao,Co,jo,Po,Bo,No,Ro,$o,Mo,Do,Uo,Vo,Fo=e=>{throw TypeError(e)},Lo=(e,t,n)=>t.has(e)||Fo("Cannot "+n),Ko=(e,t,n)=>(Lo(e,t,"read from private field"),n?n.call(e):t.get(e)),qo=(e,t,n)=>t.has(e)?Fo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),zo=(e,t,n,r)=>(Lo(e,t,"write to private field"),t.set(e,n),n),Zo=(e,t,n)=>(Lo(e,t,"access private method"),n);class Wo extends EventTarget{constructor(e,t){var n,r;super(),qo(this,Ao),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,qo(this,mo),qo(this,yo),qo(this,bo),qo(this,wo),qo(this,vo),qo(this,ko),qo(this,Eo),qo(this,So,null),qo(this,xo),qo(this,Oo),qo(this,To,null),qo(this,Io,null),qo(this,_o,null),qo(this,jo,async e=>{var t;Ko(this,Oo).reset();const{body:n,redirected:r,status:s,headers:i}=e;if(204===s)return Zo(this,Ao,$o).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(zo(this,bo,r?new URL(e.url):void 0),200!==s)return void Zo(this,Ao,$o).call(this,`Non-200 status code (${s})`,s);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void Zo(this,Ao,$o).call(this,'Invalid content type, expected "text/event-stream"',s);if(Ko(this,mo)===this.CLOSED)return;zo(this,mo,this.OPEN);const a=new Event("open");if(null==(t=Ko(this,_o))||t.call(this,a),this.dispatchEvent(a),"object"!=typeof n||!n||!("getReader"in n))return Zo(this,Ao,$o).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&&Ko(this,Oo).feed(o.decode(t,{stream:!e})),e&&(u=!1,Ko(this,Oo).reset(),Zo(this,Ao,Mo).call(this))}while(u)}),qo(this,Po,e=>{zo(this,xo,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&Zo(this,Ao,Mo).call(this,fo(e))}),qo(this,No,e=>{"string"==typeof e.id&&zo(this,So,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Ko(this,bo)?Ko(this,bo).origin:Ko(this,yo).origin,lastEventId:e.id||""});Ko(this,Io)&&(!e.event||"message"===e.event)&&Ko(this,Io).call(this,t),this.dispatchEvent(t)}),qo(this,Ro,e=>{zo(this,ko,e)}),qo(this,Do,()=>{zo(this,Eo,void 0),Ko(this,mo)===this.CONNECTING&&Zo(this,Ao,Co).call(this)});try{if(e instanceof URL)zo(this,yo,e);else{if("string"!=typeof e)throw new Error("Invalid URL");zo(this,yo,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")}zo(this,Oo,ho({onEvent:Ko(this,No),onRetry:Ko(this,Ro)})),zo(this,mo,this.CONNECTING),zo(this,ko,3e3),zo(this,vo,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),zo(this,wo,null!=(r=null==t?void 0:t.withCredentials)&&r),Zo(this,Ao,Co).call(this)}get readyState(){return Ko(this,mo)}get url(){return Ko(this,yo).href}get withCredentials(){return Ko(this,wo)}get onerror(){return Ko(this,To)}set onerror(e){zo(this,To,e)}get onmessage(){return Ko(this,Io)}set onmessage(e){zo(this,Io,e)}get onopen(){return Ko(this,_o)}set onopen(e){zo(this,_o,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(){Ko(this,Eo)&&clearTimeout(Ko(this,Eo)),Ko(this,mo)!==this.CLOSED&&(Ko(this,xo)&&Ko(this,xo).abort(),zo(this,mo,this.CLOSED),zo(this,xo,void 0))}}function Go(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Ho(e){const t={};for(const n of Object.keys(e)){const r=Go(n),s=e[n];t[r]=s}return t}mo=new WeakMap,yo=new WeakMap,bo=new WeakMap,wo=new WeakMap,vo=new WeakMap,ko=new WeakMap,Eo=new WeakMap,So=new WeakMap,xo=new WeakMap,Oo=new WeakMap,To=new WeakMap,Io=new WeakMap,_o=new WeakMap,Ao=new WeakSet,Co=function(){zo(this,mo,this.CONNECTING),zo(this,xo,new AbortController),Ko(this,vo)(Ko(this,yo),Zo(this,Ao,Bo).call(this)).then(Ko(this,jo)).catch(Ko(this,Po))},jo=new WeakMap,Po=new WeakMap,Bo=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ko(this,So)?{"Last-Event-ID":Ko(this,So)}:void 0},cache:"no-store",signal:null==(e=Ko(this,xo))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},No=new WeakMap,Ro=new WeakMap,$o=function(e,t){var n;Ko(this,mo)!==this.CLOSED&&zo(this,mo,this.CLOSED);const r=new po("error",{code:t,message:e});null==(n=Ko(this,To))||n.call(this,r),this.dispatchEvent(r)},Mo=function(e,t){var n;if(Ko(this,mo)===this.CLOSED)return;zo(this,mo,this.CONNECTING);const r=new po("error",{code:t,message:e});null==(n=Ko(this,To))||n.call(this,r),this.dispatchEvent(r),zo(this,Eo,setTimeout(Ko(this,Do),Ko(this,ko)))},Do=new WeakMap,Wo.CONNECTING=0,Wo.OPEN=1,Wo.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}(Uo||(Uo={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Vo||(Vo={}));const Jo=Uo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yo=e=>{switch(typeof e){case"undefined":return Jo.undefined;case"string":return Jo.string;case"number":return Number.isNaN(e)?Jo.nan:Jo.number;case"boolean":return Jo.boolean;case"function":return Jo.function;case"bigint":return Jo.bigint;case"symbol":return Jo.symbol;case"object":return Array.isArray(e)?Jo.array:null===e?Jo.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Jo.promise:"undefined"!=typeof Map&&e instanceof Map?Jo.map:"undefined"!=typeof Set&&e instanceof Set?Jo.set:"undefined"!=typeof Date&&e instanceof Date?Jo.date:Jo.object;default:return Jo.unknown}},Xo=Uo.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 Qo 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 Qo))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Uo.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()}}Qo.create=e=>new Qo(e);var ec=(e,t)=>{let n;switch(e.code){case Xo.invalid_type:n=e.received===Jo.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Xo.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Uo.jsonStringifyReplacer)}`;break;case Xo.unrecognized_keys:n=`Unrecognized key(s) in object: ${Uo.joinValues(e.keys,", ")}`;break;case Xo.invalid_union:n="Invalid input";break;case Xo.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Uo.joinValues(e.options)}`;break;case Xo.invalid_enum_value:n=`Invalid enum value. Expected ${Uo.joinValues(e.options)}, received '${e.received}'`;break;case Xo.invalid_arguments:n="Invalid function arguments";break;case Xo.invalid_return_type:n="Invalid function return type";break;case Xo.invalid_date:n="Invalid date";break;case Xo.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}"`:Uo.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Xo.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 Xo.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 Xo.custom:n="Invalid input";break;case Xo.invalid_intersection_types:n="Intersection results could not be merged";break;case Xo.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Xo.not_finite:n="Number must be finite";break;default:n=t.defaultError,Uo.assertNever(e)}return{message:n}};let tc=ec;function nc(e,t){const n=tc,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===ec?void 0:ec].filter(e=>!!e)});e.common.issues.push(r)}class rc{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 sc;"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 rc.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 sc;if("aborted"===s.status)return sc;"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 sc=Object.freeze({status:"aborted"}),ic=e=>({status:"dirty",value:e}),ac=e=>({status:"valid",value:e}),oc=e=>"aborted"===e.status,cc=e=>"dirty"===e.status,uc=e=>"valid"===e.status,dc=e=>"undefined"!=typeof Promise&&e instanceof Promise;var lc;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(lc||(lc={}));class hc{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 pc=(e,t)=>{if(uc(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 Qo(e.common.issues);return this._error=t,this._error}}};function fc(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 gc{get description(){return this._def.description}_getType(e){return Yo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rc,ctx:{common:e.parent.common,data:e.data,parsedType:Yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(dc(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:Yo(e)},r=this._parseSync({data:e,path:n.path,parent:n});return pc(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yo(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return uc(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=>uc(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:Yo(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(dc(r)?r:Promise.resolve(r));return pc(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:Xo.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 fu({schema:this,typeName:Su.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 gu.create(this,this._def)}nullable(){return mu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xc.create(this)}promise(){return pu.create(this,this._def)}or(e){return tu.create([this,e],this._def)}and(e){return ru.create(this,e,this._def)}transform(e){return new fu({...fc(this._def),schema:this,typeName:Su.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new yu({...fc(this._def),innerType:this,defaultValue:t,typeName:Su.ZodDefault})}brand(){return new vu({typeName:Su.ZodBranded,type:this,...fc(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new bu({...fc(this._def),innerType:this,catchValue:t,typeName:Su.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ku.create(this,e)}readonly(){return Eu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const mc=/^c[^\s-]{8,}$/i,yc=/^[0-9a-z]+$/,bc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wc=/^[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,vc=/^[a-z0-9_-]{21}$/i,kc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ec=/^[-+]?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)?)??$/,Sc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let xc;const Oc=/^(?:(?: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])$/,Tc=/^(?:(?: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])$/,Ic=/^(([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]))$/,_c=/^(([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])$/,Ac=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jc="((\\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])))",Pc=new RegExp(`^${jc}$`);function Bc(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 Nc(e){return new RegExp(`^${Bc(e)}$`)}function Rc(e){let t=`${jc}T${Bc(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 $c(e,t){return!("v4"!==t&&t||!Oc.test(e))||!("v6"!==t&&t||!Ic.test(e))}function Mc(e,t){if(!kc.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 Dc(e,t){return!("v4"!==t&&t||!Tc.test(e))||!("v6"!==t&&t||!_c.test(e))}class Uc extends gc{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Jo.string){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.string,received:t.parsedType}),sc}const t=new rc;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),nc(n,{code:Xo.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),nc(n,{code:Xo.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?nc(n,{code:Xo.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):i&&nc(n,{code:Xo.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)Sc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"email",code:Xo.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)xc||(xc=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"emoji",code:Xo.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)wc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"uuid",code:Xo.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)vc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"nanoid",code:Xo.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)mc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"cuid",code:Xo.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)yc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"cuid2",code:Xo.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)bc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"ulid",code:Xo.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),nc(n,{validation:"url",code:Xo.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),nc(n,{validation:"regex",code:Xo.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),nc(n,{code:Xo.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),nc(n,{code:Xo.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),nc(n,{code:Xo.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){Rc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{code:Xo.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Pc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{code:Xo.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Nc(r).test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{code:Xo.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?Ec.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"duration",code:Xo.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?$c(e.data,r.version)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"ip",code:Xo.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Mc(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"jwt",code:Xo.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Dc(e.data,r.version)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"cidr",code:Xo.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Ac.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"base64",code:Xo.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?Cc.test(e.data)||(n=this._getOrReturnCtx(e,n),nc(n,{validation:"base64url",code:Xo.invalid_string,message:r.message}),t.dirty()):Uo.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Xo.invalid_string,...lc.errToObj(n)})}_addCheck(e){return new Uc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...lc.errToObj(e)})}url(e){return this._addCheck({kind:"url",...lc.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...lc.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...lc.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...lc.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...lc.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...lc.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...lc.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...lc.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...lc.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...lc.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...lc.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...lc.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,...lc.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,...lc.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...lc.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...lc.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...lc.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...lc.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...lc.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...lc.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...lc.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...lc.errToObj(t)})}nonempty(e){return this.min(1,lc.errToObj(e))}trim(){return new Uc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Uc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Uc({...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 Vc(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}Uc.create=e=>new Uc({checks:[],typeName:Su.ZodString,coerce:e?.coerce??!1,...fc(e)});class Fc extends gc{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)!==Jo.number){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.number,received:t.parsedType}),sc}let t;const n=new rc;for(const r of this._def.checks)if("int"===r.kind)Uo.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),nc(t,{code:Xo.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),nc(t,{code:Xo.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),nc(t,{code:Xo.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==Vc(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),nc(t,{code:Xo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),nc(t,{code:Xo.not_finite,message:r.message}),n.dirty()):Uo.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,lc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,lc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,lc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,lc.toString(t))}setLimit(e,t,n,r){return new Fc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:lc.toString(r)}]})}_addCheck(e){return new Fc({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:lc.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:lc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:lc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:lc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:lc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:lc.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:lc.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:lc.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:lc.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&&Uo.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)}}Fc.create=e=>new Fc({checks:[],typeName:Su.ZodNumber,coerce:e?.coerce||!1,...fc(e)});class Lc extends gc{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)!==Jo.bigint)return this._getInvalidInput(e);let t;const n=new rc;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),nc(t,{code:Xo.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),nc(t,{code:Xo.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),nc(t,{code:Xo.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Uo.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.bigint,received:t.parsedType}),sc}gte(e,t){return this.setLimit("min",e,!0,lc.toString(t))}gt(e,t){return this.setLimit("min",e,!1,lc.toString(t))}lte(e,t){return this.setLimit("max",e,!0,lc.toString(t))}lt(e,t){return this.setLimit("max",e,!1,lc.toString(t))}setLimit(e,t,n,r){return new Lc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:lc.toString(r)}]})}_addCheck(e){return new Lc({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:lc.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:lc.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:lc.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:lc.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:lc.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}}Lc.create=e=>new Lc({checks:[],typeName:Su.ZodBigInt,coerce:e?.coerce??!1,...fc(e)});class Kc extends gc{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Jo.boolean){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.boolean,received:t.parsedType}),sc}return ac(e.data)}}Kc.create=e=>new Kc({typeName:Su.ZodBoolean,coerce:e?.coerce||!1,...fc(e)});class qc extends gc{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Jo.date){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.date,received:t.parsedType}),sc}if(Number.isNaN(e.data.getTime())){return nc(this._getOrReturnCtx(e),{code:Xo.invalid_date}),sc}const t=new rc;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),nc(n,{code:Xo.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),nc(n,{code:Xo.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Uo.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new qc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:lc.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:lc.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}}qc.create=e=>new qc({checks:[],coerce:e?.coerce||!1,typeName:Su.ZodDate,...fc(e)});class zc extends gc{_parse(e){if(this._getType(e)!==Jo.symbol){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.symbol,received:t.parsedType}),sc}return ac(e.data)}}zc.create=e=>new zc({typeName:Su.ZodSymbol,...fc(e)});class Zc extends gc{_parse(e){if(this._getType(e)!==Jo.undefined){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.undefined,received:t.parsedType}),sc}return ac(e.data)}}Zc.create=e=>new Zc({typeName:Su.ZodUndefined,...fc(e)});class Wc extends gc{_parse(e){if(this._getType(e)!==Jo.null){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.null,received:t.parsedType}),sc}return ac(e.data)}}Wc.create=e=>new Wc({typeName:Su.ZodNull,...fc(e)});class Gc extends gc{constructor(){super(...arguments),this._any=!0}_parse(e){return ac(e.data)}}Gc.create=e=>new Gc({typeName:Su.ZodAny,...fc(e)});class Hc extends gc{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ac(e.data)}}Hc.create=e=>new Hc({typeName:Su.ZodUnknown,...fc(e)});class Jc extends gc{_parse(e){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.never,received:t.parsedType}),sc}}Jc.create=e=>new Jc({typeName:Su.ZodNever,...fc(e)});class Yc extends gc{_parse(e){if(this._getType(e)!==Jo.undefined){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.void,received:t.parsedType}),sc}return ac(e.data)}}Yc.create=e=>new Yc({typeName:Su.ZodVoid,...fc(e)});class Xc extends gc{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==Jo.array)return nc(t,{code:Xo.invalid_type,expected:Jo.array,received:t.parsedType}),sc;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(nc(t,{code:e?Xo.too_big:Xo.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&&(nc(t,{code:Xo.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&&(nc(t,{code:Xo.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 hc(t,e,t.path,n)))).then(e=>rc.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new hc(t,e,t.path,n)));return rc.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new Xc({...this._def,minLength:{value:e,message:lc.toString(t)}})}max(e,t){return new Xc({...this._def,maxLength:{value:e,message:lc.toString(t)}})}length(e,t){return new Xc({...this._def,exactLength:{value:e,message:lc.toString(t)}})}nonempty(e){return this.min(1,e)}}function Qc(e){if(e instanceof eu){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=gu.create(Qc(r))}return new eu({...e._def,shape:()=>t})}return e instanceof Xc?new Xc({...e._def,type:Qc(e.element)}):e instanceof gu?gu.create(Qc(e.unwrap())):e instanceof mu?mu.create(Qc(e.unwrap())):e instanceof su?su.create(e.items.map(e=>Qc(e))):e}Xc.create=(e,t)=>new Xc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Su.ZodArray,...fc(t)});class eu extends gc{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=Uo.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Jo.object){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.object,received:t.parsedType}),sc}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Jc&&"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 hc(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Jc){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&&(nc(n,{code:Xo.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 hc(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=>rc.mergeObjectSync(t,e)):rc.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return lc.errToObj,new eu({...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:lc.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new eu({...this._def,unknownKeys:"strip"})}passthrough(){return new eu({...this._def,unknownKeys:"passthrough"})}extend(e){return new eu({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new eu({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Su.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new eu({...this._def,catchall:e})}pick(e){const t={};for(const n of Uo.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new eu({...this._def,shape:()=>t})}omit(e){const t={};for(const n of Uo.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new eu({...this._def,shape:()=>t})}deepPartial(){return Qc(this)}partial(e){const t={};for(const n of Uo.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new eu({...this._def,shape:()=>t})}required(e){const t={};for(const n of Uo.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof gu;)e=e._def.innerType;t[n]=e}return new eu({...this._def,shape:()=>t})}keyof(){return du(Uo.objectKeys(this.shape))}}eu.create=(e,t)=>new eu({shape:()=>e,unknownKeys:"strip",catchall:Jc.create(),typeName:Su.ZodObject,...fc(t)}),eu.strictCreate=(e,t)=>new eu({shape:()=>e,unknownKeys:"strict",catchall:Jc.create(),typeName:Su.ZodObject,...fc(t)}),eu.lazycreate=(e,t)=>new eu({shape:e,unknownKeys:"strip",catchall:Jc.create(),typeName:Su.ZodObject,...fc(t)});class tu extends gc{_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 Qo(e.ctx.common.issues));return nc(t,{code:Xo.invalid_union,unionErrors:n}),sc});{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 Qo(e));return nc(t,{code:Xo.invalid_union,unionErrors:s}),sc}}get options(){return this._def.options}}function nu(e,t){const n=Yo(e),r=Yo(t);if(e===t)return{valid:!0,data:e};if(n===Jo.object&&r===Jo.object){const n=Uo.objectKeys(t),r=Uo.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=nu(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===Jo.array&&r===Jo.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=nu(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===Jo.date&&r===Jo.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}tu.create=(e,t)=>new tu({options:e,typeName:Su.ZodUnion,...fc(t)});class ru extends gc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(oc(e)||oc(r))return sc;const s=nu(e.value,r.value);return s.valid?((cc(e)||cc(r))&&t.dirty(),{status:t.value,value:s.data}):(nc(n,{code:Xo.invalid_intersection_types}),sc)};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}))}}ru.create=(e,t,n)=>new ru({left:e,right:t,typeName:Su.ZodIntersection,...fc(n)});class su extends gc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Jo.array)return nc(n,{code:Xo.invalid_type,expected:Jo.array,received:n.parsedType}),sc;if(n.data.length<this._def.items.length)return nc(n,{code:Xo.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sc;!this._def.rest&&n.data.length>this._def.items.length&&(nc(n,{code:Xo.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 hc(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>rc.mergeArray(t,e)):rc.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new su({...this._def,rest:e})}}su.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new su({items:e,typeName:Su.ZodTuple,rest:null,...fc(t)})};class iu extends gc{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!==Jo.object)return nc(n,{code:Xo.invalid_type,expected:Jo.object,received:n.parsedType}),sc;const r=[],s=this._def.keyType,i=this._def.valueType;for(const e in n.data)r.push({key:s._parse(new hc(n,e,n.path,e)),value:i._parse(new hc(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?rc.mergeObjectAsync(t,r):rc.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new iu(t instanceof gc?{keyType:e,valueType:t,typeName:Su.ZodRecord,...fc(n)}:{keyType:Uc.create(),valueType:e,typeName:Su.ZodRecord,...fc(t)})}}class au extends gc{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!==Jo.map)return nc(n,{code:Xo.invalid_type,expected:Jo.map,received:n.parsedType}),sc;const r=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([e,t],i)=>({key:r._parse(new hc(n,e,n.path,[i,"key"])),value:s._parse(new hc(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 sc;"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 sc;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}au.create=(e,t,n)=>new au({valueType:t,keyType:e,typeName:Su.ZodMap,...fc(n)});class ou extends gc{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Jo.set)return nc(n,{code:Xo.invalid_type,expected:Jo.set,received:n.parsedType}),sc;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(nc(n,{code:Xo.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&&(nc(n,{code:Xo.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 sc;"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 hc(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new ou({...this._def,minSize:{value:e,message:lc.toString(t)}})}max(e,t){return new ou({...this._def,maxSize:{value:e,message:lc.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ou.create=(e,t)=>new ou({valueType:e,minSize:null,maxSize:null,typeName:Su.ZodSet,...fc(t)});class cu extends gc{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})}}cu.create=(e,t)=>new cu({getter:e,typeName:Su.ZodLazy,...fc(t)});class uu extends gc{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return nc(t,{received:t.data,code:Xo.invalid_literal,expected:this._def.value}),sc}return{status:"valid",value:e.data}}get value(){return this._def.value}}function du(e,t){return new lu({values:e,typeName:Su.ZodEnum,...fc(t)})}uu.create=(e,t)=>new uu({value:e,typeName:Su.ZodLiteral,...fc(t)});class lu extends gc{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return nc(t,{expected:Uo.joinValues(n),received:t.parsedType,code:Xo.invalid_type}),sc}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 nc(t,{received:t.data,code:Xo.invalid_enum_value,options:n}),sc}return ac(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 lu.create(e,{...this._def,...t})}exclude(e,t=this._def){return lu.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}lu.create=du;class hu extends gc{_parse(e){const t=Uo.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Jo.string&&n.parsedType!==Jo.number){const e=Uo.objectValues(t);return nc(n,{expected:Uo.joinValues(e),received:n.parsedType,code:Xo.invalid_type}),sc}if(this._cache||(this._cache=new Set(Uo.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Uo.objectValues(t);return nc(n,{received:n.data,code:Xo.invalid_enum_value,options:e}),sc}return ac(e.data)}get enum(){return this._def.values}}hu.create=(e,t)=>new hu({values:e,typeName:Su.ZodNativeEnum,...fc(t)});class pu extends gc{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Jo.promise&&!1===t.common.async)return nc(t,{code:Xo.invalid_type,expected:Jo.promise,received:t.parsedType}),sc;const n=t.parsedType===Jo.promise?t.data:Promise.resolve(t.data);return ac(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}pu.create=(e,t)=>new pu({type:e,typeName:Su.ZodPromise,...fc(t)});class fu extends gc{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Su.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=>{nc(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 sc;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?sc:"dirty"===r.status||"dirty"===t.value?ic(r.value):r});{if("aborted"===t.value)return sc;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?sc:"dirty"===r.status||"dirty"===t.value?ic(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?sc:("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?sc:("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(!uc(e))return sc;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=>uc(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):sc)}Uo.assertNever(r)}}fu.create=(e,t,n)=>new fu({schema:e,typeName:Su.ZodEffects,effect:t,...fc(n)}),fu.createWithPreprocess=(e,t,n)=>new fu({schema:t,effect:{type:"preprocess",transform:e},typeName:Su.ZodEffects,...fc(n)});class gu extends gc{_parse(e){return this._getType(e)===Jo.undefined?ac(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gu.create=(e,t)=>new gu({innerType:e,typeName:Su.ZodOptional,...fc(t)});class mu extends gc{_parse(e){return this._getType(e)===Jo.null?ac(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}mu.create=(e,t)=>new mu({innerType:e,typeName:Su.ZodNullable,...fc(t)});class yu extends gc{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Jo.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}yu.create=(e,t)=>new yu({innerType:e,typeName:Su.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...fc(t)});class bu extends gc{_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 dc(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Qo(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Qo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}bu.create=(e,t)=>new bu({innerType:e,typeName:Su.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...fc(t)});class wu extends gc{_parse(e){if(this._getType(e)!==Jo.nan){const t=this._getOrReturnCtx(e);return nc(t,{code:Xo.invalid_type,expected:Jo.nan,received:t.parsedType}),sc}return{status:"valid",value:e.data}}}wu.create=e=>new wu({typeName:Su.ZodNaN,...fc(e)});class vu extends gc{_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 ku extends gc{_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?sc:"dirty"===e.status?(t.dirty(),ic(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?sc:"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 ku({in:e,out:t,typeName:Su.ZodPipeline})}}class Eu extends gc{_parse(e){const t=this._def.innerType._parse(e),n=e=>(uc(e)&&(e.value=Object.freeze(e.value)),e);return dc(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Su;Eu.create=(e,t)=>new Eu({innerType:e,typeName:Su.ZodReadonly,...fc(t)}),eu.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"}(Su||(Su={}));const xu=Uc.create,Ou=Fc.create;wu.create,Lc.create;const Tu=Kc.create;qc.create,zc.create,Zc.create,Wc.create,Gc.create,Hc.create,Jc.create;const Iu=Yc.create,_u=Xc.create,Au=eu.create;eu.strictCreate,tu.create,ru.create,su.create;const Cu=iu.create;au.create,ou.create,cu.create,uu.create;const ju=lu.create;function Pu(e,t){let n={...e};for(let e of t)delete n[e];return n}hu.create,pu.create,fu.create,gu.create,mu.create,fu.createWithPreprocess;var Bu=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;function Nu(e){let t=e.url,n=e.params;return n&&(t=t.replace(Bu,(e,t)=>t in n?`${n[t]}`:e)),t}function Ru(e,t,n){return e.find(e=>e.method===t&&e.path===n)}var $u=class extends Error{constructor(e,t,n,r){super(e),this.config=t,this.data=n,this.cause=r}},Mu={name:"form-data",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new $u("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 Du={name:"form-url",request:async(e,t)=>{if("object"!=typeof t.data||Array.isArray(t.data))throw new $u("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 Uu(e,t){return{request:async(n,r)=>({...r,headers:{...r.headers,[e]:t}})}}function Vu(e){return[!0,"response","all"].includes(e)}function Fu(e){return[!0,"request","all"].includes(e)}var Lu=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 Ku(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 qu=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||{}}Ku(this.api),this.options={validate:!0,transform:!0,sendDefaults:!1,...r},this.options.axiosInstance?this.axiosInstance=this.options.axiosInstance:this.axiosInstance=h.default.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:Fu(e)?async(e,r)=>{let s=Ru(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=Fu(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 $u(`Zodios: Invalid ${i} parameter '${t}'`,r,a,e.error);u&&c[i](t,e.data)}}return a}:void 0,response:Vu(e)?async(e,n,r)=>{var s,i,a,o;let c=Ru(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 $u(`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);Vu(t)&&(r.data=e.data)}return r}:void 0}}(this.options))}initPlugins(){this.endpointPlugins.set("any-any",new Lu("any","any")),this.api.forEach(e=>{let t=new Lu(e.method,e.path);switch(e.requestFormat){case"binary":t.use(Uu("Content-Type","application/octet-stream"));break;case"form-data":t.use(Mu);break;case"form-url":t.use(Du);break;case"text":t.use(Uu("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({...Pu(t,["params","queries"]),url:Nu(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 zu=ju(["crypto","fx","equity","metal","rates","crypto_redemption_rate","commodities","crypto_index","crypto_nav"]),Zu=zu.nullish(),Wu=xu(),Gu=Au({attributes:Cu(xu()),id:Wu}).passthrough(),Hu=xu(),Ju=ju(["hex","base64"]),Yu=Au({data:_u(xu()),encoding:Ju}).passthrough(),Xu=Au({conf:xu(),expo:Ou().int(),price:xu(),publish_time:Ou().int()}).passthrough(),Qu=Au({prev_publish_time:Ou().int().nullable(),proof_available_time:Ou().int().nullable(),slot:Ou().int().gte(0).nullable()}).partial().passthrough(),ed=Au({ema_price:Xu,id:Wu,metadata:Qu,price:Xu}).passthrough(),td=Au({binary:Yu,parsed:_u(ed).nullish()}).passthrough(),nd=Au({cap:Ou().int().gte(0),publisher:xu()}).passthrough(),rd=Au({publisher_stake_caps:_u(nd)}).passthrough(),sd=Au({binary:Yu,parsed:_u(rd).nullish()}).passthrough(),id=Au({down_slots_ratio:xu(),end_timestamp:Ou().int(),id:Wu,start_timestamp:Ou().int(),twap:Xu}).passthrough(),ad=Au({binary:Yu,parsed:_u(id).nullish()}).passthrough(),od={AssetType:zu,asset_type:Zu,RpcPriceIdentifier:Wu,PriceFeedMetadata:Gu,PriceIdInput:Hu,EncodingType:Ju,BinaryUpdate:Yu,RpcPrice:Xu,RpcPriceFeedMetadataV2:Qu,ParsedPriceUpdate:ed,PriceUpdate:td,ParsedPublisherStakeCap:nd,ParsedPublisherStakeCapsUpdate:rd,LatestPublisherStakeCapsUpdateDataResponse:sd,ParsedPriceFeedTwap:id,TwapsResponse:ad};var cd;new qu((Ku(cd=[{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:xu().nullish()},{name:"asset_type",type:"Query",schema:Zu}],response:_u(Gu)},{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:Ou().int()},{name:"ids[]",type:"Query",schema:_u(Hu)},{name:"encoding",type:"Query",schema:ju(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Tu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Tu().optional()}],response:td,errors:[{status:404,description:"Price ids not found",schema:Iu()}]},{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:_u(Hu)},{name:"encoding",type:"Query",schema:ju(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Tu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Tu().optional()}],response:td,errors:[{status:404,description:"Price ids not found",schema:Iu()}]},{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:_u(Hu)},{name:"encoding",type:"Query",schema:ju(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Tu().optional()},{name:"allow_unordered",type:"Query",schema:Tu().optional()},{name:"benchmarks_only",type:"Query",schema:Tu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Tu().optional()}],response:td,errors:[{status:404,description:"Price ids not found",schema:Iu()}]},{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:ju(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Tu().optional()}],response:sd},{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:Ou().int().gte(0)},{name:"ids[]",type:"Query",schema:_u(Hu)},{name:"encoding",type:"Query",schema:ju(["hex","base64"]).optional()},{name:"parsed",type:"Query",schema:Tu().optional()},{name:"ignore_invalid_price_ids",type:"Query",schema:Tu().optional()}],response:ad,errors:[{status:404,description:"Price ids not found",schema:Iu()}]}]),cd));class ud{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=Ho(t);this.appendUrlSearchParams(n,e)}return await this.httpRequest(n.toString(),od.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(),od.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=Ho(t);this.appendUrlSearchParams(r,e)}return this.httpRequest(r.toString(),od.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=Ho(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),od.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=Ho(t);this.appendUrlSearchParams(n,e)}return new Wo(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=Ho(n);this.appendUrlSearchParams(s,e)}return this.httpRequest(s.toString(),od.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 dd extends ud{async getPriceFeedsUpdateData(e){return(await this.getLatestPriceUpdates(e,{encoding:"base64",parsed:!1})).binary.data.map(e=>n.Buffer.from(e,"base64"))}}const ld=16384;class hd{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(Cr.vector(Cr.U8).serialize([...s],{maxSize:ld}).toBytes()),t.object(os)]});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(Cr.vector(Cr.U8).serialize([...t[0]],{maxSize:ld}).toBytes()),s[0],e.object(os)]});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(os)]}),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(Cr.vector(Cr.U8).serialize([...t[0]],{maxSize:ld}).toBytes()),s[0],e.object(os)]})}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:r}=await this.getPriceTableInfo(),s=await this.provider.getDynamicFieldObject({parentId:e,name:{type:`${r}::price_identifier::PriceIdentifier`,value:{bytes:[...n.Buffer.from(t,"hex")]}}});if(!s.data?.content)return;if("moveObject"!==s.data.content.dataType)throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(t,s.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 pd={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"},fd='{"onboardingUrl":"dipcoin.io"}',gd={USDC:6,SUI:9,DEFAULT:18},md={mainnet:{wormholeStateId:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pythStateId:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",priceServiceUrl:"https://hermes.pyth.network/"},testnet:{wormholeStateId:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",pythStateId:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",priceServiceUrl:"https://hermes-beta.pyth.network"}};class yd{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((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}`);r&&c.push("-d",r);const u=s.spawn("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())}}var bd,wd;exports.OrderSide=void 0,(bd=exports.OrderSide||(exports.OrderSide={})).BUY="BUY",bd.SELL="SELL",exports.OrderType=void 0,(wd=exports.OrderType||(exports.OrderType={})).MARKET="MARKET",wd.LIMIT="LIMIT";const vd=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]),kd=new Uint32Array(64);class Ed extends Ws{constructor(e=32){super(64,e,8,!1),this.A=0|Gs[0],this.B=0|Gs[1],this.C=0|Gs[2],this.D=0|Gs[3],this.E=0|Gs[4],this.F=0|Gs[5],this.G=0|Gs[6],this.H=0|Gs[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)kd[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=kd[e-15],n=kd[e-2],r=ws(t,7)^ws(t,18)^t>>>3,s=ws(n,17)^ws(n,19)^n>>>10;kd[e]=s+kd[e-7]+r+kd[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+(ws(a,6)^ws(a,11)^ws(a,25))+zs(a,o,c)+vd[e]+kd[e]|0,d=(ws(n,2)^ws(n,13)^ws(n,22))+Zs(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(){ys(kd)}destroy(){this.set(0,0,0,0,0,0,0,0),ys(this.buffer)}}const Sd=(()=>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}=Qs(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))))(),xd=(()=>Sd[0])(),Od=(()=>Sd[1])(),Td=new Uint32Array(80),Id=new Uint32Array(80);class _d extends Ws{constructor(e=64){super(128,e,16,!1),this.Ah=0|Js[0],this.Al=0|Js[1],this.Bh=0|Js[2],this.Bl=0|Js[3],this.Ch=0|Js[4],this.Cl=0|Js[5],this.Dh=0|Js[6],this.Dl=0|Js[7],this.Eh=0|Js[8],this.El=0|Js[9],this.Fh=0|Js[10],this.Fl=0|Js[11],this.Gh=0|Js[12],this.Gl=0|Js[13],this.Hh=0|Js[14],this.Hl=0|Js[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)Td[n]=e.getUint32(t),Id[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Td[e-15],n=0|Id[e-15],r=ni(t,n,1)^ni(t,n,8)^ei(t,0,7),s=ri(t,n,1)^ri(t,n,8)^ti(t,n,7),i=0|Td[e-2],a=0|Id[e-2],o=ni(i,a,19)^si(i,a,61)^ei(i,0,6),c=ri(i,a,19)^ii(i,a,61)^ti(i,a,6),u=di(s,c,Id[e-7],Id[e-16]),d=li(u,r,o,Td[e-7],Td[e-16]);Td[e]=0|d,Id[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=ni(d,l,14)^ni(d,l,18)^si(d,l,41),b=ri(d,l,14)^ri(d,l,18)^ii(d,l,41),w=d&h^~d&f,v=hi(y,b,l&p^~l&g,Od[e],Id[e]),k=pi(v,m,t,w,xd[e],Td[e]),E=0|v,S=ni(n,r,28)^si(n,r,34)^si(n,r,39),x=ri(n,r,28)^ii(n,r,34)^ii(n,r,39),O=n&s^n&a^s&a,T=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}=oi(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 I=ci(E,x,T);n=ui(I,k,S,O),r=0|I}({h:n,l:r}=oi(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=oi(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=oi(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=oi(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l:l}=oi(0|this.Eh,0|this.El,0|d,0|l)),({h:h,l:p}=oi(0|this.Fh,0|this.Fl,0|h,0|p)),({h:f,l:g}=oi(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=oi(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(){ys(Td,Id)}destroy(){ys(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Ad extends _d{constructor(){super(48),this.Ah=0|Hs[0],this.Al=0|Hs[1],this.Bh=0|Hs[2],this.Bl=0|Hs[3],this.Ch=0|Hs[4],this.Cl=0|Hs[5],this.Dh=0|Hs[6],this.Dl=0|Hs[7],this.Eh=0|Hs[8],this.El=0|Hs[9],this.Fh=0|Hs[10],this.Fl=0|Hs[11],this.Gh=0|Hs[12],this.Gl=0|Hs[13],this.Hh=0|Hs[14],this.Hl=0|Hs[15]}}const Cd=Fs(()=>new Ed),jd=Fs(()=>new _d),Pd=Fs(()=>new Ad),Bd=BigInt(0),Nd=BigInt(1);function Rd(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function $d(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Md(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Bd:BigInt("0x"+e)}function Dd(e){return Md(Is(e))}function Ud(e){return hs(e),Md(Is(Uint8Array.from(e).reverse()))}function Vd(e,t){return Rs(e.toString(16).padStart(2*t,"0"))}function Fd(e,t){return Vd(e,t).reverse()}function Ld(e,t,n){let r;if("string"==typeof t)try{r=Rs(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ds(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 Kd=e=>"bigint"==typeof e&&Bd<=e;function qd(e,t,n,r){if(!function(e,t,n){return Kd(e)&&Kd(t)&&Kd(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function zd(e){let t;for(t=0;e>Bd;e>>=Nd,t+=1);return t}const Zd=e=>(Nd<<BigInt(e))-Nd;function Wd(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 Gd(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 Hd=BigInt(0),Jd=BigInt(1),Yd=BigInt(2),Xd=BigInt(3),Qd=BigInt(4),el=BigInt(5),tl=BigInt(7),nl=BigInt(8),rl=BigInt(9),sl=BigInt(16);function il(e,t){const n=e%t;return n>=Hd?n:t+n}function al(e,t,n){let r=e;for(;t-- >Hd;)r*=r,r%=n;return r}function ol(e,t){if(e===Hd)throw new Error("invert: expected non-zero number");if(t<=Hd)throw new Error("invert: expected positive modulus, got "+t);let n=il(e,t),r=t,s=Hd,i=Jd;for(;n!==Hd;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==Jd)throw new Error("invert: does not exist");return il(s,t)}function cl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ul(e,t){const n=(e.ORDER+Jd)/Qd,r=e.pow(t,n);return cl(e,r,t),r}function dl(e,t){const n=(e.ORDER-el)/nl,r=e.mul(t,Yd),s=e.pow(r,n),i=e.mul(t,s),a=e.mul(e.mul(i,Yd),s),o=e.mul(i,e.sub(a,e.ONE));return cl(e,o,t),o}function ll(e){if(e<Xd)throw new Error("sqrt is not defined for small field");let t=e-Jd,n=0;for(;t%Yd===Hd;)t/=Yd,n++;let r=Yd;const s=yl(e);for(;1===ml(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ul;let i=s.pow(r,t);const a=(t+Jd)/Yd;return function(e,r){if(e.is0(r))return r;if(1!==ml(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=Jd<<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 hl(e){return e%Qd===Xd?ul:e%nl===el?dl:e%sl===rl?function(e){const t=yl(e),n=ll(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),a=(e+tl)/sl;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 cl(e,p,t),p}}(e):ll(e)}const pl=(e,t)=>(il(e,t)&Jd)===Jd,fl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gl(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 ml(e,t){const n=(e.ORDER-Jd)/Yd,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 yl(e,t,n=!1,r={}){if(e<=Hd)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&&ls(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:Zd(c),ZERO:Hd,ONE:Jd,allowedLengths:a,create:t=>il(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Hd<=t&&t<e},is0:e=>e===Hd,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Jd)===Jd,neg:t=>il(-t,e),eql:(e,t)=>e===t,sqr:t=>il(t*t,e),add:(t,n)=>il(t+n,e),sub:(t,n)=>il(t-n,e),mul:(t,n)=>il(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Hd)throw new Error("invalid exponent, negatives unsupported");if(n===Hd)return e.ONE;if(n===Jd)return t;let r=e.ONE,s=t;for(;n>Hd;)n&Jd&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Jd;return r}(l,e,t),div:(t,n)=>il(t*ol(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ol(t,e),sqrt:i||(t=>(d||(d=hl(e)),d(l,t))),toBytes:e=>n?Fd(e,u):Vd(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?Ud(t):Dd(t);if(o&&(s=il(s,e)),!r&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>gl(l,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(l)}function bl(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 wl(e){const t=bl(e);return t+Math.ceil(t/2)}const vl=BigInt(0),kl=BigInt(1);function El(e,t){const n=t.negate();return e?n:t}function Sl(e,t){const n=gl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function xl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ol(e,t){xl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Zd(e),maxNumber:n,shiftBy:BigInt(e)}}function Tl(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+=kl);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 Il=new WeakMap,_l=new WeakMap;function Al(e){return _l.get(e)||1}function Cl(e){if(e!==vl)throw new Error("invalid wNAF")}class jl{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>vl;)t&kl&&(n=n.add(r)),r=r.double(),t>>=kl;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ol(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=Ol(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=Tl(n,e,i);n=a,c?s=s.add(El(d,t[l])):r=r.add(El(u,t[o]))}return Cl(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Ol(e,this.bits);for(let e=0;e<s.windows&&n!==vl;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=Tl(n,e,s);if(n=i,!o){const e=t[a];r=r.add(c?e.negate():e)}}return Cl(n),r}getPrecomputes(e,t,n){let r=Il.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Il.set(t,r))),r}cached(e,t,n){const r=Al(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=Al(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){xl(t,this.bits),_l.set(e,t),Il.delete(e)}hasCache(e){return 1!==Al(e)}}function Pl(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=zd(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=Zd(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 Bl(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=fl.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Wd(e,t)}(t),t}return yl(e)}function Nl(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>vl))throw new Error(`CURVE.${e} must be positive bigint`)}const r=Bl(t.p,n.Fp),s=Bl(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 Rl=BigInt(0),$l=BigInt(1),Ml=BigInt(2),Dl=BigInt(8);class Ul{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 Is(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 Vl(e,t,n){if("function"!=typeof t)throw new Error('"hash" function param is required');Wd(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||Ks,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Rd("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(Ud(e))}function p(e){const{head:n,prefix:r,scalar:a}=function(e){const n=i.BYTES;e=Ld("private key",e,n);const r=Ld("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=Us(...n);return h(t(d(s,Ld("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($l+n,$l-n):i.div(n-$l,n+$l);return i.toBytes(s)},toMontgomeryPriv(e){hs(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=Ld("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);qd("signature.s",f,Rl,o);const m=i.BYTES;return Ld("result",Us(h,Fd(f,m)),2*m)},verify:function(t,n,a,o=m){const{context:c,zip215:u}=o,d=i.BYTES;t=Ld("signature",t,2*d),n=Ld("message",n),a=Ld("publicKey",a,d),void 0!==u&&Rd("zip215",u),r&&(n=r(n));const l=Ud(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 Fl(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:yl(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}=Nl("edwards",e,t),{h:s,n:i}=e;Wd(t,{},{uvRatio:"function"});const a=Ml<<BigInt(8*r.BYTES)-$l,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:Rl}}});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 qd("coordinate "+e,t,n?$l:Rl,a),t}function d(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const l=Gd((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?Dl:n.inv(i));const c=o(r*t),u=o(s*t),d=n.mul(i,t);if(a)return{x:Rl,y:$l};if(d!==$l)throw new Error("invZ was invalid");return{x:c,y:u}}),h=Gd(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 Sl(p,e)}static msm(e,t){return Pl(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,$l,o(t*n))}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(Ml),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(Ml*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),T=o(v*k);return new p(S,x,T,O)}subtract(e){return this.add(e.negate())}multiply(e){const t=e;qd("scalar",t,$l,i);const{p:n,f:r}=f.cached(this,t,e=>Sl(p,e));return Sl(p,[n,r])[0]}multiplyUnsafe(e,t=p.ZERO){const n=e;return qd("scalar",n,Rl,i),n===Rl?p.ZERO:this.is0()||n===$l?this:f.unsafe(this,n,e=>Sl(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===$l?this:this.multiplyUnsafe(s)}static fromBytes(e,t=!1){return hs(e),p.fromHex(e,t)}static fromHex(t,r=!1){const{d:s,a:i}=e,u=n.BYTES;t=Ld("pointHex",t,u),Rd("zip215",r);const d=t.slice(),l=t[u-1];d[u-1]=-129&l;const h=Ud(d),f=r?a:n.ORDER;qd("pointHex.y",h,Rl,f);const g=o(h*h),m=o(g-$l),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&$l)===$l,k=!!(128&l);if(!r&&w===Rl&&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=Fd(t,n.BYTES);return r[r.length-1]|=e&$l?128:0,r}toRawBytes(){return this.toBytes()}toHex(){return Is(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}p.BASE=new p(e.Gx,e.Gy,$l,o(e.Gx*e.Gy)),p.ZERO=new p(Rl,$l,$l,Rl),p.Fp=n,p.Fn=r;const f=new jl(p,8*r.BYTES);return p}(t,n);return function(e,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:e})}(e,Vl(i,r,s))}const Ll=BigInt(0),Kl=BigInt(1),ql=BigInt(2);BigInt(3);const zl=BigInt(5),Zl=BigInt(8),Wl={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Gl(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Hl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Jl(e,t){const n=Wl.p,r=il(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Wl.p,a=e*e%i*e%i,o=al(a,ql,i)*a%i,c=al(o,Kl,i)*e%i,u=al(c,zl,i)*c%i,d=al(u,t,i)*u%i,l=al(d,n,i)*d%i,h=al(l,r,i)*l%i,p=al(h,s,i)*h%i,f=al(p,s,i)*h%i,g=al(f,t,i)*u%i;return{pow_p_5_8:al(g,ql,i)*e%i,b2:a}}(e*il(r*r*t,n)).pow_p_5_8;let i=il(e*r*s,n);const a=il(t*i*i,n),o=i,c=il(i*Hl,n),u=a===e,d=a===il(-e,n),l=a===il(-e*Hl,n);return u&&(i=o),(d||l)&&(i=c),pl(i,n)&&(i=il(-i,n)),{isValid:u||d,value:i}}const Yl=(()=>yl(Wl.p,{isLE:!0}))(),Xl=(()=>yl(Wl.n,{isLE:!0}))(),Ql=(()=>({...Wl,Fp:Yl,hash:jd,adjustScalarBytes:Gl,uvRatio:Jl}))(),eh=(()=>Fl(Ql))(),th=Hl,nh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),rh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),sh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),ih=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ah=e=>Jl(Kl,e),oh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ch=e=>eh.CURVE.Fp.create(Ud(e)&oh);function uh(e){const{d:t}=eh.CURVE,n=eh.CURVE.Fp.ORDER,r=eh.CURVE.Fp.create,s=r(th*e*e),i=r((s+Kl)*sh);let a=BigInt(-1);const o=r((a-t*s)*r(s+t));let{isValid:c,value:u}=Jl(i,o),d=r(u*e);pl(d,n)||(d=r(-d)),c||(u=d),c||(a=s);const l=r(a*(s-Kl)*ih-o),h=u*u,p=r((u+u)*o),f=r(l*nh),g=r(Kl-h),m=r(Kl+h);return new eh.Point(r(p*m),r(g*f),r(f*m),r(p*g))}class dh extends Ul{constructor(e){super(e)}static fromAffine(e){return new dh(eh.Point.fromAffine(e))}assertSame(e){if(!(e instanceof dh))throw new Error("RistrettoPoint expected")}init(e){return new dh(e)}static hashToCurve(e){return function(e){hs(e,64);const t=uh(ch(e.subarray(0,32))),n=uh(ch(e.subarray(32,64)));return new dh(t.add(n))}(Ld("ristrettoHash",e,64))}static fromBytes(e){hs(e,32);const{a:t,d:n}=eh.CURVE,r=Yl.ORDER,s=Yl.create,i=ch(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}(Fd(i,32),e)||pl(i,r))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Kl+t*a),c=s(Kl-t*a),u=s(o*o),d=s(c*c),l=s(t*n*u-d),{isValid:h,value:p}=ah(s(l*d)),f=s(p*c),g=s(p*f*l);let m=s((i+i)*f);pl(m,r)&&(m=s(-m));const y=s(o*g),b=s(m*y);if(!h||pl(b,r)||y===Ll)throw new Error("invalid ristretto255 encoding 2");return new dh(new eh.Point(m,y,Kl,b))}static fromHex(e){return dh.fromBytes(Ld("ristrettoHex",e,32))}static msm(e,t){return Pl(dh,eh.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep;const s=Yl.ORDER,i=Yl.create,a=i(i(n+t)*i(n-t)),o=i(e*t),c=i(o*o),{value:u}=ah(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*r);let p;if(pl(r*h,s)){let n=i(t*th),r=i(e*th);e=n,t=r,p=i(d*rh)}else p=l;pl(e*h,s)&&(t=i(-t));let f=i((n-t)*p);return pl(f,s)&&(f=i(-f)),Fd(f,32)}equals(e){this.assertSame(e);const{X:t,Y:n}=this.ep,{X:r,Y:s}=e.ep,i=Yl.create,a=i(t*s)===i(n*r),o=i(n*s)===i(t*r);return a||o}is0(){return this.equals(dh.ZERO)}}function lh(e,t){return Cr.IntentMessage(Cr.bytes(t.length)).serialize({intent:{scope:{[e]:!0},version:{V0:!0},appId:{Sui:!0}},value:t}).toBytes()}dh.BASE=(()=>new dh(eh.Point.BASE))(),dh.ZERO=(()=>new dh(eh.Point.ZERO))(),dh.Fp=Yl,dh.Fn=Xl;const hh={ED25519:0,Secp256k1:1,Secp256r1:2,MultiSig:3,ZkLogin:5,Passkey:6},ph={ED25519:32,Secp256k1:33,Secp256r1:33,Passkey:33},fh={0:"ED25519",1:"Secp256k1",2:"Secp256r1",3:"MultiSig",5:"ZkLogin",6:"Passkey"};class gh extends Vs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ps(e);const n=Ms(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),ys(s)}update(e){return fs(this),this.iHash.update(e),this}digestInto(e){fs(this),hs(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 mh=(e,t,n)=>new gh(e,t).update(n).digest();mh.create=(e,t)=>new gh(e,t);const yh=(e,t)=>(e+(e>=0?t:-t)/Sh)/t;function bh(e){void 0!==e.lowS&&Rd("lowS",e.lowS),void 0!==e.prehash&&Rd("prehash",e.prehash)}class wh extends Error{constructor(e=""){super(e)}}const vh={Err:wh,_tlv:{encode:(e,t)=>{const{Err:n}=vh;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=$d(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?$d(s.length/2|128):"";return $d(e)+i+s+t},decode(e,t){const{Err:n}=vh;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}=vh;if(e<kh)throw new t("integer: negative integers are not allowed");let n=$d(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}=vh;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 Dd(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=vh,s=Ld("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}=vh,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},kh=BigInt(0),Eh=BigInt(1),Sh=BigInt(2),xh=BigInt(3),Oh=BigInt(4);function Th(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=Ld("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 Ih(e,t={}){const{Fp:n,Fn:r}=Nl("weierstrass",e,t),{h:s,n:i}=e;Wd(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(Rd("isCompressed",r),r){o();return Us(_h(!n.isOdd(i)),a)}return Us(Uint8Array.of(4),a,n.toBytes(i))},u=t.fromBytes||function(e){hs(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,xh),Oh),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=yh(a*e,n),c=yh(-s*e,n);let u=e-o*r-c*i,d=-o*s-c*a;const l=u<kh,h=d<kh;l&&(u=-u),h&&(d=-d);const p=Zd(Math.ceil(zd(n)/2))+Eh;if(u<kh||u>=p||d<kh||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=Gd((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=Gd(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=El(s,t),r=El(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 Sl(v,e)}static fromBytes(e){return hs(e),v.fromHex(e)}static fromHex(e){const t=v.fromAffine(u(Ld("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(Th(r,e))}static msm(e,t){return Pl(v,r,e,t)}_setWindowSize(e){this.precompute(e)}precompute(e=8,t=!0){return E.createCache(this,e),t||this.multiply(xh),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,xh),{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,xh);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=>Sl(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 Sl(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===kh||s.is0())return v.ZERO;if(e===Eh)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>vl||r>vl;)n&kl&&(i=i.add(s)),r&kl&&(a=a.add(s)),s=s.double(),n>>=kl,r>>=kl;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===Eh||(e?e(v,this):E.unsafe(this,i).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Eh?this:e?e(v,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Rd("isCompressed",e),this.assertValidity(),c(v,this,e)}toRawBytes(e=!0){return this.toBytes(e)}toHex(e=!0){return Is(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 jl(v,t.endo?Math.ceil(k/2):k);return v}function _h(e){return Uint8Array.of(e?2:3)}function Ah(e,t,n={}){ps(t),Wd(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Ks,s=n.hmac||((e,...n)=>mh(t,e,Us(...n))),{Fp:i,Fn:a}=e,{ORDER:o,BITS:c}=a,u=wl(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>>Eh}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;hs(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){hs(e);const{r:t,s:n}=vh.toSig(e);return new p(t,n)}throw new Error("invalid format")}static fromHex(e,t){return this.fromBytes(Rs(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*Sh<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(Us(_h(!(1&c)),d)),h=a.inv(u),p=v(Ld("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 Us(a.toBytes(this.r),a.toBytes(this.s));if("der"===e)return Rs(vh.hexFromSig(this));throw new Error("invalid format")}toHex(e){return Is(this.toBytes(e))}assertValidity(){}static fromCompact(e){return p.fromBytes(Ld("sig",e),"compact")}static fromDER(e){return p.fromBytes(Ld("sig",e),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Is(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Is(this.toBytes("compact"))}}function f(e){try{return!!Th(a,e)}catch(e){return!1}}function g(e=r(u)){return function(e,t,n=!1){const r=e.length,s=bl(t),i=wl(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=il(n?Ud(e):Dd(e),t-Jd)+Jd;return n?Fd(a,s):Vd(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=>Th(a,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};function y(t,n=!0){return e.BASE.multiply(Th(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=Ld("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=Dd(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=Zd(c);function E(e){return qd("num < 2^"+c,e,kh,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=Ld("msgHash",n),bh(i),c&&(n=Ld("prehashed msgHash",t(n)));const h=v(n),f=Th(a,s),g=[E(f),E(h)];if(null!=u&&!1!==u){const e=!0===u?r(d.secret):u;g.push(Ld("extraEntropy",e))}const m=Us(...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===kh)return;const c=a.create(r*a.create(y+i*f));if(c===kh)return;let u=(s.x===i?0:2)|Number(s.y&Eh),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 Us(...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=Ld("msgHash",r),s=Ld("publicKey",s),bh(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||ds(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 vh.Err))throw e}if(!l)try{l=p.fromCompact(o)}catch(e){return!1}}}else if("compact"===d||"der"===d){if("string"!=typeof o&&!ds(o))throw new Error('"der" / "compact" format expects Uint8Array signature');l=p.fromBytes(Ld("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=Th(a,t);return e.fromHex(n).multiply(s).toBytes(r)},utils:m,Point:e,Signature:p,info:{type:"weierstrass",lengths:d,publicKeyHasPrefix:!0}})}function Ch(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:yl(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 jh(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=Ch(e);return function(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}(e,Ah(Ih(t,n),r,s))}function Ph(e,t){const n=t=>jh({...e,hash:t});return{...n(t),create:n}}const Bh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Nh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Rh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},$h=yl(Bh.p),Mh=yl(Nh.p),Dh=yl(Rh.p),Uh=Ph({...Bh,Fp:$h,lowS:!1},Cd);Ph({...Nh,Fp:Mh,lowS:!1},Pd),Ph({...Rh,Fp:Dh,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},jd);const Vh=Uh,Fh=Cd;function Lh(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 Kh{equals(e){return Lh(this.toRawBytes(),e.toRawBytes())}toBase64(){return je(this.toRawBytes())}toString(){throw new Error("`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.")}toSuiPublicKey(){return je(this.toSuiBytes())}verifyWithIntent(e,t,n){const r=lh(n,e),s=vi(r,{dkLen:32});return this.verify(s,t)}verifyPersonalMessage(e,t){return this.verifyWithIntent(Cr.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 on(Is(vi(this.toSuiBytes(),{dkLen:32})).slice(0,64))}}function qh(e){const t=Ae(e),n=fh[t[0]];switch(n){case"ED25519":case"Secp256k1":case"Secp256r1":const r=ph[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 zh(e){const t="string"==typeof e?Ae(e):e;if(t[0]!==hh.Passkey)throw new Error("Invalid signature scheme");const n=lr.parse(t.slice(1));return{signatureScheme:"Passkey",serializedSignature:je(t),signature:t,authenticatorData:n.authenticatorData,clientDataJson:n.clientDataJson,userSignature:new Uint8Array(n.userSignature),publicKey:new Uint8Array(n.userSignature.slice(65))}}function Zh(e,t){if(!Boolean(e))throw new Error(t)}(class extends Kh{constructor(e){if(super(),"string"==typeof e?this.data=Ae(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 hh.Passkey}async verify(e,t){const n=zh(t),r=JSON.parse(n.clientDataJson);if("webauthn.get"!==r.type)return!1;if(!Lh(e,Ae(r.challenge.replace(/-/g,"+").replace(/_/g,"/"))))return!1;const s=n.userSignature.slice(65);if(!Lh(this.toRawBytes(),s))return!1;const i=new Uint8Array([...n.authenticatorData,...Fh(n.clientDataJson)]),a=n.userSignature.slice(1,65);return Vh.verify(a,Fh(i),s)}}).SIZE=33;const Wh={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"]},Gh=new Set(Object.keys(Wh));function Hh(e){const t=null==e?void 0:e.kind;return"string"==typeof t&&Gh.has(t)}var Jh,Yh;function Xh(e){return 9===e||32===e}!function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"}(Jh||(Jh={})),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"}(Yh||(Yh={}));function Qh(e){return ep(e,[])}function ep(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:ep(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(ep(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+": "+ep(n,t));return"{ "+r.join(", ")+" }"}(e,n)}(e,t);default:return String(e)}}const tp=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function np(e){return rp[e.charCodeAt(0)]}const rp=["\\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"],sp=Object.freeze({});function ip(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 ap(e){return function(e,t,n=Wh){const r=new Map;for(const e of Object.values(Yh))r.set(e,ip(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;Hh(l)||Zh(!1,`Invalid AST Node: ${Qh(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===sp)break;if(!1===b){if(!e){h.pop();continue}}else if(void 0!==b&&(d.push([i,b]),!e)){if(!Hh(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,op)}const op={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>cp(e.definitions,"\n\n")},OperationDefinition:{leave(e){const t=hp(e.variableDefinitions)?dp("(\n",cp(e.variableDefinitions,"\n"),"\n)"):dp("(",cp(e.variableDefinitions,", "),")"),n=dp("",e.description,"\n")+cp([e.operation,cp([e.name,t]),cp(e.directives," ")]," ");return("query"===n?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r,description:s})=>dp("",s,"\n")+e+": "+t+dp(" = ",n)+dp(" ",cp(r," "))},SelectionSet:{leave:({selections:e})=>up(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:s}){const i=dp("",e,": ")+t;let a=i+dp("(",cp(n,", "),")");return a.length>80&&(a=i+dp("(\n",lp(cp(n,"\n")),"\n)")),cp([a,cp(r," "),s]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+dp(" ",cp(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>cp(["...",dp("on ",e),cp(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:s,description:i})=>dp("",i,"\n")+`fragment ${e}${dp("(",cp(n,", "),")")} `+`on ${t} ${dp("",cp(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||Xh(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&&Xh(e.charCodeAt(0));return(d&&!h||i)&&(l+="\n"),l+=n,(d||u)&&(l+="\n"),'"""'+l+'"""'}(e):`"${e.replace(tp,np)}"`},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+cp(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+cp(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+dp("(",cp(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>dp("",e,"\n")+cp(["schema",cp(t," "),up(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>dp("",e,"\n")+cp(["scalar",t,cp(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>dp("",e,"\n")+cp(["type",t,dp("implements ",cp(n," & ")),cp(r," "),up(s)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:s})=>dp("",e,"\n")+t+(hp(n)?dp("(\n",lp(cp(n,"\n")),"\n)"):dp("(",cp(n,", "),")"))+": "+r+dp(" ",cp(s," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:s})=>dp("",e,"\n")+cp([t+": "+n,dp("= ",r),cp(s," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:s})=>dp("",e,"\n")+cp(["interface",t,dp("implements ",cp(n," & ")),cp(r," "),up(s)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>dp("",e,"\n")+cp(["union",t,cp(n," "),dp("= ",cp(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>dp("",e,"\n")+cp(["enum",t,cp(n," "),up(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>dp("",e,"\n")+cp([t,cp(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>dp("",e,"\n")+cp(["input",t,cp(n," "),up(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:r,locations:s})=>dp("",e,"\n")+"directive @"+t+(hp(n)?dp("(\n",lp(cp(n,"\n")),"\n)"):dp("(",cp(n,", "),")"))+(r?" repeatable":"")+" on "+cp(s," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>cp(["extend schema",cp(e," "),up(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>cp(["extend scalar",e,cp(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>cp(["extend type",e,dp("implements ",cp(t," & ")),cp(n," "),up(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>cp(["extend interface",e,dp("implements ",cp(t," & ")),cp(n," "),up(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>cp(["extend union",e,cp(t," "),dp("= ",cp(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>cp(["extend enum",e,cp(t," "),up(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>cp(["extend input",e,cp(t," "),up(n)]," ")},TypeCoordinate:{leave:({name:e})=>e},MemberCoordinate:{leave:({name:e,memberName:t})=>cp([e,dp(".",t)])},ArgumentCoordinate:{leave:({name:e,fieldName:t,argumentName:n})=>cp([e,dp(".",t),dp("(",n,":)")])},DirectiveCoordinate:{leave:({name:e})=>cp(["@",e])},DirectiveArgumentCoordinate:{leave:({name:e,argumentName:t})=>cp(["@",e,dp("(",t,":)")])}};function cp(e,t=""){var n;return null!==(n=null==e?void 0:e.filter(e=>e).join(t))&&void 0!==n?n:""}function up(e){return dp("{\n",lp(cp(e,"\n")),"\n}")}function dp(e,t,n=""){return null!=t&&""!==t?e+t+n:""}function lp(e){return dp(" ",e.replace(/\n/g,"\n "))}function hp(e){var t;return null!==(t=null==e?void 0:e.some(e=>e.includes("\n")))&&void 0!==t&&t}var pp=(e=>(e.PersonalMessage="PERSONAL_MESSAGE",e.TransactionData="TRANSACTION_DATA",e))(pp||{});class fp extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t}toString(){return this.value}}new fp("\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 fp("\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 fp("\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 fp("\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 gp=new fp("\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 "),mp=new fp('\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 '),yp=new fp('\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}'),bp=new fp("\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 "),wp=new fp("\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 "),vp=new fp("\n query getReferenceGasPrice {\n epoch {\n referenceGasPrice\n }\n}\n "),kp=new fp("\n query defaultSuinsName($address: SuiAddress!) {\n address(address: $address) {\n defaultSuinsName\n }\n}\n "),Ep=new fp("\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}"),Sp=new fp("\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}"),xp=new fp("\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}"),Op=new fp("\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}"),Tp=new fp("\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}"),Ip=new fp("\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 _p,Ap,Cp,jp=e=>{throw TypeError(e)},Pp=(e,t,n)=>t.has(e)||jp("Cannot "+n),Bp=(e,t,n)=>t.has(e)?jp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Np=(e,t,n)=>(Pp(e,t,"access private method"),n);class Rp extends La{constructor({graphqlClient:e,mvr:t}){var n,r,s,i;super({network:e.network,base:e,mvr:t}),Bp(this,Ap),Bp(this,_p),s=e,Pp(n=this,r=_p,"write to private field"),i?i.call(n,s):r.set(n,s)}async getObjects(e){const t=Ne(e.objectIds,50),n=[];for(const e of t){const t=await Np(this,Ap,Cp).call(this,{query:Sp,variables:{objectKeys:e.map(e=>({address:e}))}},e=>e.multiGetObjects);n.push(...e.map(e=>on(e)).map(e=>t.find(t=>t?.address===e)??new qa("notFound",`Object ${e} not found`)).map(e=>e instanceof qa?e:{id:e.address,version:e.version?.toString(),digest:e.digest,owner:Mp(e.owner),type:e.asMoveObject?.contents?.type?.repr,content:Promise.resolve(e.asMoveObject?.contents?.bcs?Ae(e.asMoveObject.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}return{objects:n}}async getOwnedObjects(e){const t=await Np(this,Ap,Cp).call(this,{query:Ep,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:Mp(e.owner),type:e.contents?.type?.repr,content:Promise.resolve(e.contents?.bcs?Ae(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 Np(this,Ap,Cp).call(this,{query:yp,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:Mp(e.owner),type:e.contents?.type?.repr,balance:e.contents?.json?.balance,content:Promise.resolve(e.contents?.bcs?Ae(e.contents.bcs):new Uint8Array),previousTransaction:e.previousTransaction?.digest??null}))}}async getBalance(e){const t=await Np(this,Ap,Cp).call(this,{query:mp,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 Np(this,Ap,Cp).call(this,{query:gp,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:Dp(await Np(this,Ap,Cp).call(this,{query:Tp,variables:{digest:e.digest}},e=>e.transaction))}}async executeTransaction(e){const t=await Np(this,Ap,Cp).call(this,{query:Op,variables:{transactionDataBcs:je(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:Dp(t.effects?.transaction)}}async dryRunTransaction(e){const t=await Np(this,Ap,Cp).call(this,{query:xp,variables:{transaction:{bcs:{value:je(e.transaction)}}}},e=>e.simulateTransaction);if(t.error)throw new Error(t.error);return{transaction:Dp(t.effects?.transaction)}}async getReferenceGasPrice(){return{referenceGasPrice:await Np(this,Ap,Cp).call(this,{query:vp},e=>e.epoch?.referenceGasPrice)}}async getDynamicFields(e){const t=await Np(this,Ap,Cp).call(this,{query:bp,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:ki(e.parentId,t.name?.type?.repr,Ae(t.name?.bcs)),type:an("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:Ae(t.name?.bcs)},valueType:n}}),cursor:t.pageInfo.endCursor??null,hasNextPage:t.pageInfo.hasNextPage}}async verifyZkLoginSignature(e){const t="TransactionData"===e.intentScope?pp.TransactionData:pp.PersonalMessage,n=await Np(this,Ap,Cp).call(this,{query:Ip,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 Np(this,Ap,Cp).call(this,{query:kp,signal:e.signal,variables:{address:e.address}},e=>e.address?.defaultSuinsName??null)}}}async getMoveFunction(e){const t=await Np(this,Ap,Cp).call(this,{query:wp,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:on(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=>Up(e.signature))??[],returns:t.return?.map(({signature:e})=>Up(e))??[]}}}resolveTransactionPlugin(){throw new Error("GraphQL client does not support transaction resolution yet")}}_p=new WeakMap,Ap=new WeakSet,Cp=async function(e,t){const{data:n,errors:r}=await(s=this,i=_p,Pp(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 $p(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 $p extends Error{constructor(e){super(e.message),this.locations=e.locations}}function Mp(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 Dp(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:Za(Ae(e.effects?.effectsBcs)),epoch:e.effects?.epoch?.epochId?.toString()??null,objectTypes:Promise.resolve(t),transaction:za(Ae(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 Up(e){let t=null;return"&"===e.ref?t="immutable":"&mut"===e.ref&&(t="mutable"),{reference:t,body:Vp(e.body)}}function Vp(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:Vp(e.vector)};if("datatype"in e)return{$kind:"datatype",datatype:{typeName:`${on(e.datatype.package)}::${e.datatype.module}::${e.datatype.type}`,typeParameters:e.datatype.typeParameters.map(e=>Vp(e))}};if("typeParameter"in e)return{$kind:"typeParameter",index:e.typeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}var Fp,Lp,Kp,qp,zp=e=>{throw TypeError(e)},Zp=(e,t,n)=>t.has(e)||zp("Cannot "+n),Wp=(e,t,n)=>(Zp(e,t,"read from private field"),n?n.call(e):t.get(e)),Gp=(e,t,n)=>t.has(e)?zp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Hp=(e,t,n,r)=>(Zp(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);class Jp extends Error{}class Yp extends vt{constructor({url:e,fetch:t=fetch,headers:n={},queries:r={},network:s="unknown",mvr:i}){super({network:s}),Gp(this,Fp),Gp(this,Lp),Gp(this,Kp),Gp(this,qp),Hp(this,Fp,e),Hp(this,Lp,r),Hp(this,Kp,n),Hp(this,qp,(...e)=>t(...e)),this.core=new Rp({graphqlClient:this,mvr:i})}async query(e){const t=await Wp(this,qp).call(this,Wp(this,Fp),{method:"POST",headers:{"Content-Type":"application/json",...Wp(this,Kp)},body:JSON.stringify({query:"string"==typeof e.query||e.query instanceof String?String(e.query):ap(e.query),variables:e.variables,extensions:e.extensions,operationName:e.operationName}),signal:e.signal});if(!t.ok)throw new Jp(`GraphQL request failed: ${t.statusText} (${t.status})`);return await t.json()}async execute(e,t){return this.query({...t,query:Wp(this,Lp)[e]})}}function Xp(e,t){return Rs(e.toString(16).padStart(2*t,"0").slice(2*-t))}function Qp(e,t){const n=Xp(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 ef(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 tf(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=ef(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 nf(e,t){const n=tf(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}Fp=new WeakMap,Lp=new WeakMap,Kp=new WeakMap,qp=new WeakMap;const rf=lt.struct("ZkLoginSignature",{inputs:lt.struct("ZkLoginSignatureInputs",{proofPoints:lt.struct("ZkLoginSignatureInputsProofPoints",{a:lt.vector(lt.string()),b:lt.vector(lt.vector(lt.string())),c:lt.vector(lt.string())}),issBase64Details:lt.struct("ZkLoginSignatureInputsClaim",{value:lt.string(),indexMod4:lt.u8()}),headerBase64:lt.string(),addressSeed:lt.string()}),maxEpoch:lt.u64(),userSignature:lt.byteVector()});var sf,af,of,cf,uf,df=e=>{throw TypeError(e)},lf=(e,t,n)=>t.has(e)||df("Cannot "+n),hf=(e,t,n)=>(lf(e,t,"read from private field"),n?n.call(e):t.get(e)),pf=(e,t,n)=>t.has(e)?df("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ff=(e,t,n,r)=>(lf(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),gf=(e,t,n)=>(lf(e,t,"access private method"),n);sf=new WeakMap,af=new WeakMap,of=new WeakMap,cf=new WeakSet,uf=function(){const e=bf(hf(this,sf),!0),t=new Uint8Array(e.length+1);return t[0]=this.flag(),t.set(e,1),on(Is(vi(t,{dkLen:32})).slice(0,64))};let mf=class e extends Kh{constructor(e,{client:t}={}){super(),pf(this,cf),pf(this,sf),pf(this,af),pf(this,of),ff(this,af,t),"string"==typeof e?ff(this,sf,Ae(e)):e instanceof Uint8Array?ff(this,sf,e):ff(this,sf,Uint8Array.from(e)),ff(this,of,hf(this,sf).length!==hf(this,sf)[0]+1+32),hf(this,of)&&ff(this,sf,bf(hf(this,sf)))}static fromBytes(t,{client:n,address:r,legacyAddress:s}={}){let i;if(!0===s?i=new e(bf(t,!0),{client:n}):!1===s?i=new e(bf(t,!1),{client:n}):r?(i=new e(bf(t,!1),{client:n}),i.toSuiAddress()!==r&&(i=new e(bf(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=nf(n,"iss"),i=yf(BigInt(r),s,{legacyAddress:!0});if(i.toSuiAddress()===e)return i;const a=yf(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 hf(this,of)?gf(this,cf,uf).call(this):super.toSuiAddress()}toRawBytes(){return hf(this,sf)}flag(){return hh.ZkLogin}async verify(e,t){throw Error("does not support")}verifyPersonalMessage(t,n){const r=vf(n);return wf({address:new e(r.publicKey).toSuiAddress(),bytes:je(t),signature:r.serializedSignature,intentScope:"PersonalMessage",client:hf(this,af)})}verifyTransaction(t,n){const r=vf(n);return wf({address:new e(r.publicKey).toSuiAddress(),bytes:je(t),signature:r.serializedSignature,intentScope:"TransactionData",client:hf(this,af)})}verifyAddress(e){return e===super.toSuiAddress()||e===gf(this,cf,uf).call(this)}};function yf(e,t,n){const r=n?.legacyAddress?Qp(e,32):Xp(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 mf(i,n)}function bf(e,t=!1){const n=e[0]+1,r=BigInt(`0x${Be(e.slice(n))}`),s=t?Qp(r,32):Xp(r,32),i=new Uint8Array(n+s.length);return i.set(e.slice(0,n),0),i.set(s,n),i}async function wf({address:e,bytes:t,signature:n,intentScope:r,client:s=new Yp({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 vf(e){const t="string"==typeof e?Ae(e):e;if(t[0]!==hh.ZkLogin)throw new Error("Invalid signature scheme");const n=t.slice(1),{inputs:r,maxEpoch:s,userSignature:i}=function(e){return rf.parse("string"==typeof e?Ae(e):e)}(n),{issBase64Details:a,addressSeed:o}=r,c=nf(a,"iss"),u=yf(BigInt(o),c);return{serializedSignature:je(t),signatureScheme:"ZkLogin",zkLogin:{inputs:r,maxEpoch:s,userSignature:i,iss:c,addressSeed:BigInt(o)},signature:t,publicKey:u.toRawBytes()}}function kf(e){const t=Ae(e),n=fh[t[0]];switch(n){case"Passkey":return zh(e);case"MultiSig":return{serializedSignature:e,signatureScheme:n,multisig:Cr.MultiSig.parse(t.slice(1)),bytes:t,signature:void 0};case"ZkLogin":return vf(e);case"ED25519":case"Secp256k1":case"Secp256r1":return qh(e);default:throw new Error("Unsupported signature scheme")}}const Ef="suiprivkey";class Sf{async signWithIntent(e,t){const n=lh(t,e),r=vi(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([hh[t]]),s.set(e,1),s.set(r,1+e.length),je(s)}({signature:await this.sign(r),signatureScheme:this.getKeyScheme(),publicKey:this.getPublicKey()}),bytes:je(e)}}async signTransaction(e){return this.signWithIntent(e,"TransactionData")}async signPersonalMessage(e){const{signature:t}=await this.signWithIntent(lt.byteVector().serialize(e).toBytes(),"PersonalMessage");return{bytes:je(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 xf extends Sf{}function Of(e){const{prefix:t,words:n}=Te.decode(e);if(t!==Ef)throw new Error("invalid private key prefix");const r=new Uint8Array(Te.fromWords(n)),s=r.slice(1),i=fh[r[0]];return{scheme:i,schema:i,secretKey:s}}function Tf(e,t){if(32!==e.length)throw new Error("Invalid bytes length");const n=hh[t],r=new Uint8Array(e.length+1);return r.set([n]),r.set(e,1),Te.encode(Ef,Te.toWords(r))}function If(e,t,n,r){ps(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(ls(i),ls(a),ls(o),i<1)throw new Error("iterations (c) should be >= 1");const c=Ds(t),u=Ds(n),d=new Uint8Array(a),l=mh.create(e,c),h=l._cloneInto().update(u);return{c:i,dkLen:a,asyncTick:o,DK:d,PRF:l,PRFSalt:h}}function _f(e,t,n,r){const{c:s,dkLen:i,DK:a,PRF:o,PRFSalt:c}=If(e,t,n,r);let u;const d=new Uint8Array(4),l=bs(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(),ys(s),n}(o,c,a,u,h)}function Af(e){if("string"!=typeof e)throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function Cf(e,t=""){return _f(jd,function(e){const t=Af(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=>Af("mnemonic"+e))(t),{c:2048,dkLen:64})}function jf(e){return!!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(e)}function Pf(e){return!!new RegExp("^m\\/(54|74)'\\/784'\\/[0-9]+'\\/[0-9]+\\/[0-9]+$").test(e)}function Bf(e){return Cf(e,"")}const Nf=jd,Rf=new RegExp("^m(\\/[0-9]+')+$"),$f=e=>e.replace("'",""),Mf=(e,t,n=2147483648)=>{if(!(e=>!!Rf.test(e)&&!e.split("/").slice(1).map($f).some(isNaN))(e))throw new Error("Invalid derivation path");const{key:r,chainCode:s}=(e=>{const t=mh.create(Nf,"ed25519 seed").update(Pe(e)).digest();return{key:t.slice(0,32),chainCode:t.slice(32)}})(t);return e.split("/").slice(1).map($f).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=mh.create(Nf,t).update(s).digest();return{key:i.slice(0,32),chainCode:i.slice(32)}})(e,t+n),{key:r,chainCode:s})};class Df extends Kh{constructor(e){if(super(),"string"==typeof e?this.data=Ae(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 hh.ED25519}async verify(e,t){let n;if("string"==typeof t){const e=qh(t);if("ED25519"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Lh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return eh.verify(n,e,this.toRawBytes())}}Df.SIZE=32;const Uf="m/44'/784'/0'/0'/0'";class Vf extends xf{constructor(e){if(super(),e)this.keypair={publicKey:e.publicKey,secretKey:e.secretKey.slice(0,32)};else{const e=eh.utils.randomPrivateKey();this.keypair={publicKey:eh.getPublicKey(e),secretKey:e}}}getKeyScheme(){return"ED25519"}static generate(){const e=eh.utils.randomPrivateKey();return new Vf({publicKey:eh.getPublicKey(e),secretKey:e})}static fromSecretKey(e,t){if("string"==typeof e){const n=Of(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:eh.getPublicKey(e),secretKey:e};if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),n=eh.sign(t,e);if(!eh.verify(n,t,r.publicKey))throw new Error("provided secretKey is invalid")}return new Vf(r)}getPublicKey(){return new Df(this.keypair.publicKey)}getSecretKey(){return Tf(this.keypair.secretKey.slice(0,32),this.getKeyScheme())}async sign(e){return eh.sign(e,this.keypair.secretKey)}static deriveKeypair(e,t){if(null==t&&(t=Uf),!jf(t))throw new Error("Invalid derivation path");const{key:n}=Mf(t,function(e){return Be(Bf(e))}(e));return Vf.fromSecretKey(n)}static deriveKeypairFromSeed(e,t){if(null==t&&(t=Uf),!jf(t))throw new Error("Invalid derivation path");const{key:n}=Mf(t,e);return Vf.fromSecretKey(n)}}const Ff={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Lf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Kf=BigInt(2);const qf=yl(Ff.p,void 0,void 0,{sqrt:function(e){const t=Ff.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=al(d,n,t)*d%t,h=al(l,n,t)*d%t,p=al(h,Kf,t)*u%t,f=al(p,s,t)*p%t,g=al(f,i,t)*f%t,m=al(g,o,t)*g%t,y=al(m,c,t)*m%t,b=al(y,o,t)*g%t,w=al(b,n,t)*d%t,v=al(w,a,t)*f%t,k=al(v,r,t)*u%t,E=al(k,Kf,t);if(!qf.eql(qf.sqr(E),e))throw new Error("Cannot find square root");return E}}),zf=Ph({...Ff,Fp:qf,lowS:!0,endo:Lf},Cd),Zf=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Wf=(()=>Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)))(),Gf=(()=>Wf.map(e=>(9*e+5)%16))(),Hf=(()=>{const e=[[Wf],[Gf]];for(let t=0;t<4;t++)for(let n of e)n.push(n[t].map(e=>Zf[e]));return e})(),Jf=(()=>Hf[0])(),Yf=(()=>Hf[1])(),Xf=[[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)),Qf=Jf.map((e,t)=>e.map(e=>Xf[t][e])),eg=Yf.map((e,t)=>e.map(e=>Xf[t][e])),tg=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ng=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function rg(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 sg=new Uint32Array(16);class ig extends Ws{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)sg[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=tg[e],p=ng[e],f=Jf[e],g=Yf[e],m=Qf[e],y=eg[e];for(let t=0;t<16;t++){const r=vs(n+rg(e,s,a,c)+sg[f[t]]+h,m[t])+d|0;n=d,d=c,c=0|vs(a,10),a=s,s=r}for(let e=0;e<16;e++){const n=vs(r+rg(t,i,o,u)+sg[g[e]]+p,y[e])+l|0;r=l,l=u,u=0|vs(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(){ys(sg)}destroy(){this.destroyed=!0,ys(this.buffer),this.set(0,0,0,0,0)}}const ag=Fs(()=>new ig),og=zf.ProjectivePoint,cg=(e=>{return ae((n=t=>e(e(t)),ne(t=4),ee(n),{encode(e){if(!X(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(!X(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}}),ve);var t,n})(Cd);function ug(e){hs(e);const t=0===e.length?"0":Is(e);return BigInt("0x"+t)}const dg=$s("Bitcoin seed"),lg={private:76066276,public:76067358},hg=2147483648,pg=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 bs(t).setUint32(0,e,!1),t};class fg{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return bs(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 cg.encode(this.serialize(this.versions.private,Us(new Uint8Array([0]),e)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return cg.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(e,t=lg){if(hs(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=mh(jd,dg,e);return new fg({versions:t,chainCode:n.slice(32),privateKey:n.slice(0,32)})}static fromExtendedKey(e,t=lg){const n=cg.decode(e),r=bs(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 fg(o?{...i,privateKey:a.slice(1)}:{...i,publicKey:a})}static fromJSON(e){return fg.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||lg,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(!zf.utils.isValidPrivateKey(e.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof e.privateKey?e.privateKey:ug(e.privateKey),this.privKeyBytes=function(e){if("bigint"!=typeof e)throw new Error("bigint expected");return Rs(e.toString(16).padStart(64,"0"))}(this.privKey),this.pubKey=zf.getPublicKey(e.privateKey,!0)}else{if(!e.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=og.fromHex(e.publicKey).toRawBytes(!0)}var t;this.pubHash=(t=this.pubKey,ag(Cd(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>=hg)throw new Error("Invalid index");"'"===t[2]&&(s+=hg),n=n.deriveChild(s)}return n}deriveChild(e){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let t=pg(e);if(e>=hg){const e=this.privateKey;if(!e)throw new Error("Could not derive hardened child key");t=Us(new Uint8Array([0]),e,t)}else t=Us(this.pubKey,t);const n=mh(jd,this.chainCode,t),r=ug(n.slice(0,32)),s=n.slice(32);if(!zf.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=il(this.privKey+r,zf.CURVE.n);if(!zf.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=og.fromHex(this.pubKey).add(og.fromPrivateKey(r));if(e.equals(og.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=e.toRawBytes(!0)}return new fg(i)}catch(t){return this.deriveChild(e+1)}}sign(e){if(!this.privateKey)throw new Error("No privateKey set!");return hs(e,32),zf.sign(e,this.privKey).toCompactRawBytes()}verify(e,t){if(hs(e,32),hs(t,64),!this.publicKey)throw new Error("No publicKey set!");let n;try{n=zf.Signature.fromCompact(t)}catch(e){return!1}return zf.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 hs(t,33),Us(pg(e),new Uint8Array([this.depth]),pg(this.parentFingerprint),pg(this.index),this.chainCode,t)}}class gg extends Kh{constructor(e){if(super(),"string"==typeof e?this.data=Ae(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 hh.Secp256k1}async verify(e,t){let n;if("string"==typeof t){const e=qh(t);if("Secp256k1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Lh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return zf.verify(zf.Signature.fromCompact(n),Fh(e),this.toRawBytes())}}gg.SIZE=33;class mg extends xf{constructor(e){if(super(),e)this.keypair=e;else{const e=zf.utils.randomPrivateKey(),t=zf.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256k1"}static generate(){return new mg}static fromSecretKey(e,t){if("string"==typeof e){const n=Of(e);if("Secp256k1"!==n.schema)throw new Error(`Expected a Secp256k1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=zf.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=Is(vi(t,{dkLen:32})),s=zf.sign(r,e);if(!zf.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new mg({publicKey:n,secretKey:e})}static fromSeed(e){const t=zf.getPublicKey(e,!0);return new mg({publicKey:t,secretKey:e})}getPublicKey(){return new gg(this.keypair.publicKey)}getSecretKey(){return Tf(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Fh(e);return zf.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/54'/784'/0'/0/0"),!Pf(t))throw new Error("Invalid derivation path");const n=fg.fromMasterSeed(Bf(e)).derive(t);if(null==n.publicKey||null==n.privateKey)throw new Error("Invalid key");return new mg({publicKey:n.publicKey,secretKey:n.privateKey})}}class yg extends Kh{constructor(e){if(super(),"string"==typeof e?this.data=Ae(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 hh.Secp256r1}async verify(e,t){let n;if("string"==typeof t){const e=kf(t);if("Secp256r1"!==e.signatureScheme)throw new Error("Invalid signature scheme");if(!Lh(this.toRawBytes(),e.publicKey))throw new Error("Signature does not match public key");n=e.signature}else n=t;return Vh.verify(Vh.Signature.fromCompact(n),Fh(e),this.toRawBytes())}}yg.SIZE=33;class bg extends xf{constructor(e){if(super(),e)this.keypair=e;else{const e=Vh.utils.randomPrivateKey(),t=Vh.getPublicKey(e,!0);this.keypair={publicKey:t,secretKey:e}}}getKeyScheme(){return"Secp256r1"}static generate(){return new bg}static fromSecretKey(e,t){if("string"==typeof e){const n=Of(e);if("Secp256r1"!==n.schema)throw new Error(`Expected a Secp256r1 keypair, got ${n.schema}`);return this.fromSecretKey(n.secretKey,t)}const n=Vh.getPublicKey(e,!0);if(!t||!t.skipValidation){const t=(new TextEncoder).encode("sui validation"),r=Is(vi(t,{dkLen:32})),s=Vh.sign(r,e,{lowS:!0});if(!Vh.verify(s,r,n,{lowS:!0}))throw new Error("Provided secretKey is invalid")}return new bg({publicKey:n,secretKey:e})}static fromSeed(e){const t=Vh.getPublicKey(e,!0);return new bg({publicKey:t,secretKey:e})}getPublicKey(){return new yg(this.keypair.publicKey)}getSecretKey(){return Tf(this.keypair.secretKey,this.getKeyScheme())}async sign(e){const t=Fh(e);return Vh.sign(t,this.keypair.secretKey,{lowS:!0}).toCompactRawBytes()}static deriveKeypair(e,t){if(null==t&&(t="m/74'/784'/0'/0/0"),!Pf(t))throw new Error("Invalid derivation path");const n=fg.fromMasterSeed(Bf(e)).derive(t).privateKey;return bg.fromSecretKey(n)}}var wg;function vg(e,t=!1){let n,r;if("object"==typeof e){if(!t)throw new Error("Invalid secret key format");r=Ae(e.privateKey),n=e.schema}else{const t=Of(e);n=t.schema,r=t.secretKey}switch(n){case"ED25519":{let e=r;return 64===r.length&&(e=r.slice(0,32)),Vf.fromSecretKey(e)}case"Secp256k1":return mg.fromSecretKey(r);case"Secp256r1":return bg.fromSecretKey(r);default:throw new Error(`Invalid keypair schema: ${n}`)}}async function kg(e,t){const n=await e.signPersonalMessage(t);return Eg("string"==typeof n?n:n.signature,!0)}function Eg(e,t=!1){const n=kf(e);let r=i.Buffer.from(n.signature).toString("hex"),s=i.Buffer.from(n.publicKey).toString("base64"),a=exports.SignerTypes.KP_SECP256;if("Secp256k1"===n.signatureScheme||"Secp256r1"===n.signatureScheme)a=exports.SignerTypes.KP_SECP256;else if("ED25519"===n.signatureScheme)a=t?exports.SignerTypes.KP_ED25519:exports.SignerTypes.UI_ED25519;else{if("ZkLogin"!==n.signatureScheme)throw new Error(`Unsupported signature scheme: ${n.signatureScheme}`);a=exports.SignerTypes.ZK_ED25519}return`${r}${a}${s}`}function Sg(e,t=18){if(!e&&0!==e)return"0";try{const n=new l.default(e);if(n.isNaN())return"0";return n.multipliedBy(new l.default(10).pow(t)).integerValue(l.default.ROUND_DOWN).toString(10)}catch(e){return"0"}}function xg(e,t=18){return new l.default(e).multipliedBy(new l.default(10).pow(t))}function Og(e){return e instanceof Error?e.message:"string"==typeof e?e:String(e)}function Tg(e){const t=function(){try{if(void 0!=={url:"undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href}&&("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href)){const e=c.fileURLToPath("undefined"==typeof document?new(require("url").URL)("file:"+e).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs.js",document.baseURI).href);return f.default.dirname(e)}}catch(e){}return"undefined"!=typeof __dirname?__dirname:process.cwd()}();let n=null;if(f.default.isAbsolute(e))n=e;else{const r=f.default.resolve(t,".."),s=f.default.resolve(r,e);if(p.default.existsSync(s))n=s;else{const r=function(e){let t=e;const n=f.default.parse(t).root;for(;t!==n;){const e=f.default.join(t,"package.json");if(p.default.existsSync(e))try{if("dipcoin-cli"===JSON.parse(p.default.readFileSync(e,"utf-8")).name)return t}catch(e){}const n=f.default.dirname(t);if(n===t)break;t=n}return null}(t);if(r){const t=f.default.resolve(r,"dist",e);p.default.existsSync(t)&&(n=t)}if(!n){const t=f.default.resolve(process.cwd(),e);p.default.existsSync(t)&&(n=t)}}}if(!n||!p.default.existsSync(n))return{packages:[]};const r=JSON.parse(p.default.readFileSync(n).toString());return r.packages&&Array.isArray(r.packages)||(r.packages=[]),r}exports.SignerTypes=void 0,(wg=exports.SignerTypes||(exports.SignerTypes={})).KP_SECP256="0",wg.KP_ED25519="1",wg.UI_ED25519="2",wg.ZK_ED25519="3";const Ig=f.default.join(g.default.homedir(),".config","dipcoin","jwt");function _g(e){return f.default.join(Ig,`${e}.json`)}function Ag(e){try{const t=_g(e);if(!p.default.existsSync(t))return null;const n=p.default.readFileSync(t,"utf-8"),r=JSON.parse(n),s=Math.floor(Date.now()/1e3);return r.exp-60>s?r.token:(p.default.unlinkSync(t),null)}catch{return null}}function Cg(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;p.default.mkdirSync(Ig,{recursive:!0});const r={token:t,exp:n};p.default.writeFileSync(_g(e),JSON.stringify(r),{mode:384})}catch{}}function jg(e){try{const t=_g(e);p.default.existsSync(t)&&p.default.unlinkSync(t)}catch{}}class Pg{httpClient;keypair;subKeypair;walletAddress;subAddress;options;jwtToken;subJwtToken;isAuthenticating=!1;isSubAuthenticating=!1;exchangeOnChain;deploymentConfig;suiClient;transactionBuilder;priceServiceConnection;pythClient;tradingPairsCache;tradingPairsCacheTimestamp;constructor(t,n){this.options=n,this.httpClient=new yd(n.apiBaseUrl),this.keypair="string"==typeof t?vg(t):t,n.subAccountKey&&("string"==typeof n.subAccountKey?this.subKeypair=vg(n.subAccountKey):this.subKeypair=n.subAccountKey,this.subAddress=this.subKeypair.getPublicKey().toSuiAddress()),this.walletAddress=this.keypair.getPublicKey().toSuiAddress(),this.httpClient.setWalletAddress(this.walletAddress),this.deploymentConfig=Tg(`config/deployed/${n.network}/main_contract.json`);const r=n.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}`)}}(n.network);this.suiClient=new co({url:r}),this.exchangeOnChain=new e.ExchangeOnChain(this.deploymentConfig,this.suiClient,this.keypair);const s=this.getDeploymentPackageId(),i=this.getDeploymentProtocolConfigId();this.transactionBuilder=new e.TransactionBuilder(s,i,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};const e=Ag(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(fd),n=await kg(this.keypair,t),r=await this.httpClient.post(pd.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),Cg(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:Og(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=Ag(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(fd),r=await kg(this.subKeypair,n),s=await this.httpClient.post(pd.AUTHORIZE,{userAddress:e,isTermAccepted:!0,signature:r});return 200===s.code&&s.data?.token?(this.subJwtToken=s.data.token,Cg(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:Og(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&&jg(this.walletAddress),this.subJwtToken&&this.subAddress&&jg(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===exports.OrderType.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:h="",creator:p,tpTriggerPrice:f,tpOrderType:g=exports.OrderType.MARKET,tpOrderPrice:m="",slTriggerPrice:y,slOrderType:b=exports.OrderType.MARKET,slOrderPrice:w=""}=t,v=p||this.walletAddress,k=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 E=o&&""!==o?xg(o):new l.default(0),S=xg(a),x=xg(c),O=new l.default(0),T=new l.default(+new Date),I={market:u,creator:v,isLong:s===exports.OrderSide.BUY,reduceOnly:d,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:i===exports.OrderType.LIMIT?E:new l.default(0),leverage:x,expiration:O,salt:T};let _=null,A=null;f&&(A=new l.default(Date.now()+1),_={market:I.market,creator:v,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:g===exports.OrderType.LIMIT?xg(m||f):xg(""),leverage:x,expiration:O,salt:A});let C=null,j=null;y&&(j=new l.default(Date.now()+2),C={market:I.market,creator:v,isLong:!I.isLong,reduceOnly:!0,postOnly:!1,orderbookOnly:!0,ioc:!1,quantity:S,price:b===exports.OrderType.LIMIT?xg(w||y):xg(""),leverage:x,expiration:O,salt:j});const P=e.OrderSigner.getOrderMessageForUIWallet(I),B=(new TextEncoder).encode(P),N=await kg(k,B);let R,$;if(_){const t=e.OrderSigner.getOrderMessageForUIWallet(_),n=(new TextEncoder).encode(t);R=await kg(k,n)}if(C){const t=e.OrderSigner.getOrderMessageForUIWallet(C),n=(new TextEncoder).encode(t);$=await kg(k,n)}const M={symbol:r,side:s,orderType:i,quantity:Sg(a),price:Sg(o||""),leverage:Sg(c),salt:T.toString(),creator:v,clientId:h,reduceOnly:d,orderSignature:N};f&&R&&(M.tpOrderSignature=R,M.tpTriggerPrice=Sg(f),M.tpOrderType=g,M.tpOrderPrice=g===exports.OrderType.LIMIT?Sg(m||f):Sg(""),M.tpSalt=A?.toString(),M.triggerWay="oracle"),y&&$&&(M.slOrderSignature=$,M.slTriggerPrice=Sg(y),M.slOrderType=b,M.slOrderPrice=b===exports.OrderType.LIMIT?Sg(w||y):Sg(""),M.slSalt=j?.toString());const D=await this.httpClient.post(pd.PLACE_ORDER,M);if(1e3===D.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(pd.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===D.code?{status:!0,data:D}:{status:!1,error:D.message||"Order failed",data:D}}catch(e){return this.restoreMainAuth(),{status:!1,error:Og(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 kg(i,o),parentAddress:s},u=await this.httpClient.post(pd.CANCEL_ORDER,c);if(1e3===u.code){this.clearAuth();if((await this.authenticateForTrading()).status){const e=await this.httpClient.post(pd.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:Og(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:Sg(r)};let a=await this.httpClient.post(pd.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(pd.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:Og(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(pd.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(pd.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:Og(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:h=!1,orderbookOnly:p=!0,ioc:f=!1,tp:g,sl:m}=t;if(!this.isPositiveNumber(u))return{status:!1,error:"Quantity must be greater than zero"};const y=this.hasTpSlOrderConfig(g,u),b=this.hasTpSlOrderConfig(m,u);if(!y&&!b)return{status:!1,error:"At least one TP or SL configuration is required"};const w=xg(c),v=Sg(c),k=new l.default(0),E=new l.default(+new Date),S=E.plus(1),x={symbol:s,side:a,leverage:v,creator:this.walletAddress},O=async e=>{let t=await this.httpClient.post(pd.PLAN_CLOSE_ORDER,e);if(1e3===t.code){this.clearAuth();(await this.authenticate()).status&&(t=await this.httpClient.post(pd.PLAN_CLOSE_ORDER,e))}return t},T={};let I,_;if(y&&g){if(!this.isPositiveNumber(g.triggerPrice))return{status:!1,error:"TP trigger price must be greater than zero"};const t=g.salt?new l.default(g.salt):E,n=xg(g.quantity??u),s=(g.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?xg(g.orderPrice??g.triggerPrice??"0"):new l.default(0),a={market:i,creator:this.walletAddress,isLong:!o,reduceOnly:d,postOnly:h,orderbookOnly:p,ioc:f,quantity:n,price:s,leverage:w,expiration:k,salt:t},c=e.OrderSigner.getOrderMessageForUIWallet(a),m=await kg(r,(new TextEncoder).encode(c));I={...x,tpOrderType:g.orderType||exports.OrderType.MARKET,tpTpslType:g.tpslType||"position",tpTriggerPrice:Sg(g.triggerPrice),tpOrderPrice:(g.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?Sg(g.orderPrice??g.triggerPrice??"0"):"0",tpQuantity:Sg(g.quantity??u),tpTriggerWay:g.triggerWay||"oracle",tpSalt:t.toString(),tpOrderSignature:m},void 0!==g.planId&&(I.tpPlanId=g.planId)}if(b&&m){if(!this.isPositiveNumber(m.triggerPrice))return{status:!1,error:"SL trigger price must be greater than zero"};const t=m.salt?new l.default(m.salt):S,n=xg(m.quantity??u),s=(m.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?xg(m.orderPrice??m.triggerPrice??"0"):new l.default(0),a={market:i,creator:this.walletAddress,isLong:!o,reduceOnly:d,postOnly:h,orderbookOnly:p,ioc:f,quantity:n,price:s,leverage:w,expiration:k,salt:t},c=e.OrderSigner.getOrderMessageForUIWallet(a),g=await kg(r,(new TextEncoder).encode(c));_={...x,slOrderType:m.orderType||exports.OrderType.MARKET,slTpslType:m.tpslType||"position",slTriggerPrice:Sg(m.triggerPrice),slOrderPrice:(m.orderType||exports.OrderType.MARKET)===exports.OrderType.LIMIT?Sg(m.orderPrice??m.triggerPrice??"0"):"0",slQuantity:Sg(m.quantity??u),slTriggerWay:m.triggerWay||"oracle",slSalt:t.toString(),slOrderSignature:g},void 0!==m.planId&&(_.slPlanId=m.planId)}if(y&&b&&I&&_){const e={...I,..._},t=await O(e);T.tpResult=t,T.slResult=t}else y&&I?T.tpResult=await O(I):b&&_&&(T.slResult=await O(_));return[T.tpResult,T.slResult].some(e=>e&&200===e.code)?(this.restoreMainAuth(),{status:!0,data:T}):(this.restoreMainAuth(),{status:!1,data:T,error:T.tpResult?.message||T.slResult?.message||"Failed to place TP/SL order"})}catch(e){return this.restoreMainAuth(),{status:!1,error:Og(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(pd.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(pd.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:Og(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(pd.GET_ACCOUNT_INFO,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(pd.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:Og(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(pd.GET_POSITIONS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(pd.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:Og(e)}}}async getTradingPairs(){try{const e=await this.httpClient.get(pd.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:Og(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(pd.GET_OPEN_ORDERS,{params:n});if(1e3===r.code){this.clearAuth();if((await this.authenticate()).status){const e=await this.httpClient.get(pd.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:Og(e)}}}async getOrderBook(e){try{if(!e)return{status:!1,error:"Symbol is required"};const t={symbol:e},n=await this.httpClient.get(pd.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:Og(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 l.default(e);return n.isNaN()||n.isZero()?"0":n.dividedBy(new l.default(10).pow(t)).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(pd.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:Og(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 l.default(e).gt(0)}catch{return!1}}processTickerData(e){let t;if(e.bestAskPrice&&e.bestBidPrice){const n=new l.default(e.bestAskPrice),r=new l.default(e.bestBidPrice);t=n.plus(r).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),e?.beginTime&&(n.beginTime=e.beginTime),e?.endTime&&(n.endTime=e.endTime);let r=await this.httpClient.get(pd.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(pd.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:Og(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(pd.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(pd.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:Og(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(pd.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(pd.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:Og(e)}}}async getOraclePrice(e){try{if(!e)return{status:!1,error:"Symbol is required"};const t=await this.httpClient.get(pd.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:Og(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:r,symbol:s,market:i,perpId:a,subAccountsMapId:o,gasBudget:c,txHash:u}=e;if(!this.isPositiveNumber(n))throw new Error(`Amount must be greater than zero to ${t} margin`);const d=new l.default(n).toNumber();if(!Number.isFinite(d))throw new Error("Amount is too large to represent as a number");const h=i||s,p=h?h.toUpperCase():void 0,f=a||(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:d,account:r||this.walletAddress,market:p,perpID:f,subAccountsMapID:o,gasBudget:c,txHash:u}}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 Va;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 Va,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=md[this.options.network];e&&(this.priceServiceConnection||(this.priceServiceConnection=new dd(e.priceServiceUrl)),this.pythClient||(this.pythClient=new hd(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:Sg(e,gd.USDC),accountAddress:this.address},this.keypair)}async withdrawFromBank(e){return await this.exchangeOnChain.withdrawFromBank({amount:Sg(e,gd.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:Og(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:Og(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 Va,s=this.getVaultPackageId(),i=this.getCurrencyType(),a=t&&t.length>0?t:this.getMarketSymbols();if("testnet"===this.options.network&&this.transactionBuilder){const e=[];for(const t of a)try{const n=await this.exchangeOnChain.getOraclePrice(t);null!=n&&e.push({price:Number(n),market:t})}catch{}e.length>0&&this.transactionBuilder.price_info_batchSetOraclePriceTx({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 Va,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(Sg(e.maxCap)),t.pure.u128(Sg(e.minDepositAmount)),t.pure.u128(e.creatorMinimumShareRatio),t.pure.u128(e.creatorProfitShareRatio),t.pure.u128(Sg(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(Sg(e.amount))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(n)}async requestWithdrawFromVault(e){const t=new Va,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(Sg(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 Va,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 Va,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 Va,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 Va,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 Va,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 Va,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(Sg(e.maxCap))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultMinDepositAmount(e){const t=new Va,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(Sg(e.minDepositAmount))],typeArguments:[this.getCurrencyType()]}),this.signAndExecuteVaultTx(t)}async setVaultAutoCloseOnWithdraw(e){const t=new Va,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:Og(e)}}}async listVaults(e){try{const t=e||this.walletAddress,n=await this.httpClient.get(pd.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:Og(e)}}}}exports.API_ENDPOINTS=pd,exports.DECIMALS=gd,exports.DEFAULT_API_URLS=m,exports.DEFAULT_SLIPPAGE=.05,exports.DipCoinPerpSDK=Pg,exports.HttpClient=yd,exports.ONBOARDING_MESSAGE=fd,exports.PYTH_CONFIG=md,exports.buildSignature=Eg,exports.default=Pg,exports.formatError=Og,exports.formatNormalToWei=Sg,exports.formatNormalToWeiBN=xg,exports.fromExportedKeypair=vg,exports.initDipCoinPerpSDK=function(e,t){const n=y(t);return new Pg(e,n)},exports.initSDKOptions=y,exports.readFile=Tg,exports.signMessage=kg;
4
4
  //# sourceMappingURL=index.cjs.js.map