@stellar/stellar-sdk 16.0.0 → 16.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/stellar-sdk-axios.js +3 -3
- package/dist/stellar-sdk-axios.min.js +1 -1
- package/dist/stellar-sdk.js +3 -3
- package/dist/stellar-sdk.min.js +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/package.json +3 -0
- package/lib/axios/esm/rpc/axios.js +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/package.json +3 -0
- package/lib/esm/rpc/axios.js +1 -1
- package/package.json +1 -1
package/dist/stellar-sdk.min.js
CHANGED
|
@@ -196,5 +196,5 @@
|
|
|
196
196
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
197
197
|
* @license MIT
|
|
198
198
|
*/var fe=(de||(de=1,function(e){const t=function(){if(ae)return ue;ae=1,ue.byteLength=function(e){var t=s(e),n=t[0],r=t[1];return 3*(n+r)/4-r},ue.toByteArray=function(e){var r,o,i=s(e),a=i[0],c=i[1],u=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),l=0,d=c>0?a-4:a;for(o=0;o<d;o+=4)r=t[e.charCodeAt(o)]<<18|t[e.charCodeAt(o+1)]<<12|t[e.charCodeAt(o+2)]<<6|t[e.charCodeAt(o+3)],u[l++]=r>>16&255,u[l++]=r>>8&255,u[l++]=255&r;return 2===c&&(r=t[e.charCodeAt(o)]<<2|t[e.charCodeAt(o+1)]>>4,u[l++]=255&r),1===c&&(r=t[e.charCodeAt(o)]<<10|t[e.charCodeAt(o+1)]<<4|t[e.charCodeAt(o+2)]>>2,u[l++]=r>>8&255,u[l++]=255&r),u},ue.fromByteArray=function(t){for(var n,r=t.length,o=r%3,s=[],i=16383,c=0,u=r-o;c<u;c+=i)s.push(a(t,c,c+i>u?u:c+i));return 1===o?(n=t[r-1],s.push(e[n>>2]+e[n<<4&63]+"==")):2===o&&(n=(t[r-2]<<8)+t[r-1],s.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"=")),s.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)e[o]=r[o],t[r.charCodeAt(o)]=o;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function i(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),o.push(i(r));return o.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,ue}(),n=he(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=i,e.SlowBuffer=function(e){return+e!=e&&(e=0),i.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function s(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,i.prototype),t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|h(e,t);let r=s(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(W(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(W(e,ArrayBuffer)||e&&W(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(W(e,SharedArrayBuffer)||e&&W(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);const o=function(e){if(i.isBuffer(e)){const t=0|p(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?s(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),s(e<0?0:0|p(e))}function l(e){const t=e.length<0?0:0|p(e.length),n=s(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,i.prototype),r}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function h(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||W(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return X(e).length;default:if(o)return r?-1:$(e).length;t=(""+t).toLowerCase(),o=!0}}function f(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,n);case"utf8":case"utf-8":return E(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function g(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Z(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let s,i=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;i=2,a/=2,c/=2,n/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){let r=-1;for(s=n;s<a;s++)if(u(e,s)===u(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*i}else-1!==r&&(s-=s-r),r=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(u(e,s+r)!==u(t,r)){n=!1;break}if(n)return s}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const s=t.length;let i;for(r>s/2&&(r=s/2),i=0;i<r;++i){const r=parseInt(t.substr(2*i,2),16);if(Z(r))return i;e[n+i]=r}return i}function A(e,t,n,r){return K($(t,e.length-n),e,n,r)}function S(e,t,n,r){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function b(e,t,n,r){return K(X(t),e,n,r)}function v(e,t,n,r){return K(function(e,t){let n,r,o;const s=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)n=e.charCodeAt(i),r=n>>8,o=n%256,s.push(o),s.push(r);return s}(t,e.length-n),e,n,r)}function T(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function E(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let s=null,i=t>239?4:t>223?3:t>191?2:1;if(o+i<=n){let n,r,a,c;switch(i){case 1:t<128&&(s=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,i=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),o+=i}return function(e){const t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=k));return n}(r)}e.kMaxLength=o,i.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(W(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),W(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,s=Math.min(n,r);o<s;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=i.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(W(t,Uint8Array))o+t.length>r.length?(i.isBuffer(t)||(t=i.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!i.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},i.byteLength=h,i.prototype._isBuffer=!0,i.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)m(this,t,t+1);return this},i.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)m(this,t,t+3),m(this,t+1,t+2);return this},i.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},i.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?E(this,0,e):f.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(i.prototype[r]=i.prototype.inspect),i.prototype.compare=function(e,t,n,r,o){if(W(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(s,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){s=u[e],a=l[e];break}return s<a?-1:a<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return g(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return g(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return A(this,e,t,n);case"ascii":case"latin1":case"binary":return S(this,e,t,n);case"base64":return b(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function C(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function B(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=z[e[r]];return o}function x(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function R(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(e,t,n,r,o,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,o){M(t,r,o,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,n}function O(e,t,n,r,o){M(t,r,o,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=i,i>>=8,e[n+2]=i,i>>=8,e[n+1]=i,i>>=8,e[n]=i,n+8}function U(e,t,n,r,o,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,r,o,s){return t=+t,r>>>=0,s||U(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function N(e,t,r,o,s){return t=+t,r>>>=0,s||U(e,0,r,8),n.write(e,t,r,o,52,8),r+8}i.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,i.prototype),r},i.prototype.readUintLE=i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);let r=this[e],o=1,s=0;for(;++s<t&&(o*=256);)r+=this[e+s]*o;return r},i.prototype.readUintBE=i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},i.prototype.readUint8=i.prototype.readUInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),this[e]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readBigUInt64LE=j(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),i.prototype.readBigUInt64BE=j(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);let r=this[e],o=1,s=0;for(;++s<t&&(o*=256);)r+=this[e+s]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);let r=t,o=1,s=this[e+--r];for(;r>0&&(o*=256);)s+=this[e+--r]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||R(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||R(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readBigInt64LE=j(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),i.prototype.readBigInt64BE=j(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),i.prototype.readFloatLE=function(e,t){return e>>>=0,t||R(e,4,this.length),n.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||R(e,4,this.length),n.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||R(e,8,this.length),n.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||R(e,8,this.length),n.read(this,e,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,s=0;for(this[t]=255&e;++s<n&&(o*=256);)this[t+s]=e/o&255;return t+n},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,s=1;for(this[t+o]=255&e;--o>=0&&(s*=256);)this[t+o]=e/s&255;return t+n},i.prototype.writeUint8=i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigUInt64LE=j(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=j(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let o=0,s=1,i=0;for(this[t]=255&e;++o<n&&(s*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/s|0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let o=n-1,s=1,i=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/s|0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigInt64LE=j(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=j(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return N(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return N(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const s=i.isBuffer(e)?e:i.from(e,r),a=s.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=s[o%a]}return this};const V={};function F(e,t,n){V[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function D(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function M(e,t,n,r,o,s){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new V.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||H(t,e.length-(n+1))}(r,o,s)}function q(e,t){if("number"!=typeof e)throw new V.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new V.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new V.ERR_BUFFER_OUT_OF_BOUNDS;throw new V.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),F("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),F("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=D(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=D(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function $(e,t){let n;t=t||1/0;const r=e.length;let o=null;const s=[];for(let i=0;i<r;++i){if(n=e.charCodeAt(i),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(i+1===r){(t-=3)>-1&&s.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&s.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function X(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function W(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const z=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function j(e){return"undefined"==typeof BigInt?Y:e}function Y(){throw new Error("BigInt not supported")}}(ce)),ce);function me(e,t,n=""){const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name&&"BYTES_PER_ELEMENT"in o&&1===o.BYTES_PER_ELEMENT;var o;const s=e?.length;if(!r||void 0!==t){const t=(n&&`"${n}" `)+"expected Uint8Array"+""+", got "+(r?`length=${s}`:"type="+typeof e);if(!r)throw new TypeError(t);throw new RangeError(t)}return e}function ge(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 ye(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function we(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ae(e,t){return e<<32-t|e>>>t}function Se(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const be=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ve(e,t,n){return e&t^~e&n}function Te(e,t,n){return e&t^e&n^t&n}class Ee{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=we(this.buffer)}update(e){ge(this),me(e);const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){const t=we(e);for(;r<=o-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ge(this),function(e,t){me(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:s}=this;t[s++]=128,ye(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),o),this.process(n,0);const i=we(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,u[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ie=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ce=BigInt(2**32-1),Be=BigInt(32);function xe(e,t=!1){return t?{h:Number(e&Ce),l:Number(e>>Be&Ce)}:{h:0|Number(e>>Be&Ce),l:0|Number(e&Ce)}}const Re=(e,t,n)=>e>>>n,_e=(e,t,n)=>e<<32-n|t>>>n,Pe=(e,t,n)=>e>>>n|t<<32-n,Oe=(e,t,n)=>e<<32-n|t>>>n,Ue=(e,t,n)=>e<<64-n|t>>>n-32,Le=(e,t,n)=>e>>>n-32|t<<64-n;function Ne(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const Ve=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Fe=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,De=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Me=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,qe=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),He=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,Ge=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]),$e=new Uint32Array(64);class Xe extends Ee{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:o,F:s,G:i,H:a}=this;return[e,t,n,r,o,s,i,a]}set(e,t,n,r,o,s,i,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|s,this.G=0|i,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)$e[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=$e[e-15],n=$e[e-2],r=Ae(t,7)^Ae(t,18)^t>>>3,o=Ae(n,17)^Ae(n,19)^n>>>10;$e[e]=o+$e[e-7]+r+$e[e-16]|0}let{A:n,B:r,C:o,D:s,E:i,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(Ae(i,6)^Ae(i,11)^Ae(i,25))+ve(i,a,c)+Ge[e]+$e[e]|0,l=(Ae(n,2)^Ae(n,13)^Ae(n,22))+Te(n,r,o)|0;u=c,c=a,a=i,i=s+t|0,s=o,o=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,s,i,a,c,u)}roundClean(){ye($e)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ye(this.buffer)}}class Ke extends Xe{A=0|ke[0];B=0|ke[1];C=0|ke[2];D=0|ke[3];E=0|ke[4];F=0|ke[5];G=0|ke[6];H=0|ke[7];constructor(){super(32)}}const We=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:i}=xe(e[s],t);[r[s],o[s]]=[n,i]}return[r,o]}(["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))))(),Ze=(()=>We[0])(),ze=(()=>We[1])(),je=new Uint32Array(80),Ye=new Uint32Array(80);class Je extends Ee{constructor(e){super(128,e,16,!1)}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:s,Dh:i,Dl:a,Eh:c,El:u,Fh:l,Fl:d,Gh:p,Gl:h,Hh:f,Hl:m}=this;return[e,t,n,r,o,s,i,a,c,u,l,d,p,h,f,m]}set(e,t,n,r,o,s,i,a,c,u,l,d,p,h,f,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|s,this.Dh=0|i,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|d,this.Gh=0|p,this.Gl=0|h,this.Hh=0|f,this.Hl=0|m}process(e,t){for(let n=0;n<16;n++,t+=4)je[n]=e.getUint32(t),Ye[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|je[e-15],n=0|Ye[e-15],r=Pe(t,n,1)^Pe(t,n,8)^Re(t,0,7),o=Oe(t,n,1)^Oe(t,n,8)^_e(t,n,7),s=0|je[e-2],i=0|Ye[e-2],a=Pe(s,i,19)^Ue(s,i,61)^Re(s,0,6),c=Oe(s,i,19)^Le(s,i,61)^_e(s,i,6),u=De(o,c,Ye[e-7],Ye[e-16]),l=Me(u,r,a,je[e-7],je[e-16]);je[e]=0|l,Ye[e]=0|u}let{Ah:n,Al:r,Bh:o,Bl:s,Ch:i,Cl:a,Dh:c,Dl:u,Eh:l,El:d,Fh:p,Fl:h,Gh:f,Gl:m,Hh:g,Hl:y}=this;for(let e=0;e<80;e++){const t=Pe(l,d,14)^Pe(l,d,18)^Ue(l,d,41),w=Oe(l,d,14)^Oe(l,d,18)^Le(l,d,41),A=l&p^~l&f,S=qe(y,w,d&h^~d&m,ze[e],Ye[e]),b=He(S,g,t,A,Ze[e],je[e]),v=0|S,T=Pe(n,r,28)^Ue(n,r,34)^Ue(n,r,39),E=Oe(n,r,28)^Le(n,r,34)^Le(n,r,39),k=n&o^n&i^o&i,I=r&s^r&a^s&a;g=0|f,y=0|m,f=0|p,m=0|h,p=0|l,h=0|d,({h:l,l:d}=Ne(0|c,0|u,0|b,0|v)),c=0|i,u=0|a,i=0|o,a=0|s,o=0|n,s=0|r;const C=Ve(v,E,I);n=Fe(C,b,T,k),r=0|C}({h:n,l:r}=Ne(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:s}=Ne(0|this.Bh,0|this.Bl,0|o,0|s)),({h:i,l:a}=Ne(0|this.Ch,0|this.Cl,0|i,0|a)),({h:c,l:u}=Ne(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:d}=Ne(0|this.Eh,0|this.El,0|l,0|d)),({h:p,l:h}=Ne(0|this.Fh,0|this.Fl,0|p,0|h)),({h:f,l:m}=Ne(0|this.Gh,0|this.Gl,0|f,0|m)),({h:g,l:y}=Ne(0|this.Hh,0|this.Hl,0|g,0|y)),this.set(n,r,o,s,i,a,c,u,l,d,p,h,f,m,g,y)}roundClean(){ye(je,Ye)}destroy(){this.destroyed=!0,ye(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Qe extends Je{Ah=0|Ie[0];Al=0|Ie[1];Bh=0|Ie[2];Bl=0|Ie[3];Ch=0|Ie[4];Cl=0|Ie[5];Dh=0|Ie[6];Dl=0|Ie[7];Eh=0|Ie[8];El=0|Ie[9];Fh=0|Ie[10];Fl=0|Ie[11];Gh=0|Ie[12];Gl=0|Ie[13];Hh=0|Ie[14];Hl=0|Ie[15];constructor(){super(64)}}const et=Se(()=>new Ke,be(1)),tt=Se(()=>new Qe,be(3));function nt(e){const t="string"==typeof e?fe.Buffer.from(e,"utf8"):e;return fe.Buffer.from(et(t))}
|
|
199
|
-
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const rt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ot,n:st,Gx:it,Gy:at,a:ct,d:ut,h:lt}=rt,dt=32,pt=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,pt),t},ht=(e,t,n="")=>{const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name&&"BYTES_PER_ELEMENT"in o&&1===o.BYTES_PER_ELEMENT;var o;const s=e?.length,i=void 0!==t;if(!r||i&&s!==t){const o=(n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${s}`:"type="+typeof e);throw r?new RangeError(o):new TypeError(o)}return e},ft=e=>new Uint8Array(e),mt=e=>Uint8Array.from(e),gt=(e,t)=>e.toString(16).padStart(t,"0"),yt=e=>Array.from(ht(e)).map(e=>gt(e,2)).join(""),wt=48,At=57,St=65,bt=70,vt=97,Tt=102,Et=e=>e>=wt&&e<=At?e-wt:e>=St&&e<=bt?e-(St-10):e>=vt&&e<=Tt?e-(vt-10):void 0,kt=e=>{const t="hex invalid";if("string"!=typeof e)return pt(t);const n=e.length,r=n/2;if(n%2)return pt(t);const o=ft(r);for(let n=0,s=0;n<r;n++,s+=2){const r=Et(e.charCodeAt(s)),i=Et(e.charCodeAt(s+1));if(void 0===r||void 0===i)return pt(t);o[n]=16*r+i}return o},It=()=>globalThis?.crypto,Ct=(...e)=>{let t=0;for(const n of e)t+=ht(n).length;const n=ft(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n},Bt=BigInt,xt=(e,t,n,r="bad number: out of range")=>{if(!(e=>"bigint"==typeof e)(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Rt=(e,t=ot)=>{const n=e%t;return n>=0n?n:t+n},_t=(1n<<255n)-1n,Pt=e=>{e<0n&&pt("negative coordinate");let t=19n*(e>>255n)+(e&_t);return t=19n*(t>>255n)+(t&_t),t%ot},Ot=e=>Rt(e,st),Ut=e=>{const t=en[e];return"function"!=typeof t&&pt("hashes."+e+" not set"),t},Lt=e=>ht(e,64,"digest"),Nt=e=>e instanceof Ft?e:pt("Point expected"),Vt=2n**256n;class Ft{static BASE;static ZERO;X;Y;Z;T;constructor(e,t,n,r){const o=Vt;this.X=xt(e,0n,o),this.Y=xt(t,0n,o),this.Z=xt(n,1n,o),this.T=xt(r,0n,o),Object.freeze(this)}static CURVE(){return rt}static fromAffine(e){return new Ft(e.x,e.y,1n,Pt(e.x*e.y))}static fromBytes(e,t=!1){const n=ut,r=mt(ht(e,dt)),o=e[31];r[31]=-129&o;const s=Ht(r);xt(s,0n,t?Vt:ot);const i=Pt(s*s),a=Rt(i-1n),c=Pt(n*i+1n);let{isValid:u,value:l}=Xt(a,c);u||pt("bad point: y not sqrt");const d=1n==(1n&l),p=!!(128&o);return!t&&0n===l&&p&&pt("bad point: x==0, isLastByteOdd"),p!==d&&(l=Rt(-l)),new Ft(l,s,1n,Pt(l*s))}static fromHex(e,t){return Ft.fromBytes(kt(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const e=ct,t=ut;if(this.is0())return pt("bad point: ZERO");const{X:n,Y:r,Z:o,T:s}=this,i=Pt(n*n),a=Pt(r*r),c=Pt(o*o),u=Pt(c*c),l=Pt(i*e);if(Pt(c*(l+a))!==Rt(u+Pt(t*Pt(i*a))))return pt("bad point: equation left != right (1)");return Pt(n*r)!==Pt(o*s)?pt("bad point: equation left != right (2)"):this}equals(e){const{X:t,Y:n,Z:r}=this,{X:o,Y:s,Z:i}=Nt(e),a=Pt(t*i),c=Pt(o*r),u=Pt(n*i),l=Pt(s*r);return a===c&&u===l}is0(){return this.equals(Mt)}negate(){return new Ft(Rt(-this.X),this.Y,this.Z,Rt(-this.T))}double(){const{X:e,Y:t,Z:n}=this,r=ct,o=Pt(e*e),s=Pt(t*t),i=Pt(2n*n*n),a=Pt(r*o),c=Rt(e+t),u=Rt(Pt(c*c)-o-s),l=Rt(a+s),d=Rt(l-i),p=Rt(a-s),h=Pt(u*d),f=Pt(l*p),m=Pt(u*p),g=Pt(d*l);return new Ft(h,f,g,m)}add(e){const{X:t,Y:n,Z:r,T:o}=this,{X:s,Y:i,Z:a,T:c}=Nt(e),u=ct,l=ut,d=Pt(t*s),p=Pt(n*i),h=Pt(Pt(o*l)*c),f=Pt(r*a),m=Rt(Pt(Rt(t+n)*Rt(s+i))-d-p),g=Rt(f-h),y=Rt(f+h),w=Rt(p-Pt(u*d)),A=Pt(m*g),S=Pt(y*w),b=Pt(m*w),v=Pt(g*y);return new Ft(A,S,v,b)}subtract(e){return this.add(Nt(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return Mt;if(xt(e,1n,st),!t&&this.is0())return Mt;if(1n===e)return this;if(this.equals(Dt))return sn(e).p;let n=Mt,r=Dt;for(let o=this;e>0n;o=o.double(),e>>=1n)1n&e?n=n.add(o):t&&(r=r.add(o));return n}multiplyUnsafe(e){return this.multiply(e,!1)}toAffine(){const{X:e,Y:t,Z:n}=this;if(this.equals(Mt))return{x:0n,y:1n};const r=((e,t)=>{(0n===e||t<=0n)&&pt("no inverse n="+e+" mod="+t);let n=Rt(e,t),r=t,o=0n,s=1n;for(;0n!==n;){const e=r%n,t=o-s*(r/n);r=n,n=e,o=s,s=t}return 1n===r?Rt(o,t):pt("no inverse")})(n,ot);1n!==Pt(n*r)&&pt("invalid inverse");return{x:Pt(e*r),y:Pt(t*r)}}toBytes(){const{x:e,y:t}=this.toAffine(),n=qt(t);return n[31]|=1n&e?128:0,n}toHex(){return yt(this.toBytes())}clearCofactor(){return this.multiply(Bt(lt),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.multiply(st/2n,!1).double();return st%2n&&(e=e.add(this)),e.is0()}}const Dt=new Ft(it,at,1n,Rt(it*at)),Mt=new Ft(0n,1n,1n,0n);Ft.BASE=Dt,Ft.ZERO=Mt;const qt=e=>kt(gt(xt(e,0n,Vt),64)).reverse(),Ht=e=>Bt("0x"+yt(mt(ht(e)).reverse())),Gt=(e,t)=>{let n=e;for(;t-- >0n;)n=Pt(n*n);return n},$t=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Xt=(e,t)=>{const n=Pt(t*Pt(t*t)),r=Pt(Pt(n*n)*t),o=(e=>{const t=Pt(e*e),n=Pt(t*e),r=Pt(Gt(n,2n)*n),o=Pt(Gt(r,1n)*e),s=Pt(Gt(o,5n)*o),i=Pt(Gt(s,10n)*s),a=Pt(Gt(i,20n)*i),c=Pt(Gt(a,40n)*a),u=Pt(Gt(c,80n)*c),l=Pt(Gt(u,80n)*c),d=Pt(Gt(l,10n)*s);return{pow_p_5_8:Pt(Gt(d,2n)*e),b2:n}})(Pt(e*r)).pow_p_5_8;let s=Pt(e*Pt(n*o));const i=Pt(t*Pt(s*s)),a=s,c=Pt(s*$t),u=i===e,l=i===Rt(-e),d=i===Rt(-e*$t);return u&&(s=a),(l||d)&&(s=c),1n==(1n&Rt(s))&&(s=Rt(-s)),{isValid:u||l,value:s}},Kt=e=>Ot(Ht(e)),Wt=(...e)=>Lt(Ut("sha512")(Ct(...e))),Zt=e=>{const t=mt(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;const r=t.slice(32,64),o=Kt(n),s=Dt.multiply(o),i=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:i}},zt=e=>Zt(Wt(ht(e,dt))),jt=e=>e.finish(Wt(e.hashable)),Yt=(e,t)=>{const n=ht(e),r=zt(t),o=Wt(r.prefix,n);return jt(((e,t,n)=>{const{pointBytes:r,scalar:o}=e,s=Kt(t),i=Dt.multiply(s).toBytes();return{hashable:Ct(i,r,n),finish:e=>{const t=Ot(s+Kt(e)*o);return ht(Ct(i,qt(t)),64)}}})(r,o,n))},Jt={zip215:!0},Qt=(e,t,n,r=Jt)=>jt(((e,t,n,r=Jt)=>{e=ht(e,64),t=ht(t),n=ht(n,dt);const{zip215:o=!0}=r,s=e.subarray(0,dt),i=Ht(e.subarray(dt,64));let a,c,u,l=Uint8Array.of(),d=!1;try{a=Ft.fromBytes(n,o),c=Ft.fromBytes(s,o),u=Dt.multiply(i,!1),l=Ct(s,n,t),d=!0}catch(e){}return{hashable:l,finish:e=>{if(!d)return!1;if(!o&&a.isSmallOrder())return!1;const t=Kt(e);return c.add(a.multiply(t,!1)).subtract(u).clearCofactor().is0()}}})(e,t,n,r)),en={sha512Async:async e=>{const t=It()?.subtle??pt("crypto.subtle must be defined, consider polyfill"),n=Ct(e);return ft(await t.digest("SHA-512",n.buffer))},sha512:void 0},tn=Object.freeze({getExtendedPublicKeyAsync:e=>((...e)=>Promise.resolve(Ut("sha512Async")(Ct(...e))).then(Lt))(ht(e,dt)).then(Zt),getExtendedPublicKey:zt,randomSecretKey:e=>(e=void 0===e?((e=dt)=>It().getRandomValues(ft(e)))(dt):e,ht(e,dt))}),nn=Math.ceil(32)+1;let rn;const on=(e,t)=>{const n=t.negate();return e?n:t},sn=e=>{const t=rn||(rn=(()=>{const e=[];let t=Dt,n=t;for(let r=0;r<nn;r++){n=t,e.push(n);for(let r=1;r<128;r++)n=n.add(t),e.push(n);t=n.double()}return e})());let n=Mt,r=Dt;const o=Bt(255),s=Bt(8);for(let i=0;i<nn;i++){let a=Number(e&o);e>>=s,a>128&&(a-=256,e+=1n);const c=128*i,u=c,l=c+Math.abs(a)-1,d=i%2!=0,p=a<0;0===a?r=r.add(on(d,t[u])):n=n.add(on(p,t[l]))}return 0n!==e&&pt("invalid wnaf"),{p:n,f:r}};function an(e){return fe.Buffer.from(zt(e).pointBytes)}function cn(e,t){return fe.Buffer.from(Yt(fe.Buffer.from(e),t))}function un(e,t,n){return Qt(fe.Buffer.from(t),fe.Buffer.from(e),fe.Buffer.from(n),{zip215:!1})}en.sha512=tt;const ln=(e,t)=>{const n="number"==typeof e;let r=String(e);for(;r.endsWith(t);)r=r.slice(0,-1);return n?Number(r):r};var dn,pn={};var hn=(dn||(dn=1,function(e){var t=function(e,t){return t||(t={}),e.split("").forEach(function(e,n){e in t||(t[e]=n)}),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=t(n.alphabet,n.charmap);var r={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};r.charmap=t(r.alphabet,r.charmap);var o={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function s(t){if(this.buf=[],this.shift=8,this.carry=0,t){switch(t.type){case"rfc4648":this.charmap=e.rfc4648.charmap;break;case"crockford":this.charmap=e.crockford.charmap;break;case"base32hex":this.charmap=e.base32hex.charmap;break;default:throw new Error("invalid type")}t.charmap&&(this.charmap=t.charmap)}}function i(t){if(this.buf="",this.shift=3,this.carry=0,t){switch(t.type){case"rfc4648":this.alphabet=e.rfc4648.alphabet;break;case"crockford":this.alphabet=e.crockford.alphabet;break;case"base32hex":this.alphabet=e.base32hex.alphabet;break;default:throw new Error("invalid type")}t.alphabet?this.alphabet=t.alphabet:t.lc&&(this.alphabet=this.alphabet.toLowerCase())}}o.charmap=t(o.alphabet,o.charmap),s.prototype.charmap=n.charmap,s.prototype.write=function(e){var t=this.charmap,n=this.buf,r=this.shift,o=this.carry;return e.toUpperCase().split("").forEach(function(e){if("="!=e){var s=255&t[e];(r-=5)>0?o|=s<<r:r<0?(n.push(o|s>>-r),o=s<<(r+=8)&255):(n.push(o|s),r=8,o=0)}}),this.shift=r,this.carry=o,this},s.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},i.prototype.alphabet=n.alphabet,i.prototype.write=function(e){var t,n,r,o=this.shift,s=this.carry;for(r=0;r<e.length;r++)t=s|(n=e[r])>>o,this.buf+=this.alphabet[31&t],o>5&&(t=n>>(o-=5),this.buf+=this.alphabet[31&t]),s=n<<(o=5-o),o=8-o;return this.shift=o,this.carry=s,this},i.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},e.encode=function(e,t){return new i(t).finalize(e)},e.decode=function(e,t){return new s(t).finalize(e)},e.Decoder=s,e.Encoder=i,e.charmap=t,e.crockford=r,e.rfc4648=n,e.base32hex=o}(pn)),pn),fn=te(hn);const mn={ed25519PublicKey:48,ed25519SecretSeed:144,med25519PublicKey:96,preAuthTx:152,sha256Hash:184,signedPayload:120,contract:16,liquidityPool:88,claimableBalance:8},gn={G:"ed25519PublicKey",S:"ed25519SecretSeed",M:"med25519PublicKey",T:"preAuthTx",X:"sha256Hash",P:"signedPayload",C:"contract",L:"liquidityPool",B:"claimableBalance"};function yn(e){return Object.prototype.hasOwnProperty.call(mn,e)}class wn{static types=gn;static encodeEd25519PublicKey(e){return bn("ed25519PublicKey",e)}static decodeEd25519PublicKey(e){return Sn("ed25519PublicKey",e)}static isValidEd25519PublicKey(e){return An("ed25519PublicKey",e)}static encodeEd25519SecretSeed(e){return bn("ed25519SecretSeed",e)}static decodeEd25519SecretSeed(e){return Sn("ed25519SecretSeed",e)}static isValidEd25519SecretSeed(e){return An("ed25519SecretSeed",e)}static encodeMed25519PublicKey(e){return bn("med25519PublicKey",e)}static decodeMed25519PublicKey(e){return Sn("med25519PublicKey",e)}static isValidMed25519PublicKey(e){return An("med25519PublicKey",e)}static encodePreAuthTx(e){return bn("preAuthTx",e)}static decodePreAuthTx(e){return Sn("preAuthTx",e)}static encodeSha256Hash(e){return bn("sha256Hash",e)}static decodeSha256Hash(e){return Sn("sha256Hash",e)}static encodeSignedPayload(e){return bn("signedPayload",e)}static decodeSignedPayload(e){return Sn("signedPayload",e)}static isValidSignedPayload(e){return An("signedPayload",e)}static encodeContract(e){return bn("contract",e)}static decodeContract(e){return Sn("contract",e)}static isValidContract(e){return An("contract",e)}static encodeClaimableBalance(e){return bn("claimableBalance",e)}static decodeClaimableBalance(e){return Sn("claimableBalance",e)}static isValidClaimableBalance(e){return An("claimableBalance",e)}static encodeLiquidityPool(e){return bn("liquidityPool",e)}static decodeLiquidityPool(e){return Sn("liquidityPool",e)}static isValidLiquidityPool(e){return An("liquidityPool",e)}static getVersionByteForPrefix(e){if(e.length<1)return;const t=e[0];return gn[t]}}function An(e,t){if("string"!=typeof t)return!1;switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":case"liquidityPool":if(56!==t.length)return!1;break;case"claimableBalance":if(58!==t.length)return!1;break;case"med25519PublicKey":if(69!==t.length)return!1;break;case"signedPayload":if(t.length<56||t.length>165)return!1;break;default:return!1}let n;try{n=Sn(e,t)}catch{return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":case"liquidityPool":return 32===n.length;case"claimableBalance":return 33===n.length;case"med25519PublicKey":return 40===n.length;case"signedPayload":return n.length>=40&&n.length<=100;default:return!1}}function Sn(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");const n=fn.decode(t),r=n[0],o=n.slice(0,-2),s=o.slice(1),i=n.slice(-2);if(t!==fn.encode(n))throw new Error("invalid encoded string");if(!yn(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(mn).join(", ")}`);const a=mn[e];if(r!==a)throw new Error(`invalid version byte. expected ${a}, got ${r}`);if(!function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}(vn(o),i))throw new Error("invalid checksum");return fe.Buffer.from(s)}function bn(e,t){if(null==t)throw new Error("cannot encode null data");if(!yn(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(mn).join(", ")}`);const n=mn[e];t=fe.Buffer.from(t);const r=fe.Buffer.from([n]),o=fe.Buffer.concat([r,t]),s=fe.Buffer.from(vn(o)),i=fe.Buffer.concat([o,s]);return fn.encode(i)}function vn(e){const t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920];let n=0;for(let r=0;r<e.length;r+=1){const o=e[r];if(void 0===o)continue;n=n<<8^(t[n>>8^o]??0),n&=65535}const r=new Uint8Array(2);return r[0]=255&n,r[1]=n>>8&255,r}en.sha512=tt;class Tn{type;_publicKey;_secretSeed;_secretKey;constructor(e){if("ed25519"!==e.type)throw new Error("Invalid keys type");if(this.type=e.type,"secretKey"in e){if(e.secretKey=fe.Buffer.from(e.secretKey),32!==e.secretKey.length)throw new Error("secretKey length is invalid");if(this._secretSeed=e.secretKey,this._publicKey=an(e.secretKey),this._secretKey=e.secretKey,e.publicKey&&!this._publicKey.equals(fe.Buffer.from(e.publicKey)))throw new Error("secretKey does not match publicKey")}else{if(!("publicKey"in e))throw new Error("At least one of publicKey or secretKey must be provided");if(this._publicKey=fe.Buffer.from(e.publicKey),32!==this._publicKey.length)throw new Error("publicKey length is invalid")}}static fromSecret(e){const t=wn.decodeEd25519SecretSeed(e);return this.fromRawEd25519Seed(t)}static fromRawEd25519Seed(e){return new this({type:"ed25519",secretKey:e})}static master(e){if(!e)throw new Error("No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.");return this.fromRawEd25519Seed(nt(e))}static fromPublicKey(e){const t=wn.decodeEd25519PublicKey(e);if(32!==t.length)throw new Error("Invalid Stellar public key");return new this({type:"ed25519",publicKey:t})}static random(){const e=tn.randomSecretKey();return this.fromRawEd25519Seed(fe.Buffer.from(e))}xdrAccountId(){return se.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrPublicKey(){return se.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrMuxedAccount(e){if(void 0!==e){if("string"!=typeof e)throw new TypeError("expected string for ID, got "+typeof e);return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromString(e),ed25519:this._publicKey}))}return se.MuxedAccount.keyTypeEd25519(this._publicKey)}rawPublicKey(){return this._publicKey}signatureHint(){const e=this.xdrAccountId().toXDR();return e.subarray(e.length-4)}publicKey(){return wn.encodeEd25519PublicKey(this._publicKey)}secret(){if(!this._secretSeed)throw new Error("no secret key available");if("ed25519"===this.type)return wn.encodeEd25519SecretSeed(this._secretSeed);throw new Error("Invalid Keypair type")}rawSecretKey(){if(!this._secretSeed)throw new Error("no secret seed available");return this._secretSeed}canSign(){return!!this._secretKey}sign(e){if(!this._secretKey)throw new Error("cannot sign: no secret key available");return cn(e,this._secretKey)}verify(e,t){try{return un(e,t,this._publicKey)}catch{return!1}}signDecorated(e){const t=this.sign(e),n=this.signatureHint();return new se.DecoratedSignature({hint:n,signature:t})}signPayloadDecorated(e){const t=fe.Buffer.isBuffer(e)?e:fe.Buffer.from(e),n=this.sign(t),r=this.signatureHint();let o=fe.Buffer.from(t.subarray(-4));o.length<4&&(o=fe.Buffer.concat([o,fe.Buffer.alloc(4-o.length,0)]));for(let e=0;e<o.length;e++)o[e]=o[e]^r[e];return new se.DecoratedSignature({hint:o,signature:n})}}const En={native:"native",credit4:"credit_alphanum4",credit12:"credit_alphanum12",liquidityPoolShares:"liquidity_pool_shares"};function kn(e,t){return fe.Buffer.compare(fe.Buffer.from(e,"ascii"),fe.Buffer.from(t,"ascii"))}class In{code;issuer;constructor(e,t){if(!/^[a-zA-Z0-9]{1,12}$/.test(e))throw new Error("Asset code is invalid (maximum alphanumeric, 12 characters at max)");if("xlm"!==String(e).toLowerCase()&&!t)throw new Error("Issuer cannot be null");if(t&&!wn.isValidEd25519PublicKey(t))throw new Error("Issuer is invalid");"xlm"===String(e).toLowerCase()?this.code="XLM":this.code=e,this.issuer=t}static native(){return new In("XLM")}static fromOperation(e){let t,n,r;switch(e.switch()){case se.AssetType.assetTypeNative():return this.native();case se.AssetType.assetTypeCreditAlphanum4():return t=e.alphaNum4(),r=wn.encodeEd25519PublicKey(t.issuer().ed25519()),n=ln(t.assetCode().toString(),"\0"),new this(n,r);case se.AssetType.assetTypeCreditAlphanum12():return t=e.alphaNum12(),r=wn.encodeEd25519PublicKey(t.issuer().ed25519()),n=ln(t.assetCode().toString(),"\0"),new this(n,r);default:throw new Error(`Invalid asset type: ${e.switch().name}`)}}toXDRObject(){return this._toXDRObject(se.Asset)}toChangeTrustXDRObject(){return this._toXDRObject(se.ChangeTrustAsset)}toTrustLineXDRObject(){return this._toXDRObject(se.TrustLineAsset)}contractId(e){const t=nt(fe.Buffer.from(e)),n=se.HashIdPreimage.envelopeTypeContractId(new se.HashIdPreimageContractId({networkId:t,contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject())}));return wn.encodeContract(nt(n.toXDR()))}_toXDRObject(e){if(this.isNative())return e.assetTypeNative();if(!this.issuer)throw new Error("Issuer cannot be null for non-native asset");let t,n;this.code.length<=4?(t=se.AlphaNum4,n="assetTypeCreditAlphanum4"):(t=se.AlphaNum12,n="assetTypeCreditAlphanum12");const r=this.code.length<=4?4:12;return new e(n,new t({assetCode:this.code.padEnd(r,"\0"),issuer:Tn.fromPublicKey(this.issuer).xdrAccountId()}))}getCode(){return String(this.code)}getIssuer(){if(void 0!==this.issuer)return String(this.issuer)}getAssetType(){switch(this.getRawAssetType().value){case se.AssetType.assetTypeNative().value:return En.native;case se.AssetType.assetTypeCreditAlphanum4().value:return En.credit4;case se.AssetType.assetTypeCreditAlphanum12().value:return En.credit12;default:throw new Error("Supported asset types are: native, credit_alphanum4, credit_alphanum12")}}getRawAssetType(){return this.isNative()?se.AssetType.assetTypeNative():this.code.length<=4?se.AssetType.assetTypeCreditAlphanum4():se.AssetType.assetTypeCreditAlphanum12()}isNative(){return!this.issuer}equals(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}toString(){return this.isNative()?"native":`${this.getCode()}:${this.getIssuer()}`}static compare(e,t){if(!(e&&e instanceof In))throw new Error("assetA is invalid");if(!(t&&t instanceof In))throw new Error("assetB is invalid");if(e.equals(t))return 0;const n=e.getRawAssetType().value,r=t.getRawAssetType().value;if(n!==r)return n<r?-1:1;const o=kn(e.getCode(),t.getCode());if(0!==o)return o;const s=e.getIssuer(),i=t.getIssuer();if(void 0===s||void 0===i)throw new Error("Issuer is undefined for non-native asset");return kn(s,i)}}function Cn(e,t){if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");const{assetA:n,assetB:r,fee:o}=t??{};if(!(n&&n instanceof In))throw new Error("assetA is invalid");if(!(r&&r instanceof In))throw new Error("assetB is invalid");if(!o||30!==o)throw new Error("fee is invalid");if(-1!==In.compare(n,r))throw new Error("Assets are not in lexicographic order");return nt(se.LiquidityPoolParameters.liquidityPoolConstantProduct(new se.LiquidityPoolConstantProductParameters({assetA:n.toXDRObject(),assetB:r.toXDRObject(),fee:o})).toXDR())}class Bn{_tx;_signatures;_fee;_networkPassphrase;constructor(e,t,n,r){if("string"!=typeof r)throw new Error("Invalid passphrase provided to Transaction: expected a string but got a "+typeof r);this._networkPassphrase=r,this._tx=e,this._signatures=t,this._fee=n}get signatures(){return this._signatures}set signatures(e){throw new Error("Transaction is immutable")}get tx(){const e=this._tx.toXDR();if(this._tx instanceof se.Transaction)return se.Transaction.fromXDR(e);if(this._tx instanceof se.TransactionV0)return se.TransactionV0.fromXDR(e);if(this._tx instanceof se.FeeBumpTransaction)return se.FeeBumpTransaction.fromXDR(e);throw new Error("Unknown transaction type")}set tx(e){throw new Error("Transaction is immutable")}get fee(){return this._fee}set fee(e){throw new Error("Transaction is immutable")}get networkPassphrase(){return this._networkPassphrase}set networkPassphrase(e){throw new Error("Transaction is immutable")}sign(...e){const t=this.hash();e.forEach(e=>{const n=e.signDecorated(t);this.signatures.push(n)})}getKeypairSignature(e){return e.sign(this.hash()).toString("base64")}addSignature(e="",t=""){if(!t||"string"!=typeof t)throw new Error("Invalid signature");if(!e||"string"!=typeof e)throw new Error("Invalid publicKey");let n,r;const o=fe.Buffer.from(t,"base64");try{n=Tn.fromPublicKey(e),r=n.signatureHint()}catch{throw new Error("Invalid publicKey")}if(!n.verify(this.hash(),o))throw new Error("Invalid signature");this.signatures.push(new se.DecoratedSignature({hint:r,signature:o}))}addDecoratedSignature(e){this.signatures.push(e)}signHashX(e){if("string"==typeof e&&(e=fe.Buffer.from(e,"hex")),e.length>64)throw new Error("preimage cannot be longer than 64 bytes");const t=e,n=nt(e),r=n.subarray(n.length-4);this.signatures.push(new se.DecoratedSignature({hint:r,signature:t}))}hash(){return nt(this.signatureBase())}signatureBase(){throw new Error("Implement in subclass")}toEnvelope(){throw new Error("Implement in subclass")}toXDR(){return this.toEnvelope().toXDR().toString("base64")}}class xn{assetA;assetB;fee;constructor(e,t,n){if(!(e&&e instanceof In))throw new Error("assetA is invalid");if(!(t&&t instanceof In))throw new Error("assetB is invalid");if(-1!==In.compare(e,t))throw new Error("Assets are not in lexicographic order");if(!n||30!==n)throw new Error("fee is invalid");this.assetA=e,this.assetB=t,this.fee=n}static fromOperation(e){const t=e.switch();if(t===se.AssetType.assetTypePoolShare()){const t=e.liquidityPool().constantProduct();return new this(In.fromOperation(t.assetA()),In.fromOperation(t.assetB()),t.fee())}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=new se.LiquidityPoolConstantProductParameters({assetA:this.assetA.toXDRObject(),assetB:this.assetB.toXDRObject(),fee:this.fee}),t=se.LiquidityPoolParameters.liquidityPoolConstantProduct(e);return se.ChangeTrustAsset.assetTypePoolShare(t)}getLiquidityPoolParameters(){return{...this,assetA:this.assetA,assetB:this.assetB,fee:this.fee}}getAssetType(){return"liquidity_pool_shares"}equals(e){return this.assetA.equals(e.assetA)&&this.assetB.equals(e.assetB)&&this.fee===e.fee}toString(){return`liquidity_pool:${Cn("constant_product",this.getLiquidityPoolParameters()).toString("hex")}`}}class Rn{_destination;_predicate;constructor(e,t){if(!wn.isValidEd25519PublicKey(e))throw new Error("Destination is invalid");if(this._destination=e,t){if(!(t instanceof se.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");this._predicate=t}else this._predicate=se.ClaimPredicate.claimPredicateUnconditional()}static predicateUnconditional(){return se.ClaimPredicate.claimPredicateUnconditional()}static predicateAnd(e,t){if(!(e instanceof se.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof se.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateAnd([e,t])}static predicateOr(e,t){if(!(e instanceof se.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof se.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateOr([e,t])}static predicateNot(e){if(!(e instanceof se.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateNot(e)}static predicateBeforeAbsoluteTime(e){return se.ClaimPredicate.claimPredicateBeforeAbsoluteTime(se.Int64.fromString(e))}static predicateBeforeRelativeTime(e){return se.ClaimPredicate.claimPredicateBeforeRelativeTime(se.Int64.fromString(e))}static fromXDR(e){let t;if(e.switch()===se.ClaimantType.claimantTypeV0())return t=e.v0(),new this(wn.encodeEd25519PublicKey(t.destination().ed25519()),t.predicate());throw new Error(`Invalid claimant type: ${e.switch().name}`)}toXDRObject(){const e=new se.ClaimantV0({destination:Tn.fromPublicKey(this._destination).xdrAccountId(),predicate:this._predicate});return se.Claimant.claimantTypeV0(e)}get destination(){return this._destination}set destination(e){throw new Error("Claimant is immutable")}get predicate(){return this._predicate}set predicate(e){throw new Error("Claimant is immutable")}}class _n{liquidityPoolId;constructor(e){if(!e)throw new Error("liquidityPoolId cannot be empty");if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Liquidity pool ID is not a valid hash");this.liquidityPoolId=e}static fromOperation(e){const t=e.switch();if(t===se.AssetType.assetTypePoolShare()){const t=e.liquidityPoolId().toString("hex");return new _n(t)}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=fe.Buffer.from(this.liquidityPoolId,"hex");return se.TrustLineAsset.assetTypePoolShare(e)}getLiquidityPoolId(){return String(this.liquidityPoolId)}getAssetType(){return"liquidity_pool_shares"}equals(e){return this.liquidityPoolId===e.getLiquidityPoolId()}toString(){return`liquidity_pool:${this.liquidityPoolId}`}}function Pn(e){return wn.isValidMed25519PublicKey(e)?function(e){const t=wn.decodeMed25519PublicKey(e);return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):se.MuxedAccount.keyTypeEd25519(wn.decodeEd25519PublicKey(e))}function On(e){return e.switch().value===se.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===se.CryptoKeyType.keyTypeEd25519())return On(e);const t=e.med25519();return wn.encodeMed25519PublicKey(fe.Buffer.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):wn.encodeEd25519PublicKey(e.ed25519())}function Un(e,t){if(!wn.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromString(t),ed25519:wn.decodeEd25519PublicKey(e)}))}function Ln(e){if(wn.isValidEd25519PublicKey(e))return e;if(!wn.isValidMed25519PublicKey(e))throw new TypeError(`expected muxed account (M...), got ${e}`);const t=Pn(e);return wn.encodeEd25519PublicKey(t.med25519().ed25519())}var Nn=function e(t){var n,r,o=/^(-?)0([xbo])(?=[^.])/i,s=/^-?(Infinity|NaN)$/,i=/^\s*\+(?!-)|^\s+|\s+$/g,a=b.prototype={constructor:b,toString:null,valueOf:null},c=new b(1),u=20,l=4,d=-7,p=21,h=-1e7,f=1e7,m=!1,g=!0,y=1,w=0,A={prefix:"",negativeSign:"-",positiveSign:"",groupSeparator:",",groupSize:3,secondaryGroupSize:0,decimalSeparator:".",fractionGroupSeparator:"",fractionGroupSize:0,suffix:""},S="0123456789abcdefghijklmnopqrstuvwxyz";function b(e,t){var n,r,a,c,u=this;if(!(u instanceof b))return new b(e,t);if(c=typeof e,null==t){if(k(e))return u.s=e.s,void(!e.c||e.e>f?u.c=u.e=null:e.e<h?u.c=[u.e=0]:(u.e=e.e,u.c=e.c.slice()));if("number"==c){if(0*e!=0)return u.s=isNaN(e)?null:e<0?-1:1,void(u.c=u.e=null);if(u.s=1/e<0?(e=-e,-1):1,e===~~e){for(n=0,r=e;r>=10;r/=10,n++);return void(n>f?u.c=u.e=null:(u.e=n,u.c=[e]))}return v(u,String(e))}if("bigint"==c)return u.s=e<0?(e=-e,-1):1,v(u,String(e));if("string"==c)a=e;else{if(g)throw Error(Mn+"BigNumber, string, number, or BigInt expected: "+e);a=String(e)}if(Vn.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,v(u,a);if(a=a.replace(i,""),s.test(a))return u.s=isNaN(a)?null:a<0?-1:1,void(u.c=u.e=null);if(a=a.replace(o,function(e,n,r){return t="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n}),t)return T(u,a,t,e);if(a=a.replace(/(\d)_(?=\d)/g,"$1"),Vn.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,v(u,a);if(g)throw Error(Mn+"Not a number: "+e);u.s=u.c=u.e=null}else{if("string"!=c){if(g)throw Error(Mn+"String expected: "+e);e=String(e)}jn(t,2,S.length,"Base"),T(u,e.replace(i,""),t,e)}}function v(e,t){var n,r,o;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;48===t.charCodeAt(r);r++);for(o=t.length;48===t.charCodeAt(--o););if(t=t.slice(r,++o))if(o-=r,(n=n-r-1)>f)e.c=e.e=null;else if(n<h)e.c=[e.e=0];else{if(e.e=n,e.c=[],r=(n+1)%Hn,n<0&&(r+=Hn),r<o){for(r&&e.c.push(+t.slice(0,r)),o-=Hn;r<o;)e.c.push(+t.slice(r,r+=Hn));r=Hn-(t=t.slice(r)).length}else r-=o;for(;r--;t+="0");e.c.push(+t)}else e.c=[e.e=0]}function T(e,t,n,o){var s,i,a=S.slice(0,n),c=0,u="",l=!1,d=!1,p=!1;for(e.s=45===t.charCodeAt(0)?(t=t.slice(1),-1):1,i=t.length;c<i;c++){if(s=t.charAt(c),!(a.indexOf(s)>=0)){if("_"==s){if(d&&c+1<i){d=!1;continue}}else if("."==s){if(0==c||!l&&d){if(c+1==i)break;0==c&&(u="0"),u+=s,l=!0,d=!1;continue}}else if(!p&&(t==t.toUpperCase()&&a==a.toLowerCase()&&(t=t.toLowerCase())||t==t.toLowerCase()&&a==a.toUpperCase()&&(t=t.toUpperCase()))){c=-1,u="",p=!0,l=d=!1;continue}if(g)throw Error(Mn+"Not a base "+n+" number: "+o);return void(e.s=e.c=e.e=null)}u+=s,d=!0}v(e,r(u,n,10,e.s))}function E(e,t,n,r){var o,s,i,a,c;if(n=null==n?l:jn(n,0,8),!e.c)return e.toString();if(o=e.c[0],i=e.e,null==t)c=Zn(e.c),c=1==r||2==r&&(i<=d||i>=p)?Qn(c,i):er(c,i,"0");else if(s=(e=x(new b(e),t,n)).e,a=(c=Zn(e.c)).length,1==r||2==r&&(t<=s||s<=d)){for(;a<t;c+="0",a++);c=Qn(c,s)}else if(t-=i+(2===r&&s>i),c=er(c,s,"0"),s+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=s-a)>0)for(s+1==a&&(c+=".");t--;c+="0");return e.s<0&&o?"-"+c:c}function k(e){return e instanceof b||!!e&&!0===e._isBigNumber}function I(e,t){for(var n,r,o=1,s=new b(e[0]);o<e.length;o++)(!(r=new b(e[o])).s||(n=zn(s,r))===t||0===n&&s.s===t)&&(s=r);return s}function C(e,t,n){for(var r=1,o=t.length;!t[--o];t.pop());for(o=t[0];o>=10;o/=10,r++);return(n=r+n*Hn-1)>f?e.c=e.e=null:n<h?e.c=[e.e=0]:(e.e=n,e.c=t),e}function B(e){var t,n={};for(t in A)A.hasOwnProperty(t)&&(n[t]=e.hasOwnProperty(t)?e[t]:A[t]);return n}function x(e,t,n,r){var o,s,i,a,c,u,l,d=e.c,p=$n;if(d){e:{for(o=1,a=d[0];a>=10;a/=10,o++);if((s=t-o)<0)s+=Hn,i=t,c=d[u=0],l=Dn(c/p[o-i-1]%10);else if((u=Fn((s+1)/Hn))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,o=1,i=(s%=Hn)-Hn+1}else{for(c=a=d[u],o=1;a>=10;a/=10,o++);l=(i=(s%=Hn)-Hn+o)<0?0:Dn(c/p[o-i-1]%10)}if(r=r||t<0||null!=d[u+1]||(i<0?c:c%p[o-i-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(s>0?i>0?c/p[o-i]:0:d[u-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,r?(t-=e.e+1,d[0]=p[(Hn-t%Hn)%Hn],e.e=-t||0):d[0]=e.e=0,e;if(0==s?(d.length=u,a=1,u--):(d.length=u+1,a=p[Hn-s],d[u]=i>0?Dn(c/p[o-i]%p[i])*a:0),r)for(;;){if(0==u){for(s=1,i=d[0];i>=10;i/=10,s++);for(i=d[0]+=a,a=1;i>=10;i/=10,a++);s!=a&&(e.e++,d[0]==qn&&(d[0]=1));break}if(d[u]+=a,d[u]!=qn)break;d[u--]=0,a=1}for(s=d.length;0===d[--s];d.pop());}e.e>f?e.c=e.e=null:e.e<h&&(e.c=[e.e=0])}return e}function R(e){var t,n=e.e;return null===n?e.toString():(t=Zn(e.c),t=n<=d||n>=p?Qn(t,n):er(t,n,"0"),e.s<0?"-"+t:t)}b.clone=e,b.ROUND_UP=0,b.ROUND_DOWN=1,b.ROUND_CEIL=2,b.ROUND_FLOOR=3,b.ROUND_HALF_UP=4,b.ROUND_HALF_DOWN=5,b.ROUND_HALF_EVEN=6,b.ROUND_HALF_CEIL=7,b.ROUND_HALF_FLOOR=8,b.EUCLID=9,b.config=b.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(Mn+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(u=jn(e[t],0,Kn,t)),e.hasOwnProperty(t="ROUNDING_MODE")&&(l=jn(e[t],0,8,t)),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(Yn(n=e[t])?(jn(n[0],-Kn,0,t),jn(n[1],0,Kn,t),d=n[0],p=n[1]):d=-(p=jn(n,-Kn,Kn,t)<0?-n:n)),e.hasOwnProperty(t="RANGE")){if(!(n=e[t]))throw Error(Mn+t+" cannot be zero: "+n);Yn(n)?(jn(n[0],-Kn,-1,t),jn(n[1],1,Kn,t),h=n[0],f=n[1]):h=-(f=jn(n,-Kn,Kn,t)<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(Mn+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw m=!n,Error(Mn+"crypto unavailable");m=n}else m=n}if(e.hasOwnProperty(t="STRICT")){if((n=e[t])!==!!n)throw Error(Mn+t+" not true or false: "+n);g=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(y=jn(e[t],0,9,t)),e.hasOwnProperty(t="POW_PRECISION")&&(w=jn(e[t],0,Kn,t)),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(Mn+t+" not an object: "+n);for(t in n)n.hasOwnProperty(t)&&A.hasOwnProperty(t)&&(A[t]=n[t])}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(Mn+t+" invalid: "+n);S=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,p],RANGE:[h,f],CRYPTO:m,STRICT:g,MODULO_MODE:y,POW_PRECISION:w,FORMAT:A,ALPHABET:S}},b.fromFormat=function(e,t){if("string"!=typeof e)throw Error(Mn+"Not a string: "+e);if(null==t)t=A;else{if("object"!=typeof t)throw Error(Mn+"Argument not an object: "+t);t=B(t)}var n,r,o,s,i=t.negativeSign||"-",a=t.positiveSign||"",c=t.prefix||"",u=t.suffix||"",l=t.groupSeparator||"",d=t.decimalSeparator||".",p=t.fractionGroupSeparator||"";if(c&&0===e.indexOf(c)&&(e=e.slice(c.length)),u&&e.lastIndexOf(u)===e.length-u.length&&(e=e.slice(0,-u.length)),0===e.indexOf(i)?(e=e.slice(i.length),r=!0):a&&0===e.indexOf(a)&&(e=e.slice(a.length)),(n=e.indexOf(d))<0){if(l)for(;e.indexOf(l)>-1;)e=e.replace(l,"")}else{if(o=e.slice(0,n),s=e.slice(n+d.length),l)for(;o.indexOf(l)>-1;)o=o.replace(l,"");if(p)for(;s.indexOf(p)>-1;)s=s.replace(p,"");e=o+"."+s}return new b(r?"-"+e:e)},b.isBigNumber=function(e){if(!k(e))return!1;var t,n,r=e.c,o=e.e,s=e.s;if(!Yn(r))return null===r&&null===o&&(null===s||1===s||-1===s);if(1!==s&&-1!==s||o<-Kn||o>Kn||o!==Dn(o))return!1;if(0===r[0])return 0===o&&1===r.length;if((t=(o+1)%Hn)<1&&(t+=Hn),String(r[0]).length!==t)return!1;for(t=0;t<r.length;t++)if((n=r[t])<0||n>=qn||n!==Dn(n))return!1;return 0!==n},b.maximum=b.max=function(){return I(arguments,-1)},b.minimum=b.min=function(){return I(arguments,1)},b.random=function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return Dn(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var n,r,o,s,i,a=0,l=[],d=new b(c);if(e=null==e?u:jn(e,0,Kn),s=Fn(e/Hn),m)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(s*=2));a<s;)(i=131072*n[a]+(n[a+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),n[a]=r[0],n[a+1]=r[1]):(l.push(i%1e14),a+=2);a=s/2}else{if(!crypto.randomBytes)throw m=!1,Error(Mn+"crypto unavailable");for(n=crypto.randomBytes(s*=7);a<s;)(i=281474976710656*(31&n[a])+1099511627776*n[a+1]+4294967296*n[a+2]+16777216*n[a+3]+(n[a+4]<<16)+(n[a+5]<<8)+n[a+6])>=9e15?crypto.randomBytes(7).copy(n,a):(l.push(i%1e14),a+=7);a=s/7}if(!m)for(;a<s;)(i=t())<9e15&&(l[a++]=i%1e14);for(s=l[--a],e%=Hn,s&&e&&(i=$n[Hn-e],l[a]=Dn(s/i)*i);0===l[a];l.pop(),a--);if(a<0)l=[o=0];else{for(o=-1;0===l[0];l.splice(0,1),o-=Hn);for(a=1,i=l[0];i>=10;i/=10,a++);a<Hn&&(o-=Hn-a)}return d.e=o,d.c=l,d}}(),b.sum=function(){for(var e=0,t=new b(0);e<arguments.length;)t=t.plus(arguments[e++]);return t},r=function(){var e="0123456789";function t(e,t,n,r){for(var o,s,i=[0],a=0,c=e.length;a<c;){for(s=i.length;s--;i[s]*=t);for(i[0]+=r.indexOf(e.charAt(a++)),o=0;o<i.length;o++)i[o]>n-1&&(null==i[o+1]&&(i[o+1]=0),i[o+1]+=i[o]/n|0,i[o]%=n)}return i.reverse()}return function(r,o,s,i,a){var c,d,p,h,f,m,g,y,A=r.indexOf("."),v=u,T=l;for(A>=0&&(h=w,w=0,r=r.replace(".",""),m=(y=new b(o)).pow(r.length-A),w=h,y.c=t(er(Zn(m.c),m.e,"0"),10,s,e),y.e=y.c.length),p=h=(g=t(r,o,s,a?(c=S,e):(c=e,S))).length;0==g[--h];g.pop());if(!g[0])return c.charAt(0);if(A<0?--p:(m.c=g,m.e=p,m.s=i,g=(m=n(m,y,v,T,s)).c,f=m.r,p=m.e),A=g[d=p+v+1],h=s/2,f=f||d<0||null!=g[d+1],f=T<4?(null!=A||f)&&(0==T||T==(m.s<0?3:2)):A>h||A==h&&(4==T||f||6==T&&1&g[d-1]||T==(m.s<0?8:7)),d<1||!g[0])r=f?er(c.charAt(1),-v,c.charAt(0)):c.charAt(0);else{if(d<g.length&&(g.length=d),f)for(--s;++g[--d]>s;)g[d]=0,d||(++p,g=[1].concat(g));for(h=g.length;!g[--h];);for(A=0,r="";A<=h;r+=c.charAt(g[A++]));r=er(r,p,c.charAt(0))}return r}}(),n=function(){function e(e,t,n){var r,o,s,i,a=0,c=e.length,u=t%Xn,l=t/Xn|0;for(e=e.slice();c--;)a=((o=u*(s=e[c]%Xn)+(r=l*s+(i=e[c]/Xn|0)*u)%Xn*Xn+a)/n|0)+(r/Xn|0)+l*i,e[c]=o%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var o,s;if(n!=r)s=n>r?1:-1;else for(o=s=0;o<n;o++)if(e[o]!=t[o]){s=e[o]>t[o]?1:-1;break}return s}function n(e,t,n,r){for(var o=0;n--;)e[n]-=o,o=e[n]<t[n]?1:0,e[n]=o*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,o,s,i,a){var c,u,l,d,p,h,f,m,g,y,w,A,S,v,T,E,k,I=r.s==o.s?1:-1,C=r.c,B=o.c;if(!(C&&C[0]&&B&&B[0]))return new b(r.s&&o.s&&(C?!B||C[0]!=B[0]:B)?C&&0==C[0]||!B?0*I:I/0:NaN);for(g=(m=new b(I)).c=[],I=s+(u=r.e-o.e)+1,a||(a=qn,u=Wn(r.e/Hn)-Wn(o.e/Hn),I=I/Hn|0),l=0;B[l]==(C[l]||0);l++);if(B[l]>(C[l]||0)&&u--,I<0)g.push(1),d=!0;else{for(v=C.length,E=B.length,l=0,I+=2,(p=Dn(a/(B[0]+1)))>1&&(B=e(B,p,a),C=e(C,p,a),E=B.length,v=C.length),S=E,w=(y=C.slice(0,E)).length;w<E;y[w++]=0);k=B.slice(),k=[0].concat(k),T=B[0],B[1]>=a/2&&T++;do{if(p=0,(c=t(B,y,E,w))<0){if(A=y[0],E!=w&&(A=A*a+(y[1]||0)),(p=Dn(A/T))>1)for(p>=a&&(p=a-1),f=(h=e(B,p,a)).length,w=y.length;1==t(h,y,f,w);)p--,n(h,E<f?k:B,f,a),f=h.length,c=1;else 0==p&&(c=p=1),f=(h=B.slice()).length;if(f<w&&(h=[0].concat(h)),n(y,h,w,a),w=y.length,-1==c)for(;t(B,y,E,w)<1;)p++,n(y,E<w?k:B,w,a),w=y.length}else 0===c&&(p++,y=[0]);g[l++]=p,y[0]?y[w++]=C[S]||0:(y=[C[S]],w=1)}while((S++<v||null!=y[0])&&I--);d=null!=y[0],g[0]||g.splice(0,1)}if(a==qn){for(l=1,I=g[0];I>=10;I/=10,l++);x(m,s+(m.e=l+u*Hn-1)+1,i,d)}else m.e=u,m.r=+d;return m}}(),a.absoluteValue=a.abs=function(){var e=new b(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return zn(this,new b(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,o,s=this;if(null!=e)return x(new b(s),jn(e,-Kn,Kn)+s.e+1,null==t?l:jn(t,0,8));if(!(n=s.c))return null;if(r=((o=n.length-1)-Wn(this.e/Hn))*Hn,o=n[o])for(;o%10==0;o/=10,r--);return r<0&&(r=0),r},a.dividedBy=a.div=function(e,t){return n(this,new b(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new b(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,o,s,i,a,u,d,p=this;if((e=new b(e)).c&&!e.isInteger())throw Error(Mn+"Exponent not an integer: "+R(e));if(null!=t&&(t=new b(t)),i=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return d=new b(Math.pow(+R(p),i?e.s*(2-Jn(e)):+R(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new b(NaN);(r=!a&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||i&&p.c[1]>=24e7:p.c[0]<8e13||i&&p.c[0]<=9999975e7)))return s=p.s<0&&Jn(e)?-0:0,p.e>-1&&(s=1/s),new b(a?1/s:s);w&&(s=Fn(w/Hn+2))}for(i?(n=new b(.5),a&&(e.s=1),u=Jn(e)):u=(o=Math.abs(+R(e)))%2,d=new b(c);;){if(u){if(!(d=d.times(p)).c)break;s?d.c.length>s&&(d.c.length=s):r&&(d=d.mod(t))}if(o){if(0===(o=Dn(o/2)))break;u=o%2}else if(x(e=e.times(n),e.e+1,1),e.e>14)u=Jn(e);else{if(0===(o=+R(e)))break;u=o%2}p=p.times(p),s?p.c&&p.c.length>s&&(p.c.length=s):r&&(p=p.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):s?x(d,w,l,void 0):d)},a.integerValue=function(e){var t=new b(this);return x(t,t.e+1,null==e?l:jn(e,0,8))},a.isEqualTo=a.eq=function(e,t){return 0===zn(this,new b(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return zn(this,new b(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=zn(this,new b(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Wn(this.e/Hn)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return zn(this,new b(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=zn(this,new b(e,t)))||0===t},a.isNaN=function(){return!this.s},a.isNegative=function(){return this.s<0},a.isPositive=function(){return this.s>0},a.isZero=function(){return!!this.c&&0==this.c[0]},a.minus=function(e,t){var n,r,o,s,i=this,a=i.s;if(t=(e=new b(e,t)).s,!a||!t)return new b(NaN);if(a!=t)return e.s=-t,i.plus(e);var c=i.e/Hn,u=e.e/Hn,d=i.c,p=e.c;if(!c||!u){if(!d||!p)return d?(e.s=-t,e):new b(p?i:NaN);if(!d[0]||!p[0])return p[0]?(e.s=-t,e):new b(d[0]?i:3==l?-0:0)}if(c=Wn(c),u=Wn(u),d=d.slice(),a=c-u){for((s=a<0)?(a=-a,o=d):(u=c,o=p),o.reverse(),t=a;t--;o.push(0));o.reverse()}else for(r=(s=(a=d.length)<(t=p.length))?a:t,a=t=0;t<r;t++)if(d[t]!=p[t]){s=d[t]<p[t];break}if(s&&(o=d,d=p,p=o,e.s=-e.s),(t=(r=p.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=qn-1;r>a;){if(d[--r]<p[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=qn}d[r]-=p[r]}for(;0==d[0];d.splice(0,1),--u);return d[0]?C(e,d,u):(e.s=3==l?-1:1,e.c=[e.e=0],e)},a.modulo=a.mod=function(e,t){var r,o,s=this;return e=new b(e,t),!s.c||!e.s||e.c&&!e.c[0]?new b(NaN):!e.c||s.c&&!s.c[0]?new b(s):(9==y?(o=e.s,e.s=1,r=n(s,e,0,3),e.s=o,r.s*=o):r=n(s,e,0,y),(e=s.minus(r.times(e))).c[0]||1!=y||(e.s=s.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,o,s,i,a,c,u,l,d,p,h,f,m,g,y=this,w=y.c,A=(e=new b(e,t)).c;if(!(w&&A&&w[0]&&A[0]))return!y.s||!e.s||w&&!w[0]&&!A||A&&!A[0]&&!w?e.c=e.e=e.s=null:(e.s*=y.s,w&&A?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Wn(y.e/Hn)+Wn(e.e/Hn),e.s*=y.s,(c=w.length)<(d=A.length)&&(f=w,w=A,A=f,o=c,c=d,d=o),o=c+d,f=[];o--;f.push(0));for(m=qn,g=Xn,o=d;--o>=0;){for(n=0,p=A[o]%g,h=A[o]/g|0,s=o+(i=c);s>o;)n=((u=p*(u=w[--i]%g)+(a=h*u+(l=w[i]/g|0)*p)%g*g+f[s]+n)/m|0)+(a/g|0)+h*l,f[s--]=u%m;f[s]=n}return n?++r:f.splice(0,1),C(e,f,r)},a.negated=function(){var e=new b(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,o=r.s;if(t=(e=new b(e,t)).s,!o||!t)return new b(NaN);if(o!=t)return e.s=-t,r.minus(e);var s=r.e/Hn,i=e.e/Hn,a=r.c,c=e.c;if(!s||!i){if(!a||!c)return new b(o/0);if(!a[0]||!c[0])return c[0]?e:new b(a[0]?r:0*o)}if(s=Wn(s),i=Wn(i),a=a.slice(),o=s-i){for(o>0?(i=s,n=c):(o=-o,n=a),n.reverse();o--;n.push(0));n.reverse()}for((o=a.length)-(t=c.length)<0&&(n=c,c=a,a=n,t=o),o=0;t;)o=(a[--t]=a[t]+c[t]+o)/qn|0,a[t]=qn===a[t]?0:a[t]%qn;return o&&(a=[o].concat(a),++i),C(e,a,i)},a.precision=a.sd=function(e,t){var n,r,o,s=this;if(null!=e&&e!==!!e)return x(new b(s),jn(e,1,Kn),null==t?l:jn(t,0,8));if(!(n=s.c))return null;if(r=(o=n.length-1)*Hn+1,o=n[o]){for(;o%10==0;o/=10,r--);for(o=n[0];o>=10;o/=10,r++);}return e&&s.e+1>r&&(r=s.e+1),r},a.shiftedBy=function(e){return this.times("1e"+jn(e,-Gn,Gn))},a.squareRoot=a.sqrt=function(){var e,t,r,o,s,i=this,a=i.c,c=i.s,d=i.e,p=u+4,h=new b("0.5");if(1!==c||!a||!a[0])return new b(!c||c<0&&(!a||a[0])?NaN:a?i:1/0);if(0==(c=Math.sqrt(+R(i)))||c==1/0?(((t=Zn(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Wn((d+1)/2)-(d<0||d%2),r=new b(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new b(c+""),r.c[0])for((c=(d=r.e)+p)<3&&(c=0);;)if(s=r,r=h.times(s.plus(n(i,s,p,1))),Zn(s.c).slice(0,c)===(t=Zn(r.c)).slice(0,c)){if(r.e<d&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(o||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(x(r,r.e+u+2,1),e=!r.times(r).eq(i));break}if(!o&&(x(s,s.e+u+2,0),s.times(s).eq(i))){r=s;break}p+=4,c+=4,o=1}return x(r,r.e+u+1,l,e)},"function"==typeof BigInt&&(a.toBigInt=function(e){var t=this;return t.c?BigInt(E(t,t.e+1,e)):null});a.toExponential=function(e,t){return E(this,null==e?e:jn(e,0,Kn)+1,t,1)},a.toFixed=function(e,t){return E(this,null==e?e:jn(e,-Kn,Kn)+this.e+1,t)},a.toFormat=function(e,t,n){var r,o,s,i=this;if(null==n)n=A,null!=e&&(null!=t?"object"==typeof t&&(n=B(t),t=null):"object"!=typeof e||Yn(e)||(n=B(e),e=t=null));else{if("object"!=typeof n)throw Error(Mn+"Argument not an object: "+n);n=B(n)}if(null!=e)if(Yn(e)&&e.length<=2){if(r=e[0],o=e[1],e=i.dp(),null!=o&&e>jn(o,0,Kn)&&(e=o),null!=r&&0!==jn(r,0,Kn)){if(null!=o&&r>o)throw Error(Mn+"Minimum must not exceed maximum");e<r&&(e=r)}}else jn(e,-Kn,Kn);if(s=i.toFixed(e,t),i.s<0&&(s=s.slice(1)),i.c){var a,c=s.split("."),u=+n.groupSize,l=+n.secondaryGroupSize,d=n.groupSeparator||"",p=c[0],h=c[1],f=p.length;if(l&&(a=u,u=l,l=a,f-=a),u>0&&f>0){for(a=f%u||u,s=p.substr(0,a);a<f;a+=u)s+=d+p.substr(a,u);l>0&&(s+=d+p.slice(a))}h&&((a=+n.fractionGroupSize)&&(h=h.replace(new RegExp("\\d{"+a+"}\\B","g"),"$&"+(n.fractionGroupSeparator||""))),s+=(n.decimalSeparator||"")+h)}return(n.prefix||"")+(i.s<0?n.negativeSign||"":i.s>0&&n.positiveSign||"")+s+(n.suffix||"")},a.toFraction=function(e){var t,r,o,s,i,a,u,d,p,h,m,g,y=this,w=y.c;if(null!=e&&(!(u=new b(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(Mn+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+R(u));if(!w)return[new b(y.s||0),new b(0)];for(t=new b(c),p=r=new b(c),o=d=new b(c),g=Zn(w),i=t.e=g.length-y.e-1,t.c[0]=$n[(a=i%Hn)<0?Hn+a:a],e=!e||u.comparedTo(t)>0?i>0?t:p:u,a=f,f=1/0,u=new b(g),d.c[0]=0;h=n(u,t,0,1),1!=(s=r.plus(h.times(o))).comparedTo(e);)r=o,o=s,p=d.plus(h.times(s=p)),d=s,t=u.minus(h.times(s=t)),u=s;return s=n(e.minus(r),o,0,1),d=d.plus(s.times(p)),r=r.plus(s.times(o)),d.s=p.s=y.s,m=n(p,o,i*=2,l).minus(y).abs().comparedTo(n(d,r,i,l).minus(y).abs())<1?[p,o]:[d,r],f=a,m},a.toNumber=function(){return+R(this)},a.toObject=function(){var e=this;return{c:e.c?e.c.slice():null,e:e.e,s:e.s}},a.toPrecision=function(e,t){return E(this,null==e?e:jn(e,1,Kn),t,2)},a.toString=function(e){var t,n=this,o=n.s,s=n.e;return null===s?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=s<=d||s>=p?Qn(Zn(n.c),s):er(Zn(n.c),s,"0"):(jn(e,2,S.length,"Base"),t=r(er(Zn(n.c),s,"0"),10,e,o,!0)),o<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return R(this)},a._isBigNumber=!0,null!=t&&b.set(t);return b}(),Vn=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Fn=Math.ceil,Dn=Math.floor,Mn="[BigNumber Error] ",qn=1e14,Hn=14,Gn=9007199254740991,$n=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Xn=1e7,Kn=1e9;function Wn(e){var t=0|e;return e>0||e===t?t:t-1}function Zn(e){for(var t,n,r=1,o=e.length,s=e[0]+"";r<o;){for(t=e[r++]+"",n=Hn-t.length;n--;t="0"+t);s+=t}for(o=s.length;48===s.charCodeAt(--o););return s.slice(0,o+1||1)}function zn(e,t){var n,r,o=e.c,s=t.c,i=e.s,a=t.s,c=e.e,u=t.e;if(!i||!a)return null;if(n=o&&!o[0],r=s&&!s[0],n||r)return n?r?0:-a:i;if(i!=a)return i;if(n=i<0,r=c==u,!o||!s)return r?0:!o^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=o.length)<(u=s.length)?c:u,i=0;i<a;i++)if(o[i]!=s[i])return o[i]>s[i]^n?1:-1;return c==u?0:c>u^n?1:-1}function jn(e,t,n,r){if(e<t||e>n||e!==Dn(e))throw Error(Mn+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e));return e}function Yn(e){return"[object Array]"=={}.toString.call(e)}function Jn(e){var t=e.c.length-1;return Wn(e.e/Hn)==t&&e.c[t]%2!=0}function Qn(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function er(e,t,n){var r,o;if(t<0){for(o=n+".";++t;o+=n);e=o+e}else if(++t>(r=e.length)){for(o=n,t-=r;--t;o+=n);e+=o}else t<r&&(e=e.slice(0,t)+"."+e.slice(t));return e}const tr=Nn.clone({STRICT:!0}),nr=2147483647,rr=new tr(nr);const or=1e7;function sr(e,t){if(t.source)try{e.sourceAccount=Pn(t.source)}catch{throw new Error("Source address is invalid")}}function ir(e,t,n=null){if(void 0===t)return;const r="string"==typeof t?""===t.trim()?NaN:Number(t):t;if("number"!=typeof r||!Number.isFinite(r)||r%1!=0)throw new Error(`${e} value is invalid`);if(r<0)throw new Error(`${e} value must be unsigned`);if(!n||n(r,e))return r;throw new Error(`${e} value is invalid`)}function ar(e){const t=new tr(e).times(or);return se.Int64.fromString(t.toString())}function cr(e){return new tr(e.toString()).div(or).toFixed(7)}function ur(e){return new tr(e.n()).div(new tr(e.d())).toString()}function lr(e){let t;if("object"==typeof e&&"n"in e&&"d"in e)t=new se.Price(e);else{const n=new tr(e);if(!n.gt(0)||!n.isFinite())throw new Error("price must be positive");const r=function(e){let t,n,r=new tr(e);const o=[[new tr(0),new tr(1)],[new tr(1),new tr(0)]];let s=2;for(;!r.gt(nr);){t=r.integerValue(tr.ROUND_FLOOR),n=r.minus(t);const e=o[s-1],i=o[s-2];if(!e||!i)throw new Error(`Continued fraction approximation failed: missing fraction elements at indices ${s-1} and/or ${s-2}`);const a=t.times(e[0]).plus(i[0]),c=t.times(e[1]).plus(i[1]);if(a.gt(nr)||c.gt(nr))break;if(o.push([a,c]),n.eq(0))break;r=new tr(1).div(n),s+=1}const i=o[o.length-1];if(!i)throw new Error("Missing last fraction element in continued fraction approximation");const[a,c]=i;if(a.isZero()||c.isZero()){if(new tr(e).isZero())throw new Error("Couldn't find approximation");const t=o[o.length-1],n=o[o.length-2];if(t&&n){let e=rr;if(t[0].gt(0)&&(e=tr.min(e,rr.minus(n[0]).div(t[0]).integerValue(tr.ROUND_FLOOR))),t[1].gt(0)&&(e=tr.min(e,rr.minus(n[1]).div(t[1]).integerValue(tr.ROUND_FLOOR))),e.gte(1)){const r=e.times(t[0]).plus(n[0]),o=e.times(t[1]).plus(n[1]);if(!r.isZero()&&!o.isZero())return[r.toNumber(),o.toNumber()]}}throw new Error("Couldn't find approximation")}return[a.toNumber(),c.toNumber()]}(e);t=new se.Price({n:parseInt(String(r[0]),10),d:parseInt(String(r[1]),10)})}if(t.n()<0||t.d()<=0)throw new Error("price must be positive");return t}function dr(e,t=!1){if("string"!=typeof e)return!1;let n;try{n=new tr(e)}catch{return!1}return!(!t&&n.isZero()||n.isNegative()||n.times(or).gt(new tr("9223372036854775807").toString())||(n.decimalPlaces()??0)>7||n.isNaN()||!n.isFinite())}function pr(e){return`${e} argument must be of type String, represent a positive number and have at most 7 digits after the decimal`}function hr(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.amount,!0))throw new TypeError(pr("amount"));const r=ar(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=void 0!==e.offerId?e.offerId.toString():"0",i=se.Int64.fromString(s),a=new se.ManageSellOfferOp({selling:t,buying:n,amount:r,price:o,offerId:i}),c={sourceAccount:null,body:se.OperationBody.manageSellOffer(a)};return sr(c,e),new se.Operation(c)}function fr(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.amount))throw new TypeError(pr("amount"));const r=ar(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=new se.CreatePassiveSellOfferOp({selling:t,buying:n,amount:r,price:o}),i={sourceAccount:null,body:se.OperationBody.createPassiveSellOffer(s)};return sr(i,e),new se.Operation(i)}function mr(e){let t;try{t=se.OperationBody.accountMerge(Pn(e.destination))}catch{throw new Error("destination is invalid")}const n={sourceAccount:null,body:t};return sr(n,e),new se.Operation(n)}function gr(e){if(!wn.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");const t=Tn.fromPublicKey(e.trustor).xdrAccountId();let n,r;if(e.assetCode.length<=4){const t=fe.Buffer.from(e.assetCode.padEnd(4,"\0"));n=se.AssetCode.assetTypeCreditAlphanum4(t)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");{const t=fe.Buffer.from(e.assetCode.padEnd(12,"\0"));n=se.AssetCode.assetTypeCreditAlphanum12(t)}}if("boolean"==typeof e.authorize)r=e.authorize?se.TrustLineFlags.authorizedFlag().value:0;else{if(null==e.authorize)throw new Error("authorize is required");r=e.authorize}const o=new se.AllowTrustOp({trustor:t,asset:n,authorize:r}),s={sourceAccount:null,body:se.OperationBody.allowTrust(o)};return sr(s,e),new se.Operation(s)}function yr(e){if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new tr(e.bumpTo)}catch{throw new Error("bumpTo must be a stringified number")}const t=se.Int64.fromString(e.bumpTo),n=new se.BumpSequenceOp({bumpTo:t}),r={sourceAccount:null,body:se.OperationBody.bumpSequence(n)};return sr(r,e),new se.Operation(r)}function wr(e){const t=e.asset??e.line;let n;if(t instanceof In)n=t.toChangeTrustXDRObject();else{if(!(t instanceof xn))throw new TypeError("asset must be Asset or LiquidityPoolAsset");n=t.toXDRObject()}if(void 0!==e.limit&&!dr(e.limit,!0))throw new TypeError(pr("limit"));const r=e.limit?ar(e.limit):se.Int64.fromString("9223372036854775807"),o=new se.ChangeTrustOp({line:n,limit:r}),s={sourceAccount:null,body:se.OperationBody.changeTrust(o)};return sr(s,e),new se.Operation(s)}function Ar(e){if(!wn.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!dr(e.startingBalance,!0))throw new TypeError(pr("startingBalance"));const t=new se.CreateAccountOp({destination:Tn.fromPublicKey(e.destination).xdrAccountId(),startingBalance:ar(e.startingBalance)}),n={sourceAccount:null,body:se.OperationBody.createAccount(t)};return sr(n,e),new se.Operation(n)}function Sr(e){if(!(e.asset instanceof In))throw new Error("must provide an asset for create claimable balance operation");if(!dr(e.amount))throw new TypeError(pr("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");const t=e.asset.toXDRObject(),n=ar(e.amount),r=e.claimants.map(e=>e.toXDRObject()),o=new se.CreateClaimableBalanceOp({asset:t,amount:n,claimants:r}),s={sourceAccount:null,body:se.OperationBody.createClaimableBalance(o)};return sr(s,e),new se.Operation(s)}function br(e={}){vr(e.balanceId);const t=se.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n=new se.ClaimClaimableBalanceOp({balanceId:t}),r={sourceAccount:null,body:se.OperationBody.claimClaimableBalance(n)};return sr(r,e),new se.Operation(r)}function vr(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}function Tr(e={}){vr(e.balanceId);const t=se.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n={sourceAccount:null,body:se.OperationBody.clawbackClaimableBalance(new se.ClawbackClaimableBalanceOp({balanceId:t}))};return sr(n,e),new se.Operation(n)}function Er(e={}){const t={sourceAccount:null,body:se.OperationBody.inflation()};return sr(t,e),new se.Operation(t)}function kr(e){if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if("string"!=typeof e.value&&!fe.Buffer.isBuffer(e.value)&&null!==e.value&&void 0!==e.value)throw new Error("value must be a string, Buffer or null");let t;if(t="string"==typeof e.value?fe.Buffer.from(e.value):e.value??null,null!==t&&t.length>64)throw new Error("value cannot be longer that 64 bytes");const n=new se.ManageDataOp({dataName:e.name,dataValue:t}),r={sourceAccount:null,body:se.OperationBody.manageData(n)};return sr(r,e),new se.Operation(r)}function Ir(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.buyAmount,!0))throw new TypeError(pr("buyAmount"));const r=ar(e.buyAmount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=void 0!==e.offerId?e.offerId.toString():"0",i=se.Int64.fromString(s),a=new se.ManageBuyOfferOp({selling:t,buying:n,buyAmount:r,price:o,offerId:i}),c={sourceAccount:null,body:se.OperationBody.manageBuyOffer(a)};return sr(c,e),new se.Operation(c)}function Cr(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!dr(e.sendMax))throw new TypeError(pr("sendMax"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!dr(e.destAmount))throw new TypeError(pr("destAmount"));let t;try{t=Pn(e.destination)}catch{throw new Error("destination is invalid")}const n=e.path?e.path:[],r=new se.PathPaymentStrictReceiveOp({sendAsset:e.sendAsset.toXDRObject(),sendMax:ar(e.sendMax),destination:t,destAsset:e.destAsset.toXDRObject(),destAmount:ar(e.destAmount),path:n.map(e=>e.toXDRObject())}),o={sourceAccount:null,body:se.OperationBody.pathPaymentStrictReceive(r)};return sr(o,e),new se.Operation(o)}function Br(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!dr(e.sendAmount))throw new TypeError(pr("sendAmount"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!dr(e.destMin))throw new TypeError(pr("destMin"));const t=e.sendAsset.toXDRObject(),n=ar(e.sendAmount);let r;try{r=Pn(e.destination)}catch{throw new Error("destination is invalid")}const o=e.destAsset.toXDRObject(),s=ar(e.destMin),i=(e.path??[]).map(e=>e.toXDRObject()),a=new se.PathPaymentStrictSendOp({sendAsset:t,sendAmount:n,destination:r,destAsset:o,destMin:s,path:i}),c={sourceAccount:null,body:se.OperationBody.pathPaymentStrictSend(a)};return sr(c,e),new se.Operation(c)}function xr(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!dr(e.amount))throw new TypeError(pr("amount"));let t;try{t=Pn(e.destination)}catch{throw new Error("destination is invalid")}const n=new se.PaymentOp({destination:t,asset:e.asset.toXDRObject(),amount:ar(e.amount)}),r={sourceAccount:null,body:se.OperationBody.payment(n)};return sr(r,e),new se.Operation(r)}function Rr(e,t){if(e>=0&&e<=255)return!0;throw new Error(`${t} value must be between 0 and 255`)}function _r(e){let t=null;if(e.inflationDest){if(!wn.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t=Tn.fromPublicKey(e.inflationDest).xdrAccountId()}const n=ir("clearFlags",e.clearFlags)??null,r=ir("setFlags",e.setFlags)??null,o=ir("masterWeight",e.masterWeight,Rr)??null,s=ir("lowThreshold",e.lowThreshold,Rr)??null,i=ir("medThreshold",e.medThreshold,Rr)??null,a=ir("highThreshold",e.highThreshold,Rr)??null;if(void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");const c=e.homeDomain;let u=null;if(e.signer){const t=ir("signer.weight",e.signer.weight,Rr);let n,r=0;if(e.signer.ed25519PublicKey){if(!wn.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const t=wn.decodeEd25519PublicKey(e.signer.ed25519PublicKey);n=se.SignerKey.signerKeyTypeEd25519(t),r+=1}if(e.signer.preAuthTx){let t;if(t="string"==typeof e.signer.preAuthTx?fe.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!fe.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");n=se.SignerKey.signerKeyTypePreAuthTx(t),r+=1}if(e.signer.sha256Hash){let t;if(t="string"==typeof e.signer.sha256Hash?fe.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!fe.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");n=se.SignerKey.signerKeyTypeHashX(t),r+=1}if(e.signer.ed25519SignedPayload){if(!wn.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const t=wn.decodeSignedPayload(e.signer.ed25519SignedPayload),o=se.SignerKeyEd25519SignedPayload.fromXDR(t);n=se.SignerKey.signerKeyTypeEd25519SignedPayload(o),r+=1}if(1!==r)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx, or signer.ed25519SignedPayload.");if(void 0===t)throw new Error("signer weight is required.");if(void 0===n)throw new Error("signer key is required.");u=new se.Signer({key:n,weight:t})}const l=new se.SetOptionsOp({inflationDest:t,clearFlags:n,setFlags:r,masterWeight:o,lowThreshold:s,medThreshold:i,highThreshold:a,homeDomain:c,signer:u}),d={sourceAccount:null,body:se.OperationBody.setOptions(l)};return sr(d,e),new se.Operation(d)}function Pr(e){if(!wn.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");const t=new se.BeginSponsoringFutureReservesOp({sponsoredId:Tn.fromPublicKey(e.sponsoredId).xdrAccountId()}),n={sourceAccount:null,body:se.OperationBody.beginSponsoringFutureReserves(t)};return sr(n,e),new se.Operation(n)}function Or(e={}){const t={sourceAccount:null,body:se.OperationBody.endSponsoringFutureReserves()};return sr(t,e),new se.Operation(t)}function Ur(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");const t=se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e.account).xdrAccountId()})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Lr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.asset instanceof In)t=e.asset.toTrustLineXDRObject();else{if(!(e.asset instanceof _n))throw new TypeError("asset must be an Asset or LiquidityPoolId");t=e.asset.toXDRObject()}const n=se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),asset:t})),r=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(n),o={sourceAccount:null,body:se.OperationBody.revokeSponsorship(r)};return sr(o,e),new se.Operation(o)}function Nr(e={}){if(!wn.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");const t=se.LedgerKey.offer(new se.LedgerKeyOffer({sellerId:Tn.fromPublicKey(e.seller).xdrAccountId(),offerId:se.Int64.fromString(e.offerId)})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Vr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");const t=se.LedgerKey.data(new se.LedgerKeyData({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Fr(e={}){if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");const t=se.LedgerKey.claimableBalance(new se.LedgerKeyClaimableBalance({balanceId:se.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Dr(e={}){if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");const t=se.LedgerKey.liquidityPool(new se.LedgerKeyLiquidityPool({liquidityPoolId:fe.Buffer.from(e.liquidityPoolId,"hex")})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Mr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.signer.ed25519PublicKey){if(!wn.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const n=wn.decodeEd25519PublicKey(e.signer.ed25519PublicKey);t=se.SignerKey.signerKeyTypeEd25519(n)}else if(e.signer.preAuthTx){let n;if(n="string"==typeof e.signer.preAuthTx?fe.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!fe.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");t=se.SignerKey.signerKeyTypePreAuthTx(n)}else if(e.signer.sha256Hash){let n;if(n="string"==typeof e.signer.sha256Hash?fe.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!fe.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");t=se.SignerKey.signerKeyTypeHashX(n)}else{if(!e.signer.ed25519SignedPayload)throw new Error("signer is invalid");{if(!wn.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const n=wn.decodeSignedPayload(e.signer.ed25519SignedPayload),r=se.SignerKeyEd25519SignedPayload.fromXDR(n);t=se.SignerKey.signerKeyTypeEd25519SignedPayload(r)}}const n=new se.RevokeSponsorshipOpSigner({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),signerKey:t}),r=se.RevokeSponsorshipOp.revokeSponsorshipSigner(n),o={sourceAccount:null,body:se.OperationBody.revokeSponsorship(r)};return sr(o,e),new se.Operation(o)}function qr(e){if(!dr(e.amount))throw new TypeError(pr("amount"));let t;try{t=Pn(e.from)}catch{throw new Error("from address is invalid")}const n=new se.ClawbackOp({amount:ar(e.amount),asset:e.asset.toXDRObject(),from:t}),r={sourceAccount:null,body:se.OperationBody.clawback(n)};return sr(r,e),new se.Operation(r)}function Hr(e){if("object"!=typeof e.flags||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");const t={authorized:se.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:se.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:se.TrustLineFlags.trustlineClawbackEnabledFlag()};let n=0,r=0;Object.keys(e.flags).forEach(o=>{if(!Object.prototype.hasOwnProperty.call(t,o))throw new Error(`unsupported flag name specified: ${o}`);const s=e.flags[o],i=t[o];if(!i)throw new Error(`Invalid flag name: ${o}`);if("boolean"!=typeof s&&void 0!==s)throw new TypeError(`opts.flags.${o} must be a boolean (got ${typeof s})`);!0===s?r|=i.value:!1===s&&(n|=i.value)});const o=Tn.fromPublicKey(e.trustor).xdrAccountId(),s=e.asset.toXDRObject(),i={sourceAccount:null,body:se.OperationBody.setTrustLineFlags(new se.SetTrustLineFlagsOp({trustor:o,asset:s,clearFlags:n,setFlags:r}))};return sr(i,e),new se.Operation(i)}function Gr(e={}){const{liquidityPoolId:t,maxAmountA:n,maxAmountB:r,minPrice:o,maxPrice:s}=e;if(!t)throw new TypeError("liquidityPoolId argument is required");const i=fe.Buffer.from(t,"hex");if(!dr(n,!0))throw new TypeError(pr("maxAmountA"));const a=ar(n);if(!dr(r,!0))throw new TypeError(pr("maxAmountB"));const c=ar(r);if(void 0===o)throw new TypeError("minPrice argument is required");const u=lr(o);if(void 0===s)throw new TypeError("maxPrice argument is required");const l=lr(s),d=new se.LiquidityPoolDepositOp({liquidityPoolId:i,maxAmountA:a,maxAmountB:c,minPrice:u,maxPrice:l}),p={sourceAccount:null,body:se.OperationBody.liquidityPoolDeposit(d)};return sr(p,e),new se.Operation(p)}function $r(e={}){if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");const t=fe.Buffer.from(e.liquidityPoolId,"hex");if(!dr(e.amount))throw new TypeError(pr("amount"));const n=ar(e.amount);if(!dr(e.minAmountA,!0))throw new TypeError(pr("minAmountA"));const r=ar(e.minAmountA);if(!dr(e.minAmountB,!0))throw new TypeError(pr("minAmountB"));const o=ar(e.minAmountB),s=new se.LiquidityPoolWithdrawOp({liquidityPoolId:t,amount:n,minAmountA:r,minAmountB:o}),i={sourceAccount:null,body:se.OperationBody.liquidityPoolWithdraw(s)};return sr(i,e),new se.Operation(i)}class Xr{_type;_key;constructor(e){if(wn.isValidEd25519PublicKey(e))this._type="account",this._key=wn.decodeEd25519PublicKey(e);else if(wn.isValidContract(e))this._type="contract",this._key=wn.decodeContract(e);else if(wn.isValidMed25519PublicKey(e))this._type="muxedAccount",this._key=wn.decodeMed25519PublicKey(e);else if(wn.isValidClaimableBalance(e))this._type="claimableBalance",this._key=wn.decodeClaimableBalance(e);else{if(!wn.isValidLiquidityPool(e))throw new Error(`Unsupported address type: ${e}`);this._type="liquidityPool",this._key=wn.decodeLiquidityPool(e)}}static fromString(e){return new Xr(e)}static account(e){return new Xr(wn.encodeEd25519PublicKey(e))}static contract(e){return new Xr(wn.encodeContract(e))}static claimableBalance(e){return new Xr(wn.encodeClaimableBalance(e))}static liquidityPool(e){return new Xr(wn.encodeLiquidityPool(e))}static muxedAccount(e){return new Xr(wn.encodeMed25519PublicKey(e))}static fromScVal(e){return Xr.fromScAddress(e.address())}static fromScAddress(e){switch(e.switch().value){case se.ScAddressType.scAddressTypeAccount().value:return Xr.account(e.accountId().ed25519());case se.ScAddressType.scAddressTypeContract().value:return Xr.contract(e.contractId());case se.ScAddressType.scAddressTypeMuxedAccount().value:{const t=fe.Buffer.concat([e.muxedAccount().ed25519(),e.muxedAccount().id().toXDR("raw")]);return Xr.muxedAccount(t)}case se.ScAddressType.scAddressTypeClaimableBalance().value:{const t=e.claimableBalanceId();return Xr.claimableBalance(fe.Buffer.concat([fe.Buffer.from([t.switch().value]),t.v0()]))}case se.ScAddressType.scAddressTypeLiquidityPool().value:return Xr.liquidityPool(e.liquidityPoolId());default:throw new Error(`Unsupported address type: ${e.switch().name}`)}}toString(){switch(this._type){case"account":return wn.encodeEd25519PublicKey(this._key);case"contract":return wn.encodeContract(this._key);case"claimableBalance":return wn.encodeClaimableBalance(this._key);case"liquidityPool":return wn.encodeLiquidityPool(this._key);case"muxedAccount":return wn.encodeMed25519PublicKey(this._key);default:throw new Error("Unsupported address type")}}toScVal(){return se.ScVal.scvAddress(this.toScAddress())}toScAddress(){switch(this._type){case"account":return se.ScAddress.scAddressTypeAccount(se.PublicKey.publicKeyTypeEd25519(this._key));case"contract":return se.ScAddress.scAddressTypeContract(this._key);case"liquidityPool":return se.ScAddress.scAddressTypeLiquidityPool(this._key);case"claimableBalance":return se.ScAddress.scAddressTypeClaimableBalance(se.ClaimableBalanceId.claimableBalanceIdTypeV0(this._key.subarray(1)));case"muxedAccount":return se.ScAddress.scAddressTypeMuxedAccount(new se.MuxedEd25519Account({ed25519:this._key.subarray(0,32),id:se.Uint64.fromXDR(this._key.subarray(32,40),"raw")}));default:throw new Error("Unsupported address type")}}toBuffer(){return this._key}get type(){return this._type}}function Kr(e){if(!e.func)throw new TypeError(`host function invocation ('func') required (got ${JSON.stringify(e)})`);e.func.switch().value===se.HostFunctionType.hostFunctionTypeInvokeContract().value&&e.func.invokeContract().args().forEach(e=>{let t;try{t=Xr.fromScVal(e)}catch{return}switch(t.type){case"claimableBalance":case"liquidityPool":throw new TypeError("claimable balances and liquidity pools cannot be arguments to invokeHostFunction")}});const t=new se.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),n={sourceAccount:null,body:se.OperationBody.invokeHostFunction(t)};return sr(n,e),new se.Operation(n)}function Wr(e){const t=new Xr(e.contract);if("contract"!==t.type)throw new TypeError(`expected contract strkey instance, got ${t.toString()}`);return Kr({func:se.HostFunction.hostFunctionTypeInvokeContract(new se.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args})),...void 0!==e.source&&{source:e.source},...void 0!==e.auth&&{auth:e.auth}})}function Zr(e){const t=fe.Buffer.from(e.salt||Tn.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError(`expected hash(contract WASM) in 'opts.wasmHash', got ${String(e.wasmHash)}`);if(32!==t.length)throw new TypeError(`expected 32-byte salt in 'opts.salt', got ${String(e.salt)}`);return Kr({func:se.HostFunction.hostFunctionTypeCreateContractV2(new se.CreateContractArgsV2({executable:se.ContractExecutable.contractExecutableWasm(fe.Buffer.from(e.wasmHash)),contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAddress(new se.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:t})),constructorArgs:e.constructorArgs??[]})),...void 0!==e.source&&{source:e.source},...void 0!==e.auth&&{auth:e.auth}})}function zr(e){let t=e.asset;if("string"==typeof t){const n=t.split(":"),r=n[0];if(void 0===r)throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);t=new In(r,n[1])}if(!(t instanceof In))throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);return Kr({func:se.HostFunction.hostFunctionTypeCreateContract(new se.CreateContractArgs({executable:se.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())})),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function jr(e){return Kr({func:se.HostFunction.hostFunctionTypeUploadContractWasm(fe.Buffer.from(e.wasm)),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Yr(e){if((e.extendTo??-1)<=0)throw new RangeError("extendTo has to be positive");const t=new se.ExtendFootprintTtlOp({ext:new se.ExtensionPoint(0),extendTo:e.extendTo}),n={sourceAccount:null,body:se.OperationBody.extendFootprintTtl(t)};return sr(n,e),new se.Operation(n)}function Jr(e={}){const t=new se.RestoreFootprintOp({ext:new se.ExtensionPoint(0)}),n={sourceAccount:null,body:se.OperationBody.restoreFootprint(t)};return sr(n,e),new se.Operation(n)}class Qr{static fromXDRObject(e){const t={},n=e.sourceAccount();n&&(t.source=On(n));const r=e.body().value(),o=e.body().switch().name;switch(o){case"createAccount":t.type="createAccount",t.destination=eo(r.destination()),t.startingBalance=cr(r.startingBalance());break;case"payment":t.type="payment",t.destination=On(r.destination()),t.asset=In.fromOperation(r.asset()),t.amount=cr(r.amount());break;case"pathPaymentStrictReceive":{t.type="pathPaymentStrictReceive",t.sendAsset=In.fromOperation(r.sendAsset()),t.sendMax=cr(r.sendMax()),t.destination=On(r.destination()),t.destAsset=In.fromOperation(r.destAsset()),t.destAmount=cr(r.destAmount()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(In.fromOperation(e[n]))});break}case"pathPaymentStrictSend":{t.type="pathPaymentStrictSend",t.sendAsset=In.fromOperation(r.sendAsset()),t.sendAmount=cr(r.sendAmount()),t.destination=On(r.destination()),t.destAsset=In.fromOperation(r.destAsset()),t.destMin=cr(r.destMin()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(In.fromOperation(e[n]))});break}case"changeTrust":if(t.type="changeTrust",r.line().switch()===se.AssetType.assetTypePoolShare())t.line=xn.fromOperation(r.line());else t.line=In.fromOperation(r.line());t.limit=cr(r.limit());break;case"allowTrust":t.type="allowTrust",t.trustor=eo(r.trustor()),t.assetCode=r.asset().value().toString(),t.assetCode=ln(t.assetCode,"\0"),t.authorize=r.authorize();break;case"setOptions":if(t.type="setOptions",r.inflationDest()&&(t.inflationDest=eo(r.inflationDest())),t.clearFlags=r.clearFlags(),t.setFlags=r.setFlags(),t.masterWeight=r.masterWeight(),t.lowThreshold=r.lowThreshold(),t.medThreshold=r.medThreshold(),t.highThreshold=r.highThreshold(),t.homeDomain=void 0!==r.homeDomain()?r.homeDomain().toString("ascii"):void 0,r.signer()){const e={},n=r.signer().key().arm();if("ed25519"===n)e.ed25519PublicKey=eo(r.signer().key());else if("preAuthTx"===n)e.preAuthTx=r.signer().key().preAuthTx();else if("hashX"===n)e.sha256Hash=r.signer().key().hashX();else if("ed25519SignedPayload"===n){const t=r.signer().key().ed25519SignedPayload();e.ed25519SignedPayload=wn.encodeSignedPayload(t.toXDR())}e.weight=r.signer().weight(),t.signer=e}break;case"manageOffer":case"manageSellOffer":t.type="manageSellOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.amount=cr(r.amount()),t.price=ur(r.price()),t.offerId=r.offerId().toString();break;case"manageBuyOffer":t.type="manageBuyOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.buyAmount=cr(r.buyAmount()),t.price=ur(r.price()),t.offerId=r.offerId().toString();break;case"createPassiveOffer":case"createPassiveSellOffer":t.type="createPassiveSellOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.amount=cr(r.amount()),t.price=ur(r.price());break;case"accountMerge":t.type="accountMerge",t.destination=On(r);break;case"manageData":t.type="manageData",t.name=r.dataName().toString("ascii"),t.value=r.dataValue();break;case"inflation":t.type="inflation";break;case"bumpSequence":t.type="bumpSequence",t.bumpTo=r.bumpTo().toString();break;case"createClaimableBalance":t.type="createClaimableBalance",t.asset=In.fromOperation(r.asset()),t.amount=cr(r.amount()),t.claimants=[],r.claimants().forEach(e=>{t.claimants.push(Rn.fromXDR(e))});break;case"claimClaimableBalance":t.type="claimClaimableBalance",t.balanceId=r.toXDR("hex");break;case"beginSponsoringFutureReserves":t.type="beginSponsoringFutureReserves",t.sponsoredId=eo(r.sponsoredId());break;case"endSponsoringFutureReserves":t.type="endSponsoringFutureReserves";break;case"revokeSponsorship":!function(e,t){switch(e.switch().name){case"revokeSponsorshipLedgerEntry":{const n=e.ledgerKey();switch(n.switch().name){case se.LedgerEntryType.account().name:t.type="revokeAccountSponsorship",t.account=eo(n.account().accountId());break;case se.LedgerEntryType.trustline().name:{t.type="revokeTrustlineSponsorship",t.account=eo(n.trustLine().accountId());const e=n.trustLine().asset();if(e.switch()===se.AssetType.assetTypePoolShare())t.asset=_n.fromOperation(e);else t.asset=In.fromOperation(e);break}case se.LedgerEntryType.offer().name:t.type="revokeOfferSponsorship",t.seller=eo(n.offer().sellerId()),t.offerId=n.offer().offerId().toString();break;case se.LedgerEntryType.data().name:t.type="revokeDataSponsorship",t.account=eo(n.data().accountId()),t.name=n.data().dataName().toString("ascii");break;case se.LedgerEntryType.claimableBalance().name:t.type="revokeClaimableBalanceSponsorship",t.balanceId=n.claimableBalance().balanceId().toXDR("hex");break;case se.LedgerEntryType.liquidityPool().name:t.type="revokeLiquidityPoolSponsorship",t.liquidityPoolId=n.liquidityPool().liquidityPoolId().toString("hex");break;default:throw new Error(`Unknown ledgerKey: ${e.switch().name}`)}break}case"revokeSponsorshipSigner":t.type="revokeSignerSponsorship",t.account=eo(e.signer().accountId()),t.signer=function(e){const t={};switch(e.switch().name){case se.SignerKeyType.signerKeyTypeEd25519().name:t.ed25519PublicKey=wn.encodeEd25519PublicKey(e.ed25519());break;case se.SignerKeyType.signerKeyTypePreAuthTx().name:t.preAuthTx=e.preAuthTx().toString("hex");break;case se.SignerKeyType.signerKeyTypeHashX().name:t.sha256Hash=e.hashX().toString("hex");break;case se.SignerKeyType.signerKeyTypeEd25519SignedPayload().name:{const n=e.ed25519SignedPayload();t.ed25519SignedPayload=wn.encodeSignedPayload(n.toXDR());break}default:throw new Error(`Unknown signerKey: ${e.switch().name}`)}return t}(e.signer().signerKey());break;default:throw new Error(`Unknown revokeSponsorship: ${e.switch().name}`)}}(r,t);break;case"clawback":t.type="clawback",t.amount=cr(r.amount()),t.from=On(r.from()),t.asset=In.fromOperation(r.asset());break;case"clawbackClaimableBalance":t.type="clawbackClaimableBalance",t.balanceId=r.toXDR("hex");break;case"setTrustLineFlags":{t.type="setTrustLineFlags",t.asset=In.fromOperation(r.asset()),t.trustor=eo(r.trustor());const e=r.clearFlags(),n=r.setFlags(),o={authorized:se.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:se.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:se.TrustLineFlags.trustlineClawbackEnabledFlag()},s=t=>{const r=o[t]?.value??0;return!!(n&r)||!(e&r)&&void 0},i={};Object.keys(o).forEach(e=>{i[e]=s(e)}),t.flags=i;break}case"liquidityPoolDeposit":t.type="liquidityPoolDeposit",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.maxAmountA=cr(r.maxAmountA()),t.maxAmountB=cr(r.maxAmountB()),t.minPrice=ur(r.minPrice()),t.maxPrice=ur(r.maxPrice());break;case"liquidityPoolWithdraw":t.type="liquidityPoolWithdraw",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.amount=cr(r.amount()),t.minAmountA=cr(r.minAmountA()),t.minAmountB=cr(r.minAmountB());break;case"invokeHostFunction":t.type="invokeHostFunction",t.func=r.hostFunction(),t.auth=r.auth()??[];break;case"extendFootprintTtl":t.type="extendFootprintTtl",t.extendTo=r.extendTo();break;case"restoreFootprint":t.type="restoreFootprint";break;default:throw new Error(`Unknown operation: ${o}`)}return t}static accountMerge=mr;static allowTrust=gr;static bumpSequence=yr;static changeTrust=wr;static createAccount=Ar;static createClaimableBalance=Sr;static claimClaimableBalance=br;static clawbackClaimableBalance=Tr;static createPassiveSellOffer=fr;static inflation=Er;static manageData=kr;static manageSellOffer=hr;static manageBuyOffer=Ir;static pathPaymentStrictReceive=Cr;static pathPaymentStrictSend=Br;static payment=xr;static setOptions=_r;static beginSponsoringFutureReserves=Pr;static endSponsoringFutureReserves=Or;static revokeAccountSponsorship=Ur;static revokeTrustlineSponsorship=Lr;static revokeOfferSponsorship=Nr;static revokeDataSponsorship=Vr;static revokeClaimableBalanceSponsorship=Fr;static revokeLiquidityPoolSponsorship=Dr;static revokeSignerSponsorship=Mr;static clawback=qr;static setTrustLineFlags=Hr;static liquidityPoolDeposit=Gr;static liquidityPoolWithdraw=$r;static invokeHostFunction=Kr;static extendFootprintTtl=Yr;static restoreFootprint=Jr;static createStellarAssetContract=zr;static invokeContractFunction=Wr;static createCustomContract=Zr;static uploadContractWasm=jr}function eo(e){return wn.encodeEd25519PublicKey(e.ed25519())}const to="none",no="id",ro="text",oo="hash",so="return";class io{_type;_value;constructor(e,t=null){switch(this._type=e,this._value=t,this._type){case to:break;case no:io._validateIdValue(t);break;case ro:io._validateTextValue(t);break;case oo:case so:io._validateHashValue(t),"string"==typeof t&&(this._value=fe.Buffer.from(t,"hex"));break;default:throw new Error("Invalid memo type")}}get type(){return this._type}set type(e){throw new Error("Memo is immutable")}get value(){switch(this._type){case to:return null;case no:case ro:return this._value;case oo:case so:return fe.Buffer.from(this._value);default:throw new Error("Invalid memo type")}}set value(e){throw new Error("Memo is immutable")}static _validateIdValue(e){const t=new Error(`Expects a uint64 as a string. Got ${e}`);if("string"!=typeof e)throw t;if(!/^[0-9]+$/.test(e))throw t;let n;try{n=new tr(e)}catch{throw t}if(!n.isFinite())throw t;if(n.isNaN())throw t;if(n.isNegative())throw t;if(!n.isInteger())throw t;if(n.isGreaterThan("18446744073709551615"))throw t}static _validateTextValue(e){if("string"==typeof e){if(fe.Buffer.byteLength(e,"utf8")>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(fe.Buffer.isBuffer(e)){if(e.length>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(!se.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}static _validateHashValue(e){const t=new Error(`Expects a 32 byte hash value or hex encoded string. Got ${String(e)}`);if(null==e)throw t;let n;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw t;n=fe.Buffer.from(e,"hex")}else{if(!fe.Buffer.isBuffer(e))throw t;n=fe.Buffer.from(e)}if(!n.length||32!==n.length)throw t}static none(){return new io(to)}static text(e){return new io(ro,e)}static id(e){return new io(no,e)}static hash(e){return new io(oo,e)}static return(e){return new io(so,e)}toXDRObject(){switch(this._type){case to:return se.Memo.memoNone();case no:return se.Memo.memoId(se.Uint64.fromString(oe.UnsignedHyper.fromString(this._value).toString()));case ro:return se.Memo.memoText(this._value);case oo:return se.Memo.memoHash(this._value);case so:return se.Memo.memoReturn(this._value);default:throw new Error("Invalid memo type")}}static fromXDRObject(e){switch(e.switch()){case se.MemoType.memoId():return io.id(e.id().toString());case se.MemoType.memoText():return io.text(e.value());case se.MemoType.memoHash():return io.hash(e.hash());case se.MemoType.memoReturn():return io.return(e.retHash())}if(void 0===e.value())return io.none();throw new Error("Unknown type")}}class ao extends Bn{_envelopeType;_source="";_memo;_sequence;_operations;_timeBounds;_ledgerBounds;_minAccountSequence;_minAccountSequenceAge;_minAccountSequenceLedgerGap;_extraSigners;constructor(e,t){if("string"==typeof e){const t=fe.Buffer.from(e,"base64");e=se.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==se.EnvelopeType.envelopeTypeTxV0()&&n!==se.EnvelopeType.envelopeTypeTx())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${n.name}.`);const r=e.value(),o=r.tx(),s=o.fee().toString();if(super(o,(r.signatures()||[]).slice(),s,t),this._envelopeType=n,this._memo=o.memo(),this._sequence=o.seqNum().toString(),this._envelopeType===se.EnvelopeType.envelopeTypeTxV0())this._source=wn.encodeEd25519PublicKey(o.sourceAccountEd25519());else this._source=On(o.sourceAccount());let i=null,a=null;switch(this._envelopeType){case se.EnvelopeType.envelopeTypeTxV0():a=o.timeBounds();break;case se.EnvelopeType.envelopeTypeTx():switch(o.cond().switch()){case se.PreconditionType.precondTime():a=o.cond().timeBounds();break;case se.PreconditionType.precondV2():i=o.cond().v2(),a=i.timeBounds()}}if(a&&(this._timeBounds={minTime:a.minTime().toString(),maxTime:a.maxTime().toString()}),i){const e=i.ledgerBounds();e&&(this._ledgerBounds={minLedger:e.minLedger(),maxLedger:e.maxLedger()});const t=i.minSeqNum();t&&(this._minAccountSequence=t.toString()),this._minAccountSequenceAge=i.minSeqAge().toBigInt(),this._minAccountSequenceLedgerGap=i.minSeqLedgerGap(),this._extraSigners=i.extraSigners()}const c=o.operations()||[];this._operations=c.map(e=>Qr.fromXDRObject(e))}get timeBounds(){return this._timeBounds}set timeBounds(e){throw new Error("Transaction is immutable")}get ledgerBounds(){return this._ledgerBounds}set ledgerBounds(e){throw new Error("Transaction is immutable")}get minAccountSequence(){return this._minAccountSequence}set minAccountSequence(e){throw new Error("Transaction is immutable")}get minAccountSequenceAge(){return this._minAccountSequenceAge}set minAccountSequenceAge(e){throw new Error("Transaction is immutable")}get minAccountSequenceLedgerGap(){return this._minAccountSequenceLedgerGap}set minAccountSequenceLedgerGap(e){throw new Error("Transaction is immutable")}get extraSigners(){return this._extraSigners}set extraSigners(e){throw new Error("Transaction is immutable")}get sequence(){return this._sequence}set sequence(e){throw new Error("Transaction is immutable")}get source(){return this._source}set source(e){throw new Error("Transaction is immutable")}get operations(){return this._operations}set operations(e){throw new Error("Transaction is immutable")}get memo(){return io.fromXDRObject(this._memo)}set memo(e){throw new Error("Transaction is immutable")}signatureBase(){let e=this.tx;this._envelopeType===se.EnvelopeType.envelopeTypeTxV0()&&(e=se.Transaction.fromXDR(fe.Buffer.concat([fe.Buffer.alloc(4),e.toXDR()])));const t=se.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(e);return new se.TransactionSignaturePayload({networkId:se.Hash.fromXDR(nt(this.networkPassphrase)),taggedTransaction:t}).toXDR()}toEnvelope(){const e=this.tx.toXDR(),t=this.signatures.slice();let n;switch(this._envelopeType){case se.EnvelopeType.envelopeTypeTxV0():n=se.TransactionEnvelope.envelopeTypeTxV0(new se.TransactionV0Envelope({tx:se.TransactionV0.fromXDR(e),signatures:t}));break;case se.EnvelopeType.envelopeTypeTx():n=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:se.Transaction.fromXDR(e),signatures:t}));break;default:throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${this._envelopeType.name}.`)}return n}getClaimableBalanceId(e){if(!Number.isInteger(e)||e<0||e>=this.operations.length)throw new RangeError("invalid operation index");const t=this.operations[e];if(void 0===t)throw new RangeError("invalid operation index");try{Qr.createClaimableBalance(t)}catch(e){throw new TypeError(`expected createClaimableBalance, got ${t.type}: ${String(e)}`)}const n=wn.decodeEd25519PublicKey(Ln(this.source)),r=nt(se.HashIdPreimage.envelopeTypeOpId(new se.HashIdPreimageOperationId({sourceAccount:se.PublicKey.publicKeyTypeEd25519(n),seqNum:se.Int64.fromString(this.sequence),opNum:e})).toXDR("raw"));return se.ClaimableBalanceId.claimableBalanceIdTypeV0(r).toXDR("hex")}}class co extends Bn{_feeSource;_innerTransaction;constructor(e,t){if("string"==typeof e){const t=fe.Buffer.from(e,"base64");e=se.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==se.EnvelopeType.envelopeTypeTxFeeBump())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ${n.name}.`);const r=e.value(),o=r.tx(),s=o.fee().toString();super(o,(r.signatures()||[]).slice(),s,t);const i=se.TransactionEnvelope.envelopeTypeTx(o.innerTx().v1());this._feeSource=On(this.tx.feeSource()),this._innerTransaction=new ao(i,t)}get innerTransaction(){return this._innerTransaction}get operations(){return this._innerTransaction.operations}get feeSource(){return this._feeSource}signatureBase(){const e=se.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx);return new se.TransactionSignaturePayload({networkId:se.Hash.fromXDR(nt(this.networkPassphrase)),taggedTransaction:e}).toXDR()}toEnvelope(){const e=new se.FeeBumpTransactionEnvelope({tx:se.FeeBumpTransaction.fromXDR(this.tx.toXDR()),signatures:this.signatures.slice()});return se.TransactionEnvelope.envelopeTypeTxFeeBump(e)}}class uo{_accountId;sequence;constructor(e,t){if(wn.isValidMed25519PublicKey(e))throw new Error("accountId is an M-address; use MuxedAccount instead");if(!wn.isValidEd25519PublicKey(e))throw new Error("accountId is invalid");if("string"!=typeof t)throw new Error("sequence must be of type string");let n;try{n=new tr(t)}catch{throw new Error("sequence is not a valid number")}if(n.isNaN())throw new Error("sequence is not a valid number");this._accountId=e,this.sequence=n}accountId(){return this._accountId}sequenceNumber(){return this.sequence.toString()}incrementSequenceNumber(){this.sequence=this.sequence.plus(1)}}const lo=BigInt("18446744073709551615");function po(e){let t;try{t=BigInt(e)}catch{throw new Error(`id is not a valid uint64 string: ${e}`)}if(t<BigInt(0)||t>lo)throw new Error(`id value out of range for uint64 [0, ${lo}]: ${e}`)}class ho{account;_muxedXdr;_mAddress;_id;constructor(e,t){const n=e.accountId();if(!wn.isValidEd25519PublicKey(n))throw new Error("accountId is invalid");po(t),this.account=e,this._muxedXdr=Un(n,t),this._mAddress=On(this._muxedXdr),this._id=t}static fromAddress(e,t){const n=Pn(e),r=Ln(e),o=n.med25519().id().toString();return new ho(new uo(r,t),o)}baseAccount(){return this.account}accountId(){return this._mAddress}id(){return this._id}setId(e){if("string"!=typeof e)throw new Error("id should be a string representing a number (uint64)");return po(e),this._muxedXdr.med25519().id(se.Uint64.fromString(e)),this._mAddress=On(this._muxedXdr),this._id=e,this}sequenceNumber(){return this.account.sequenceNumber()}incrementSequenceNumber(){this.account.incrementSequenceNumber()}toXDRObject(){return this._muxedXdr}equals(e){return this.accountId()===e.accountId()}}class fo{_data;constructor(e){let t;t=e?"string"==typeof e||ArrayBuffer.isView(e)?fo.fromXDR(e):fo.fromXDR(e.toXDR()):new se.SorobanTransactionData({resources:new se.SorobanResources({footprint:new se.LedgerFootprint({readOnly:[],readWrite:[]}),instructions:0,diskReadBytes:0,writeBytes:0}),ext:new se.SorobanTransactionDataExt(0),resourceFee:new se.Int64(0)}),this._data=t}static fromXDR(e){return"string"==typeof e?se.SorobanTransactionData.fromXDR(e,"base64"):se.SorobanTransactionData.fromXDR(fe.Buffer.from(e),"raw")}setResourceFee(e){return this._data.resourceFee(new se.Int64(e)),this}setResources(e,t,n){return this._data.resources().instructions(e),this._data.resources().diskReadBytes(t),this._data.resources().writeBytes(n),this}appendFootprint(e,t){return this.setFootprint(this.getReadOnly().concat(e),this.getReadWrite().concat(t))}setFootprint(e,t){return null!==e&&this.setReadOnly(e),null!==t&&this.setReadWrite(t),this}setReadOnly(e){return this._data.resources().footprint().readOnly(e??[]),this}setReadWrite(e){return this._data.resources().footprint().readWrite(e??[]),this}build(){return se.SorobanTransactionData.fromXDR(this._data.toXDR())}getReadOnly(){return this.getFootprint().readOnly()}getReadWrite(){return this.getFootprint().readWrite()}getFootprint(){return this._data.resources().footprint()}}class mo{static decodeAddress(e){const t=wn.getVersionByteForPrefix(e);if(void 0===t)throw new Error(`invalid signer key type (${t})`);const n=Sn(t,e);switch(t){case"signedPayload":return se.SignerKey.signerKeyTypeEd25519SignedPayload(new se.SignerKeyEd25519SignedPayload({ed25519:n.subarray(0,32),payload:n.subarray(36,36+n.readUInt32BE(32))}));case"ed25519PublicKey":return se.SignerKey.signerKeyTypeEd25519(n);case"preAuthTx":return se.SignerKey.signerKeyTypePreAuthTx(n);case"sha256Hash":return se.SignerKey.signerKeyTypeHashX(n);default:throw new Error(`invalid signer key type (${t})`)}}static encodeSignerKey(e){let t,n;switch(e.switch()){case se.SignerKeyType.signerKeyTypeEd25519():t="ed25519PublicKey",n=e.value();break;case se.SignerKeyType.signerKeyTypePreAuthTx():t="preAuthTx",n=e.value();break;case se.SignerKeyType.signerKeyTypeHashX():t="sha256Hash",n=e.value();break;case se.SignerKeyType.signerKeyTypeEd25519SignedPayload():t="signedPayload",n=e.ed25519SignedPayload().toXDR("raw");break;default:throw new Error(`invalid SignerKey (type: ${e.switch().name})`)}return bn(t,n)}}class go{_id;constructor(e){try{this._id=wn.decodeContract(e)}catch{throw new Error(`Invalid contract ID: ${e}`)}}contractId(){return wn.encodeContract(this._id)}toString(){return this.contractId()}address(){return Xr.contract(this._id)}call(e,...t){return Qr.invokeContractFunction({contract:this.address().toString(),function:e,args:t})}getFootprint(){return se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:this.address().toScAddress(),key:se.ScVal.scvLedgerKeyContractInstance(),durability:se.ContractDataDurability.persistent()}))}}class yo extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 128}}yo.defineIntBoundaries();class wo extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 256}}wo.defineIntBoundaries();class Ao extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 128}}Ao.defineIntBoundaries();class So extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 256}}So.defineIntBoundaries();class bo{int;type;constructor(e,t){t instanceof Array||(t=[t]);const n=t.map(e=>"bigint"==typeof e?e:"object"==typeof e&&null!==e&&"toBigInt"in e&&"function"==typeof e.toBigInt?e.toBigInt():BigInt(e));switch(e){case"i64":this.int=new oe.Hyper(n);break;case"i128":this.int=new Ao(...n);break;case"i256":this.int=new So(...n);break;case"u64":case"timepoint":case"duration":this.int=new oe.UnsignedHyper(n);break;case"u128":this.int=new yo(...n);break;case"u256":this.int=new wo(...n);break;default:throw TypeError(`invalid type: ${e}`)}this.type=e}toNumber(){const e=this.int.toBigInt();if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw RangeError(`value ${e} not in range for Number [${Number.MAX_SAFE_INTEGER}, ${Number.MIN_SAFE_INTEGER}]`);return Number(e)}toBigInt(){return this.int.toBigInt()}toI64(){this._sizeCheck(64);const e=this.toBigInt();if(BigInt.asIntN(64,e)!==e)throw RangeError(`value too large for i64: ${e}`);return se.ScVal.scvI64(new se.Int64(e))}toU64(){return this._sizeCheck(64),se.ScVal.scvU64(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toTimepoint(){return this._sizeCheck(64),se.ScVal.scvTimepoint(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toDuration(){return this._sizeCheck(64),se.ScVal.scvDuration(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toI128(){this._sizeCheck(128);const e=this.int.toBigInt();if(BigInt.asIntN(128,e)!==e)throw RangeError(`value too large for i128: ${e}`);const t=BigInt.asIntN(64,e>>64n),n=BigInt.asUintN(64,e);return se.ScVal.scvI128(new se.Int128Parts({hi:new se.Int64(t),lo:new se.Uint64(n)}))}toU128(){this._sizeCheck(128);const e=this.int.toBigInt();return se.ScVal.scvU128(new se.UInt128Parts({hi:new se.Uint64(BigInt.asUintN(64,e>>64n)),lo:new se.Uint64(BigInt.asUintN(64,e))}))}toI256(){const e=this.int.toBigInt();if(BigInt.asIntN(256,e)!==e)throw RangeError(`value too large for i256: ${e}`);const t=BigInt.asIntN(64,e>>192n),n=BigInt.asUintN(64,e>>128n),r=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return se.ScVal.scvI256(new se.Int256Parts({hiHi:new se.Int64(t),hiLo:new se.Uint64(n),loHi:new se.Uint64(r),loLo:new se.Uint64(o)}))}toU256(){const e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),n=BigInt.asUintN(64,e>>128n),r=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return se.ScVal.scvU256(new se.UInt256Parts({hiHi:new se.Uint64(t),hiLo:new se.Uint64(n),loHi:new se.Uint64(r),loLo:new se.Uint64(o)}))}toScVal(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();case"timepoint":return this.toTimepoint();case"duration":return this.toDuration();default:throw TypeError(`invalid type: ${this.type}`)}}valueOf(){return this.int.valueOf()}toString(){return this.int.toString()}toJSON(){return{value:this.toBigInt().toString(),type:this.type}}_sizeCheck(e){if(this.int.size>e)throw RangeError(`value too large for ${e} bits (${this.type})`)}static isType(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":case"timepoint":case"duration":return!0;default:return!1}}static getType(e){const t=e.slice(3).toLowerCase();if(this.isType(t))return t}}class vo extends bo{constructor(e,t){const n=BigInt(e),r=n<0n;let o=t?.type??"";if(o.startsWith("u")&&r)throw TypeError(`specified type ${t?.type} yet negative (${e})`);if(""===o){o=r?"i":"u";const t=function(e){if(e<0n){const t=(-e-1n).toString(2).length+1;return[64,128,256].find(e=>t<=e)??t}const t=e.toString(2).length;return[64,128,256].find(e=>t<=e)??t}(n);switch(t){case 64:case 128:case 256:o+=t.toString();break;default:throw RangeError(`expected 64/128/256 bits for input (${e}), got ${t}`)}}super(o,n)}}function To(e){const t=e.switch().name,n=bo.getType(t),r=e.value();if(null===r)throw TypeError(`unexpected null value for ${t}`);switch(t){case"scvU32":case"scvI32":return BigInt(r);case"scvU64":case"scvI64":case"scvTimepoint":case"scvDuration":if(void 0===n)throw TypeError(`invalid integer type for ${t}`);return new bo(n,r).toBigInt();case"scvU128":case"scvI128":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new bo(n,[e.lo(),e.hi()]).toBigInt()}case"scvU256":case"scvI256":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new bo(n,[e.loLo(),e.loHi(),e.hiLo(),e.hiHi()]).toBigInt()}default:throw TypeError(`expected integer type, got ${t}`)}}function Eo(e,t={}){switch(typeof e){case"object":{if(null===e)return se.ScVal.scvVoid();if(e instanceof se.ScVal)return e;if(e instanceof Xr)return e.toScVal();if(e instanceof Tn)return Eo(e.publicKey(),{type:"address"});if(e instanceof go)return e.address().toScVal();if(e instanceof Uint8Array||fe.Buffer.isBuffer(e)){const n=fe.Buffer.from(e);switch(t?.type??"bytes"){case"bytes":return se.ScVal.scvBytes(n);case"symbol":return se.ScVal.scvSymbol(n);case"string":return se.ScVal.scvString(n);default:throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for bytes-like value`)}}if(Array.isArray(e))return se.ScVal.scvVec(e.map((e,n)=>Array.isArray(t.type)?Eo(e,{...t.type.length>n&&{type:t.type[n]}}):Eo(e,t)));if(Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`cannot interpret ${e.constructor?.name} value as ScVal (${JSON.stringify(e)})`);const n=t?.type??{};return se.ScVal.scvMap(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>{const[r,o]=Object.hasOwn(n,e)?n[e]??[null,null]:[null,null],s=r?{type:r}:{},i=o?{type:o}:{};return new se.ScMapEntry({key:Eo(e,s),val:Eo(t,i)})}))}case"number":case"bigint":{const n=BigInt(e);switch(t?.type){case"u32":if(n<BigInt(se.Uint32.MIN_VALUE)||n>BigInt(se.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return se.ScVal.scvU32(Number(e));case"i32":if(n<-BigInt(se.Int32.MIN_VALUE)||n>BigInt(se.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return se.ScVal.scvI32(Number(e))}return new vo(e,{type:t?.type}).toScVal()}case"string":{const n=t?.type??"string";switch(n){case"string":return se.ScVal.scvString(e);case"symbol":return se.ScVal.scvSymbol(e);case"address":return new Xr(e).toScVal();case"u32":{const t=BigInt(e);if(t<BigInt(se.Uint32.MIN_VALUE)||t>BigInt(se.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return se.ScVal.scvU32(Number(t))}case"i32":{const t=BigInt(e);if(t<-BigInt(se.Int32.MIN_VALUE)||t>BigInt(se.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return se.ScVal.scvI32(Number(t))}default:if(bo.isType(n))return new bo(n,e).toScVal();throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for string value`)}}case"boolean":return se.ScVal.scvBool(e);case"undefined":return se.ScVal.scvVoid();case"function":return Eo(e());default:throw new TypeError(`failed to convert typeof ${typeof e} (${JSON.stringify(e)})`)}}function ko(e){switch(e.switch().value){case se.ScValType.scvVoid().value:return null;case se.ScValType.scvU64().value:case se.ScValType.scvI64().value:return e.value().toBigInt();case se.ScValType.scvU128().value:case se.ScValType.scvI128().value:case se.ScValType.scvU256().value:case se.ScValType.scvI256().value:return To(e);case se.ScValType.scvVec().value:return(e.vec()??[]).map(ko);case se.ScValType.scvAddress().value:return Xr.fromScVal(e).toString();case se.ScValType.scvMap().value:return Object.fromEntries((e.map()??[]).map(e=>[ko(e.key()),ko(e.val())]));case se.ScValType.scvBool().value:case se.ScValType.scvU32().value:case se.ScValType.scvI32().value:case se.ScValType.scvBytes().value:return e.value();case se.ScValType.scvSymbol().value:{const t=e.sym();if(fe.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case se.ScValType.scvString().value:{const t=e.str();if(fe.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case se.ScValType.scvTimepoint().value:case se.ScValType.scvDuration().value:return e.value().toBigInt();case se.ScValType.scvError().value:if(e.error().switch().value===se.ScErrorType.sceContract().value)return{type:"contract",code:e.error().contractCode()};{const t=e.error();return{type:"system",code:t.code().value,value:t.code().name}}default:return e.value()}}function Io(e){const t=Array.from(e).sort((e,t)=>{const n=ko(e.key()),r=ko(t.key());switch(typeof n){case"number":case"bigint":return n===r?0:n<r?-1:1;default:{const e=n.toString(),t=r.toString();return e<t?-1:e>t?1:0}}});return se.ScVal.scvMap(t)}se.scvSortedMap=Io;const Co=oe.Hyper.MAX_VALUE,Bo=4294967295,xo="100";class Ro{source;operations;baseFee;timebounds;ledgerbounds;minAccountSequence;minAccountSequenceAge;minAccountSequenceLedgerGap;extraSigners;memo;networkPassphrase;sorobanData;constructor(e,t={}){if(!e)throw new Error("must specify source account for the transaction");if(void 0===t.fee)throw new Error("must specify fee for the transaction (in stroops)");if(this.source=e,this.operations=[],this.baseFee=t.fee,t.timebounds){const e=Po(t.timebounds.minTime),n=Po(t.timebounds.maxTime);if(void 0!==e&&e<0)throw new Error("min_time cannot be negative");if(void 0!==n&&n<0)throw new Error("max_time cannot be negative");if(void 0!==e&&void 0!==n&&n>0&&e>n)throw new Error("min_time cannot be greater than max_time");this.timebounds={...t.timebounds}}else this.timebounds=null;if(t.ledgerbounds){const e=t.ledgerbounds.minLedger,n=t.ledgerbounds.maxLedger;if(void 0!==e&&e<0)throw new Error("min_ledger cannot be negative");if(void 0!==n&&n<0)throw new Error("max_ledger cannot be negative");if(void 0!==e&&void 0!==n&&n>0&&e>n)throw new Error("min_ledger cannot be greater than max_ledger");this.ledgerbounds={...t.ledgerbounds}}else this.ledgerbounds=null;this.minAccountSequence=t.minAccountSequence||null,this.minAccountSequenceAge=void 0!==t.minAccountSequenceAge?t.minAccountSequenceAge:null,this.minAccountSequenceLedgerGap=void 0!==t.minAccountSequenceLedgerGap?t.minAccountSequenceLedgerGap:null,this.extraSigners=t.extraSigners?[...t.extraSigners]:null,this.memo=t.memo||io.none(),this.networkPassphrase=t.networkPassphrase||null,this.sorobanData=t.sorobanData?new fo(t.sorobanData).build():null}static cloneFrom(e,t={}){if(!(e instanceof ao))throw new TypeError(`expected a 'Transaction', got: ${String(e)}`);const n=(BigInt(e.sequence)-1n).toString();let r,o;if(wn.isValidMed25519PublicKey(e.source))r=ho.fromAddress(e.source,n);else{if(!wn.isValidEd25519PublicKey(e.source))throw new TypeError(`unsupported tx source account: ${e.source}`);r=new uo(e.source,n)}if(0===e.operations.length)throw new Error("cannot clone a transaction with no operations: per-operation base fee cannot be determined");const s=e.toEnvelope();s.switch()===se.EnvelopeType.envelopeTypeTx()&&(o=s.v1().tx().ext().value()??void 0);let i=parseInt(e.fee,10);if(o){const e=Number(o.resourceFee().toBigInt());i-e>0&&(i-=e)}const a={fee:(Math.floor(i/e.operations.length)||xo).toString(),memo:e.memo,networkPassphrase:e.networkPassphrase};e.timeBounds&&(a.timebounds=e.timeBounds),e.ledgerBounds&&(a.ledgerbounds=e.ledgerBounds),e.minAccountSequence&&(a.minAccountSequence=e.minAccountSequence),void 0!==e.minAccountSequenceAge&&(a.minAccountSequenceAge=e.minAccountSequenceAge),void 0!==e.minAccountSequenceLedgerGap&&(a.minAccountSequenceLedgerGap=e.minAccountSequenceLedgerGap),e.extraSigners&&(a.extraSigners=e.extraSigners.map(e=>mo.encodeSignerKey(e))),Object.assign(a,t);const c=new Ro(r,a);return e.tx.operations().forEach(e=>c.addOperation(e)),c}addOperation(e){return this.operations.push(e),this}addOperationAt(e,t){return this.operations.splice(t,0,e),this}clearOperations(){return this.operations=[],this}clearOperationAt(e){return this.operations.splice(e,1),this}addMemo(e){return this.memo=e,this}setTimeout(e){if(null!==this.timebounds&&Number(this.timebounds.maxTime)>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){const t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime??0,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}setTimebounds(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");const n=Math.floor(e.valueOf()/1e3),r=Math.floor(t.valueOf()/1e3);if(n<0)throw new Error("min_time cannot be negative");if(r<0)throw new Error("max_time cannot be negative");if(r>0&&n>r)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:n,maxTime:r},this}setLedgerbounds(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}setMinAccountSequence(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}setMinAccountSequenceAge(e){if("bigint"!=typeof e)throw new Error("min_account_sequence_age must be a bigint");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}setMinAccountSequenceLedgerGap(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}setExtraSigners(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=[...e],this}setNetworkPassphrase(e){return this.networkPassphrase=e,this}setSorobanData(e){return this.sorobanData=new fo(e).build(),this}addSacTransferOperation(e,t,n,r){if(BigInt(n)<=0n)throw new Error("Amount must be a positive integer");if(BigInt(n)>Co)throw new Error("Amount exceeds maximum value for i64");if(r){const{instructions:e,readBytes:t,writeBytes:n,resourceFee:o}=r,s=4294967295;if(e<=0||e>s)throw new Error(`instructions must be greater than 0 and at most ${s}`);if(t<=0||t>s)throw new Error(`readBytes must be greater than 0 and at most ${s}`);if(n<=0||n>s)throw new Error(`writeBytes must be greater than 0 and at most ${s}`);if(o<=0n||o>Co)throw new Error("resourceFee must be greater than 0 and at most i64 max")}const o=wn.isValidContract(e);if(!o&&!wn.isValidEd25519PublicKey(e)&&!wn.isValidMed25519PublicKey(e))throw new Error("Invalid destination address. Must be a valid Stellar address or contract ID.");const s=o?e:Ln(e);if(s===Ln(this.source.accountId()))throw new Error("Destination cannot be the same as the source account.");if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to add a SAC transfer operation");const i=t.contractId(this.networkPassphrase),a="transfer",c=this.source.accountId(),u=Ln(c),l=[Eo(c,{type:"address"}),Eo(e,{type:"address"}),Eo(n,{type:"i128"})],d=t.isNative(),p=new se.SorobanAuthorizationEntry({credentials:se.SorobanCredentials.sorobanCredentialsSourceAccount(),rootInvocation:new se.SorobanAuthorizedInvocation({function:se.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(new se.InvokeContractArgs({contractAddress:Xr.fromString(i).toScAddress(),functionName:a,args:l})),subInvocations:[]})}),h=new se.LedgerFootprint({readOnly:[se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:Xr.fromString(i).toScAddress(),key:se.ScVal.scvLedgerKeyContractInstance(),durability:se.ContractDataDurability.persistent()}))],readWrite:[]});if(o){if(h.readWrite().push(se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:Xr.fromString(i).toScAddress(),key:se.ScVal.scvVec([Eo("Balance",{type:"symbol"}),Eo(e,{type:"address"})]),durability:se.ContractDataDurability.persistent()}))),!d){const e=t.getIssuer();if(!e)throw new Error("Asset issuer must be set for non-native assets.");h.readOnly().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e).xdrPublicKey()})))}}else d?h.readWrite().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(s).xdrPublicKey()}))):t.getIssuer()!==s&&h.readWrite().push(se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(s).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));t.isNative()?h.readWrite().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(u).xdrPublicKey()}))):t.getIssuer()!==u&&h.readWrite().push(se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(u).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));const f={instructions:4e5,readBytes:1e3,writeBytes:1e3,resourceFee:BigInt(5e6)},m=new se.SorobanTransactionData({resources:new se.SorobanResources({footprint:h,instructions:r?r.instructions:f.instructions,diskReadBytes:r?r.readBytes:f.readBytes,writeBytes:r?r.writeBytes:f.writeBytes}),ext:new se.SorobanTransactionDataExt(0),resourceFee:new se.Int64(r?r.resourceFee:f.resourceFee)}),g=Qr.invokeContractFunction({contract:i,function:a,args:l,auth:[p]});return this.setSorobanData(m),this.addOperation(g)}build(){const e=new tr(this.source.sequenceNumber()).plus(1),t=new tr(this.baseFee).times(this.operations.length).toNumber();if(t>Bo)throw new Error(`Total fee (baseFee * operations) exceeds the maximum uint32 value (4294967295). Got ${t} from baseFee=${this.baseFee} and ${this.operations.length} operation(s).`);const n={fee:t,seqNum:se.Int64.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");_o(this.timebounds.minTime)&&(this.timebounds.minTime=Math.floor(this.timebounds.minTime.getTime()/1e3)),_o(this.timebounds.maxTime)&&(this.timebounds.maxTime=Math.floor(this.timebounds.maxTime.getTime()/1e3));const r=se.Uint64.fromString(this.timebounds.minTime.toString()),o=se.Uint64.fromString(this.timebounds.maxTime.toString()),s=new se.TimeBounds({minTime:r,maxTime:o});if(this.hasV2Preconditions()){let e=null;null!==this.ledgerbounds&&(e=new se.LedgerBounds({minLedger:this.ledgerbounds.minLedger??0,maxLedger:this.ledgerbounds.maxLedger??0}));const t=this.minAccountSequence?se.Int64.fromString(this.minAccountSequence):null,r=se.Uint64.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),o=this.minAccountSequenceLedgerGap||0,i=null!==this.extraSigners?this.extraSigners.map(e=>mo.decodeAddress(e)):[];n.cond=se.Preconditions.precondV2(new se.PreconditionsV2({timeBounds:s,ledgerBounds:e,minSeqNum:t,minSeqAge:r,minSeqLedgerGap:o,extraSigners:i}))}else n.cond=se.Preconditions.precondTime(s);if(n.sourceAccount=Pn(this.source.accountId()),this.sorobanData){if(n.ext=new se.TransactionExt(1,this.sorobanData),n.fee=new tr(n.fee).plus(this.sorobanData.resourceFee().toString()).toNumber(),n.fee>Bo)throw new Error(`Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (4294967295). Got ${n.fee}.`)}else n.ext=new se.TransactionExt(0);const i=new se.Transaction(n);i.operations(this.operations);const a=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:i,signatures:[]}));if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to build a transaction");const c=new ao(a,this.networkPassphrase);return this.source.incrementSequenceNumber(),c}hasV2Preconditions(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}static buildFeeBumpTransaction(e,t,n,r){const o=n.operations.length,s=new tr(xo);let i=new tr(0);const a=n.toEnvelope();switch(a.switch().value){case se.EnvelopeType.envelopeTypeTx().value:{const e=a.v1().tx().ext().value();i=new tr(e?.resourceFee().toString()??0);break}}const c=new tr(n.fee).minus(i).div(o),u=new tr(t);if(u.lt(c))throw new Error(`Invalid baseFee, it should be at least ${c.toString()} stroops.`);if(u.lt(s))throw new Error(`Invalid baseFee, it should be at least ${s.toString()} stroops.`);let l,d=n.toEnvelope();if(d.switch()===se.EnvelopeType.envelopeTypeTxV0()){const e=d.v0().tx(),t=e.timeBounds();if(null===t)throw new Error("Inner transaction must have time bounds");const n=new se.Transaction({sourceAccount:se.MuxedAccount.keyTypeEd25519(e.sourceAccountEd25519()),fee:e.fee(),seqNum:e.seqNum(),cond:se.Preconditions.precondTime(t),memo:e.memo(),operations:e.operations(),ext:new se.TransactionExt(0)});d=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:n,signatures:d.v0().signatures()}))}l="string"==typeof e?Pn(e):e.xdrMuxedAccount();const p=new se.FeeBumpTransaction({feeSource:l,fee:se.Int64.fromString(u.times(o+1).plus(i).toString()),innerTx:se.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new se.FeeBumpTransactionExt(0)}),h=new se.FeeBumpTransactionEnvelope({tx:p,signatures:[]}),f=se.TransactionEnvelope.envelopeTypeTxFeeBump(h);return new co(f,r)}static fromXDR(e,t){return"string"==typeof e&&(e=se.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===se.EnvelopeType.envelopeTypeTxFeeBump()?new co(e,t):new ao(e,t)}}function _o(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function Po(e){if(void 0===e)return;const t=e instanceof Date?Math.floor(e.getTime()/1e3):Number(e);if(!Number.isFinite(t)||t%1!=0)throw new Error("timebounds value must be a finite integer or Date");return t}var Oo=(e=>(e.PUBLIC="Public Global Stellar Network ; September 2015",e.TESTNET="Test SDF Network ; September 2015",e.FUTURENET="Test SDF Future Network ; October 2022",e.SANDBOX="Local Sandbox Stellar Network ; September 2022",e.STANDALONE="Standalone Network ; February 2017",e))(Oo||{});class Uo{static formatTokenAmount(e,t){if(e.includes("."))throw new TypeError("No decimals are allowed");const n=e.startsWith("-");let r=n?e.slice(1):e;return t>0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.includes(".")&&(r=r.replace(/0+$/,""),r.endsWith(".")&&(r+="0")),r.startsWith(".")&&(r=`0${r}`),n?`-${r}`:r}static parseTokenAmount(e,t){const[n,r,...o]=e.split(".").slice();if(o.length)throw new Error(`Invalid decimal value: ${e}`);if(r?.length&&r.length>t)throw new Error(`Too many decimal places in "${e}": expected at most ${t}, got ${r.length}`);return BigInt(n+(r?.padEnd(t,"0")??"0".repeat(t))).toString()}}function Lo(e){const t="function"==typeof e.contractId?e.contractId():null;return{...null!=t&&{contractId:wn.encodeContract(t)},type:e.type().name,topics:e.body().value().topics().map(e=>ko(e)),data:ko(e.body().value().data())}}function No(e){return e.map(e=>Lo("inSuccessfulContractCall"in e?e.event():e))}function Vo(e){return e instanceof ArrayBuffer?fe.Buffer.from(new Uint8Array(e)):fe.Buffer.from(e)}async function Fo(e,t,n,r,o){if(e.credentials().switch().value===se.SorobanCredentialsType.sorobanCredentialsSourceAccount().value)return e;const s=se.SorobanAuthorizationEntry.fromXDR(e.toXDR()),i=s.credentials(),a=Go(i);if(null===a)throw new Error(`unsupported credential type ${i.switch().name}`);a.signatureExpirationLedger(n);const c=Mo(s,n,r),u=nt(c.toXDR());let l,d;if("function"==typeof t){const e=await t(c);null!==e&&"object"==typeof e&&"signature"in e?(l=Vo(e.signature),d=e.publicKey):(l=Vo(e),d=Xr.fromScAddress(a.address()).toString())}else l=Vo(t.sign(u)),d=t.publicKey();if(!Tn.fromPublicKey(d).verify(u,l))throw new Error("signature doesn't match payload");const p=Eo({public_key:wn.decodeEd25519PublicKey(d),signature:l},{type:{public_key:["symbol",null],signature:["symbol",null]}}),h=se.ScVal.scvVec([p]),f=void 0===o?[a]:function(e){switch(e.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return[e.address()];case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return[e.addressV2()];case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:{const t=e.addressWithDelegates(),n=[t.addressCredentials()],r=e=>{e.forEach(e=>{n.push(e),r(e.nestedDelegates())})};return r(t.delegates()),n}default:return[]}}(i).filter(e=>Xr.fromScAddress(e.address()).toString()===o);if(0===f.length)throw new Error(`the authorization entry has no credential node for address ${o}`);return f.forEach(e=>e.signature(h)),s}function Do(e){const{signer:t,validUntilLedgerSeq:n,invocation:r,networkPassphrase:o,publicKey:s="",authV2:i=!1}=e,a=Tn.random().rawPublicKey(),c=new se.Int64(function(e){const t=e.subarray(0,8);if(t.length<8)throw new Error(`need at least 8 bytes to convert to Int64, got ${e.length}`);const n=new DataView(t.buffer,t.byteOffset,8);return n.getBigInt64(0,!1)}(a)),u=s||(t instanceof Tn?t.publicKey():null);if(!u)throw new Error("authorizeInvocation requires publicKey parameter");const l=new se.SorobanAddressCredentials({address:new Xr(u).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:se.ScVal.scvVec([])});return Fo(new se.SorobanAuthorizationEntry({rootInvocation:r,credentials:i?se.SorobanCredentials.sorobanCredentialsAddressV2(l):se.SorobanCredentials.sorobanCredentialsAddress(l)}),t,n,o)}function Mo(e,t,n){const r=e.credentials(),o=Go(r);if(null===o)throw new Error(`cannot build a signature payload for credential type ${r.switch().name}`);const s=nt(fe.Buffer.from(n));switch(r.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return se.HashIdPreimage.envelopeTypeSorobanAuthorization(new se.HashIdPreimageSorobanAuthorization({networkId:s,nonce:o.nonce(),invocation:e.rootInvocation(),signatureExpirationLedger:t}));case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return se.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(new se.HashIdPreimageSorobanAuthorizationWithAddress({networkId:s,nonce:o.nonce(),invocation:e.rootInvocation(),address:o.address(),signatureExpirationLedger:t}));default:throw new Error(`unsupported credential type ${r.switch().name}`)}}function qo(e){const{entry:t,validUntilLedgerSeq:n,delegates:r,signature:o}=e,s=t.credentials(),i=Go(s);if(null===i||s.switch().value===se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value)throw new Error(`buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${s.switch().name}`);return new se.SorobanAuthorizationEntry({rootInvocation:t.rootInvocation(),credentials:se.SorobanCredentials.sorobanCredentialsAddressWithDelegates(new se.SorobanAddressCredentialsWithDelegates({addressCredentials:new se.SorobanAddressCredentials({address:i.address(),nonce:i.nonce(),signatureExpirationLedger:n,signature:o??se.ScVal.scvVoid()}),delegates:Ho(r)}))})}function Ho(e){const t=e.map(e=>new se.SorobanDelegateSignature({address:new Xr(e.address).toScAddress(),signature:e.signature??se.ScVal.scvVoid(),nestedDelegates:Ho(e.nestedDelegates??[])}));t.sort((e,t)=>fe.Buffer.compare(e.address().toXDR(),t.address().toXDR()));for(let e=1;e<t.length;e++)if(0===fe.Buffer.compare(t[e-1].address().toXDR(),t[e].address().toXDR()))throw new Error(`duplicate delegate address ${Xr.fromScAddress(t[e].address()).toString()}`);return t}function Go(e){switch(e.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return e.address();case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return e.addressV2();case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return e.addressWithDelegates().addressCredentials();default:return null}}function $o(e){const t=e.function(),n={},r=t.value();switch(t.switch().value){case 0:{const e=t.contractFn();n.type="execute",n.args={source:Xr.fromScAddress(e.contractAddress()).toString(),function:e.functionName().toString(),args:e.args().map(e=>ko(e))};break}case 1:case 2:{const e=r,o=2===t.switch().value;n.type="create";const s={},[i,a]=[e.executable(),e.contractIdPreimage()];if(!!i.switch().value!=!!a.switch().value)throw new Error(`creation function appears invalid: ${JSON.stringify(r)} (should be wasm+address or token+asset)`);switch(i.switch().value){case 0:{const e=a.fromAddress();s.type="wasm",s.wasm={salt:fe.Buffer.from(e.salt()).toString("hex"),hash:i.wasmHash().toString("hex"),address:Xr.fromScAddress(e.address()).toString(),...o&&{constructorArgs:r.constructorArgs().map(e=>ko(e))}};break}case 1:s.type="sac",s.asset=In.fromOperation(a.fromAsset()).toString();break;default:throw new Error(`unknown creation type: ${JSON.stringify(i)}`)}n.args=s;break}default:throw new Error(`unknown invocation type (${t.switch().value}): ${JSON.stringify(t)}`)}return n.invocations=e.subInvocations().map(e=>$o(e)),n}function Xo(e,t){Ko(e,1,t)}function Ko(e,t,n,r){!1!==n(e,t,r)&&e.subInvocations().forEach(r=>Ko(r,t+1,n,e))}var Wo=Object.freeze({__proto__:null,Account:uo,Address:Xr,Asset:In,AssetType:En,AuthClawbackEnabledFlag:8,AuthImmutableFlag:4,AuthRequiredFlag:1,AuthRevocableFlag:2,BASE_FEE:xo,Claimant:Rn,Contract:go,FeeBumpTransaction:co,Hyper:oe.Hyper,Int128:Ao,Int256:So,Keypair:Tn,LiquidityPoolAsset:xn,LiquidityPoolFeeV18:30,LiquidityPoolId:_n,Memo:io,MemoHash:oo,MemoID:no,MemoNone:to,MemoReturn:so,MemoText:ro,MuxedAccount:ho,Networks:Oo,Operation:Qr,ScInt:vo,SignerKey:mo,Soroban:Uo,SorobanDataBuilder:fo,StrKey:wn,TimeoutInfinite:0,Transaction:ao,TransactionBase:Bn,TransactionBuilder:Ro,Uint128:yo,Uint256:wo,UnsignedHyper:oe.UnsignedHyper,XdrLargeInt:bo,authorizeEntry:Fo,authorizeInvocation:Do,buildAuthorizationEntryPreimage:Mo,buildInvocationTree:$o,buildWithDelegatesEntry:qo,cereal:ie,decodeAddressToMuxedAccount:Pn,encodeMuxedAccount:Un,encodeMuxedAccountToAddress:On,extractBaseAddress:Ln,getLiquidityPoolId:Cn,hash:nt,humanizeEvents:No,nativeToScVal:Eo,scValToBigInt:To,scValToNative:ko,scvSortedMap:Io,sign:cn,verify:un,walkInvocationTree:Xo,xdr:se});function Zo(e){if(!/^(?:[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)*[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?::\d+)?$/.test(e))throw new Error("The provided domain is invalid. Ensure that the domain adheres to RFC 1035")}const zo=102400;class jo{serverURL;domain;timeout;static async resolve(e,t={}){if(e.indexOf("*")<0)return wn.isValidEd25519PublicKey(e)?Promise.resolve({account_id:e}):Promise.reject(new Error("Invalid Account ID"));const n=e.split("*"),[,r]=n;if(2!==n.length||!r)return Promise.reject(new Error("Invalid Stellar address"));return(await jo.createForDomain(r,t)).resolveAddress(e)}static async createForDomain(e,t={}){Zo(e);const n=await Q.resolve(e,t);return n.FEDERATION_SERVER?new jo(n.FEDERATION_SERVER,e,t):Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))}constructor(e,t,n={}){this.serverURL=new URL(e),this.domain=t,Zo(t);const r=void 0===n.allowHttp?_.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?_.getTimeout():n.timeout,"https:"!==this.serverURL.protocol&&!r)throw new Error("Cannot connect to insecure federation server")}async resolveAddress(e){let t=e;if(e.indexOf("*")<0){if(!this.domain)return Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."));t=`${e}*${this.domain}`}const n=new URL(this.serverURL);return n.search="",n.searchParams.set("type","name"),n.searchParams.set("q",t),this._sendRequest(n)}async resolveAccountId(e){const t=new URL(this.serverURL);return t.search="",t.searchParams.set("type","id"),t.searchParams.set("q",e),this._sendRequest(t)}async resolveTransactionId(e){const t=new URL(this.serverURL);return t.search="",t.searchParams.set("type","txid"),t.searchParams.set("q",e),this._sendRequest(t)}async _sendRequest(e){const t=this.timeout;return T.get(e.toString(),{maxContentLength:zo,timeout:t}).then(e=>{if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data}).catch(e=>{if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of 102400");return Promise.reject(e)}return Promise.reject(new C(`Server query failed. Server responded: ${e.status} ${e.statusText}`,e.data))})}}var Yo=Object.freeze({__proto__:null,FEDERATION_RESPONSE_MAX_SIZE:zo,Server:jo});class Jo extends Error{}function Qo(e,t){const n=e.hash(),r=[...e.signatures],o=new Set;for(const e of t){if(0===r.length)break;let t;try{t=Tn.fromPublicKey(e)}catch(e){throw new Jo(`Signer is not a valid address: ${e.message}`)}for(let s=0;s<r.length;s++){const i=r[s];if(i.hint().equals(t.signatureHint())&&t.verify(n,i.signature())){o.add(e),r.splice(s,1);break}}}return Array.from(o)}function es(e,t){return 0!==Qo(e,[t]).length}const ts=Object.prototype.toString;function ns(e){return function(e,t,n){return!!e&&(e.constructor===t||ts.call(e)===n)}(e,Uint8Array,"[object Uint8Array]")}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder;function rs(e,{urlSafe:t=!1}={}){!function(e){if(!ns(e))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}(e);let n="";for(let t=0;t<e.length;t+=65535){const r=e.subarray(t,t+65535);n+=globalThis.btoa(String.fromCodePoint.apply(void 0,r))}return t?function(e){return e.replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}(n):n}function os(e,t,n,r,o){if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");let s;try{s=new ao(e,n)}catch{try{s=new co(e,n)}catch{throw new Jo("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new Jo("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(s.sequence,10))throw new Jo("The transaction sequence number should be zero");if(s.source!==t)throw new Jo("The transaction source account is not equal to the server's account");if(s.operations.length<1)throw new Jo("The transaction should contain at least one operation");const[i,...a]=s.operations;if(!i.source)throw new Jo("The transaction's operation should contain a source account");const c=i.source;let u,l=null;if(s.memo.type!==to){if(c.startsWith("M"))throw new Jo("The transaction has a memo but the client account ID is a muxed account");if(s.memo.type!==no)throw new Jo("The transaction's memo must be of type `id`");l=s.memo.value}if("manageData"!==i.type)throw new Jo("The transaction's operation type should be 'manageData'");if(s.timeBounds&&0===Number.parseInt(s.timeBounds?.maxTime,10))throw new Jo("The transaction requires non-infinite timebounds");if(!P.validateTimebounds(s,300))throw new Jo("The transaction has expired");if(void 0===i.value)throw new Jo("The transaction's operation values should not be null");if(!i.value)throw new Jo("The transaction's operation value should not be null");if(48!==fe.Buffer.from(i.value.toString(),"base64").length)throw new Jo("The transaction's operation value should be a 64 bytes base64 random string");if(!r)throw new Jo("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof r)`${r} auth`===i.name&&(u=r);else{if(!Array.isArray(r))throw new Jo(`Invalid homeDomains: homeDomains type is ${typeof r} but should be a string or an array`);u=r.find(e=>`${e} auth`===i.name)}if(!u)throw new Jo("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");for(const e of a){if("manageData"!==e.type)throw new Jo("The transaction has operations that are not of type 'manageData'");if(e.source!==t&&"client_domain"!==e.name)throw new Jo("The transaction has operations that are unrecognized");if("web_auth_domain"===e.name){if(void 0===e.value)throw new Jo("'web_auth_domain' operation value should not be null");if(e.value.compare(fe.Buffer.from(o)))throw new Jo(`'web_auth_domain' operation value does not match ${o}`)}}if(!es(s,t))throw new Jo(`Transaction not signed by server: '${t}'`);return{tx:s,clientAccountID:c,matchedHomeDomain:u,memo:l}}function ss(e,t,n,r,o,s){const{tx:i}=os(e,t,n,o,s);let a;try{a=Tn.fromPublicKey(t)}catch(e){throw new Error(`Couldn't infer keypair from the provided 'serverAccountID': ${e.message}`)}const c=new Set;for(const e of r)e!==a.publicKey()&&"G"===e.charAt(0)&&c.add(e);if(0===c.size)throw new Jo("No verifiable client signers provided, at least one G... address must be provided");let u;for(const e of i.operations)if("manageData"===e.type&&"client_domain"===e.name){if(u)throw new Jo("Found more than one client_domain operation");u=e.source}const l=[a.publicKey(),...Array.from(c)];u&&l.push(u);const d=Qo(i,l);let p=!1,h=!1;for(const e of d)e===a.publicKey()&&(p=!0),e===u&&(h=!0);if(!p)throw new Jo(`Transaction not signed by server: '${a.publicKey()}'`);if(u&&!h)throw new Jo("Transaction not signed by the source account of the 'client_domain' ManageData operation");if(1===d.length)throw new Jo("None of the given signers match the transaction signatures");if(d.length!==i.signatures.length)throw new Jo("Transaction has unrecognized signatures");if(d.splice(d.indexOf(a.publicKey()),1),u&&d.splice(d.indexOf(u),1),0===d.length)throw new Jo("None of the given signers match the transaction signatures");return d}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var is,as,cs,us,ls,ds=Object.freeze({__proto__:null,InvalidChallengeError:Jo,buildChallengeTx:function(e,t,n,r=300,o,s,i=null,a=null,c=null){if(t.startsWith("M")&&i)throw Error("memo cannot be used if clientAccountID is a muxed account");const u=new uo(e.publicKey(),"-1"),l=Math.floor(Date.now()/1e3),d=rs(crypto.getRandomValues(new Uint8Array(48))),p=new Ro(u,{fee:xo,networkPassphrase:o,timebounds:{minTime:l,maxTime:l+r}}).addOperation(Qr.manageData({name:`${n} auth`,value:d,source:t})).addOperation(Qr.manageData({name:"web_auth_domain",value:s,source:u.accountId()}));if(a){if(!c)throw Error("clientSigningKey is required if clientDomain is provided");p.addOperation(Qr.manageData({name:"client_domain",value:a,source:c}))}i&&p.addMemo(io.id(i));const h=p.build();return h.sign(e),h.toEnvelope().toXDR("base64").toString()},gatherTxSigners:Qo,readChallengeTx:os,verifyChallengeTxSigners:ss,verifyChallengeTxThreshold:function(e,t,n,r,o,s,i){const a=ss(e,t,n,o.map(e=>e.key),s,i);let c=0;for(const e of a){c+=o.find(t=>t.key===e)?.weight||0}if(c<r)throw new Jo(`signers with weight ${c} do not meet threshold ${r}"`);return a},verifyTxSignedBy:es}),ps=Object.freeze({__proto__:null});((as=is||(is={})).LiquidityPoolType||(as.LiquidityPoolType={})).constantProduct="constant_product",(cs=as.OperationResponseType||(as.OperationResponseType={})).createAccount="create_account",cs.payment="payment",cs.pathPayment="path_payment_strict_receive",cs.createPassiveOffer="create_passive_sell_offer",cs.manageOffer="manage_sell_offer",cs.setOptions="set_options",cs.changeTrust="change_trust",cs.allowTrust="allow_trust",cs.accountMerge="account_merge",cs.inflation="inflation",cs.manageData="manage_data",cs.bumpSequence="bump_sequence",cs.manageBuyOffer="manage_buy_offer",cs.pathPaymentStrictSend="path_payment_strict_send",cs.createClaimableBalance="create_claimable_balance",cs.claimClaimableBalance="claim_claimable_balance",cs.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",cs.endSponsoringFutureReserves="end_sponsoring_future_reserves",cs.revokeSponsorship="revoke_sponsorship",cs.clawback="clawback",cs.clawbackClaimableBalance="clawback_claimable_balance",cs.setTrustLineFlags="set_trust_line_flags",cs.liquidityPoolDeposit="liquidity_pool_deposit",cs.liquidityPoolWithdraw="liquidity_pool_withdraw",cs.invokeHostFunction="invoke_host_function",cs.bumpFootprintExpiration="bump_footprint_expiration",cs.restoreFootprint="restore_footprint",(us=as.OperationResponseTypeI||(as.OperationResponseTypeI={}))[us.createAccount=0]="createAccount",us[us.payment=1]="payment",us[us.pathPayment=2]="pathPayment",us[us.createPassiveOffer=3]="createPassiveOffer",us[us.manageOffer=4]="manageOffer",us[us.setOptions=5]="setOptions",us[us.changeTrust=6]="changeTrust",us[us.allowTrust=7]="allowTrust",us[us.accountMerge=8]="accountMerge",us[us.inflation=9]="inflation",us[us.manageData=10]="manageData",us[us.bumpSequence=11]="bumpSequence",us[us.manageBuyOffer=12]="manageBuyOffer",us[us.pathPaymentStrictSend=13]="pathPaymentStrictSend",us[us.createClaimableBalance=14]="createClaimableBalance",us[us.claimClaimableBalance=15]="claimClaimableBalance",us[us.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",us[us.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",us[us.revokeSponsorship=18]="revokeSponsorship",us[us.clawback=19]="clawback",us[us.clawbackClaimableBalance=20]="clawbackClaimableBalance",us[us.setTrustLineFlags=21]="setTrustLineFlags",us[us.liquidityPoolDeposit=22]="liquidityPoolDeposit",us[us.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",us[us.invokeHostFunction=24]="invokeHostFunction",us[us.bumpFootprintExpiration=25]="bumpFootprintExpiration",us[us.restoreFootprint=26]="restoreFootprint",(ls=as.TransactionFailedResultCodes||(as.TransactionFailedResultCodes={})).TX_FAILED="tx_failed",ls.TX_BAD_SEQ="tx_bad_seq",ls.TX_BAD_AUTH="tx_bad_auth",ls.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",ls.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",ls.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",ls.TX_NOT_SUPPORTED="tx_not_supported",ls.TX_SUCCESS="tx_success",ls.TX_TOO_EARLY="tx_too_early",ls.TX_TOO_LATE="tx_too_late",ls.TX_MISSING_OPERATION="tx_missing_operation",ls.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",ls.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",ls.TX_INSUFFICIENT_FEE="tx_insufficient_fee",ls.TX_INTERNAL_ERROR="tx_internal_error";var hs,fs,ms,gs=(e=>(e[e.account_created=0]="account_created",e[e.account_removed=1]="account_removed",e[e.account_credited=2]="account_credited",e[e.account_debited=3]="account_debited",e[e.account_thresholds_updated=4]="account_thresholds_updated",e[e.account_home_domain_updated=5]="account_home_domain_updated",e[e.account_flags_updated=6]="account_flags_updated",e[e.account_inflation_destination_updated=7]="account_inflation_destination_updated",e[e.signer_created=10]="signer_created",e[e.signer_removed=11]="signer_removed",e[e.signer_updated=12]="signer_updated",e[e.trustline_created=20]="trustline_created",e[e.trustline_removed=21]="trustline_removed",e[e.trustline_updated=22]="trustline_updated",e[e.trustline_authorized=23]="trustline_authorized",e[e.trustline_deauthorized=24]="trustline_deauthorized",e[e.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",e[e.trustline_flags_updated=26]="trustline_flags_updated",e[e.offer_created=30]="offer_created",e[e.offer_removed=31]="offer_removed",e[e.offer_updated=32]="offer_updated",e[e.trade=33]="trade",e[e.data_created=40]="data_created",e[e.data_removed=41]="data_removed",e[e.data_updated=42]="data_updated",e[e.sequence_bumped=43]="sequence_bumped",e[e.claimable_balance_created=50]="claimable_balance_created",e[e.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",e[e.claimable_balance_claimed=52]="claimable_balance_claimed",e[e.account_sponsorship_created=60]="account_sponsorship_created",e[e.account_sponsorship_updated=61]="account_sponsorship_updated",e[e.account_sponsorship_removed=62]="account_sponsorship_removed",e[e.trustline_sponsorship_created=63]="trustline_sponsorship_created",e[e.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",e[e.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",e[e.data_sponsorship_created=66]="data_sponsorship_created",e[e.data_sponsorship_updated=67]="data_sponsorship_updated",e[e.data_sponsorship_removed=68]="data_sponsorship_removed",e[e.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",e[e.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",e[e.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",e[e.signer_sponsorship_created=72]="signer_sponsorship_created",e[e.signer_sponsorship_updated=73]="signer_sponsorship_updated",e[e.signer_sponsorship_removed=74]="signer_sponsorship_removed",e[e.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",e[e.liquidity_pool_deposited=90]="liquidity_pool_deposited",e[e.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",e[e.liquidity_pool_trade=92]="liquidity_pool_trade",e[e.liquidity_pool_created=93]="liquidity_pool_created",e[e.liquidity_pool_removed=94]="liquidity_pool_removed",e[e.liquidity_pool_revoked=95]="liquidity_pool_revoked",e[e.contract_credited=96]="contract_credited",e[e.contract_debited=97]="contract_debited",e))(gs||{});(fs=hs||(hs={})).EffectType=gs,(ms=fs.TradeType||(fs.TradeType={})).all="all",ms.liquidityPools="liquidity_pool",ms.orderbook="orderbook",is.OperationResponseType,is.OperationResponseTypeI;class ys{id;paging_token;account_id;sequence;sequence_ledger;sequence_time;subentry_count;home_domain;inflation_destination;last_modified_ledger;last_modified_time;thresholds;flags;balances;signers;num_sponsoring;num_sponsored;sponsor;data;data_attr;effects;offers;operations;payments;trades;transactions;_baseAccount;constructor(e){this._baseAccount=new uo(e.account_id,e.sequence),this.effects=e.effects,this.offers=e.offers,this.operations=e.operations,this.payments=e.payments,this.trades=e.trades,this.data=e.data,this.transactions=e.transactions,this.id=e.id,this.paging_token=e.paging_token,this.account_id=e.account_id,this.sequence=e.sequence,this.sequence_ledger=e.sequence_ledger,this.sequence_time=e.sequence_time,this.subentry_count=e.subentry_count,this.home_domain=e.home_domain,this.inflation_destination=e.inflation_destination,this.last_modified_ledger=e.last_modified_ledger,this.last_modified_time=e.last_modified_time,this.thresholds=e.thresholds,this.flags=e.flags,this.balances=e.balances,this.signers=e.signers,this.data_attr=e.data_attr,this.sponsor=e.sponsor,this.num_sponsoring=e.num_sponsoring,this.num_sponsored=e.num_sponsored}accountId(){return this._baseAccount.accountId()}sequenceNumber(){return this._baseAccount.sequenceNumber()}incrementSequenceNumber(){this._baseAccount.incrementSequenceNumber(),this.sequence=this._baseAccount.sequenceNumber()}}class ws 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}}const As=32;function Ss(e){}function bs(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=Ss,onError:n=Ss,onRetry:r=Ss,onComment:o}=e,s=[];let i,a,c=!0,u="",l=0;function d(e){let n=0;if(-1===e.indexOf("\r")){let r=e.indexOf("\n",n);for(;-1!==r;){if(n===r){l>0&&t({id:i,event:a,data:u}),i=void 0,u="",l=0,a=void 0,n=r+1,r=e.indexOf("\n",n);continue}const o=e.charCodeAt(n);if(vs(e,n,o)){const o=e.charCodeAt(n+5)===As?n+6:n+5,s=e.slice(o,r);if(0===l&&10===e.charCodeAt(r+1)){t({id:i,event:a,data:s}),i=void 0,u="",a=void 0,n=r+2,r=e.indexOf("\n",n);continue}u=0===l?s:`${u}\n${s}`,l++}else Ts(e,n,o)?a=e.slice(e.charCodeAt(n+6)===As?n+7:n+6,r)||void 0:p(e,n,r);n=r+1,r=e.indexOf("\n",n)}return e.slice(n)}for(;n<e.length;){const t=e.indexOf("\r",n),r=e.indexOf("\n",n);let o=-1;if(-1!==t&&-1!==r?o=t<r?t:r:-1!==t?o=t===e.length-1?-1:t:-1!==r&&(o=r),-1===o)break;p(e,n,o),n=o+1,13===e.charCodeAt(n-1)&&10===e.charCodeAt(n)&&n++}return e.slice(n)}function p(e,n,r){if(n===r)return l>0&&t({id:i,event:a,data:u}),i=void 0,u="",l=0,void(a=void 0);const s=e.charCodeAt(n);if(vs(e,n,s)){const t=e.charCodeAt(n+5)===As?n+6:n+5,o=e.slice(t,r);return u=0===l?o:`${u}\n${o}`,void l++}if(Ts(e,n,s))return void(a=e.slice(e.charCodeAt(n+6)===As?n+7:n+6,r)||void 0);if(105===s&&100===e.charCodeAt(n+1)&&58===e.charCodeAt(n+2)){const t=e.slice(e.charCodeAt(n+3)===As?n+4:n+3,r);return void(i=t.includes("\0")?void 0:t)}if(58===s){if(o){const t=e.slice(n,r);o(t.slice(e.charCodeAt(n+1)===As?2:1))}return}const c=e.slice(n,r),d=c.indexOf(":");if(-1===d)return void h(c,"",c);const p=c.slice(0,d),f=c.charCodeAt(d+1)===As?2:1;h(p,c.slice(d+f),c)}function h(e,t,o){switch(e){case"event":a=t||void 0;break;case"data":u=0===l?t:`${u}\n${t}`,l++;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new ws(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new ws(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){if(c&&(c=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){const t=d(e);return void(""!==t&&s.push(t))}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return void s.push(e);s.push(e);const t=s.join("");s.length=0;const n=d(t);""!==n&&s.push(n)},reset:function(e={}){if(e.consume&&s.length>0){const e=s.join("");p(e,0,e.length)}c=!0,i=void 0,u="",l=0,a=void 0,s.length=0}}}function vs(e,t,n){return 100===n&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function Ts(e,t,n){return 101===n&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class Es 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(Is(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Is(this),t)}}function ks(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(ks).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${ks(e.cause)}`:e.message:`${e}`}function Is(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Cs,Bs,xs,Rs,_s,Ps,Os,Us,Ls,Ns,Vs,Fs,Ds,Ms,qs,Hs,Gs,$s,Xs,Ks,Ws,Zs,zs,js=e=>{throw TypeError(e)},Ys=(e,t,n)=>t.has(e)||js("Cannot "+n),Js=(e,t,n)=>(Ys(e,t,"read from private field"),n?n.call(e):t.get(e)),Qs=(e,t,n)=>t.has(e)?js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ei=(e,t,n,r)=>(Ys(e,t,"write to private field"),t.set(e,n),n),ti=(e,t,n)=>(Ys(e,t,"access private method"),n);class ni extends EventTarget{constructor(e,t){var n,r;super(),Qs(this,Ms),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Qs(this,Cs),Qs(this,Bs),Qs(this,xs),Qs(this,Rs),Qs(this,_s),Qs(this,Ps),Qs(this,Os),Qs(this,Us,null),Qs(this,Ls),Qs(this,Ns),Qs(this,Vs,null),Qs(this,Fs,null),Qs(this,Ds,null),Qs(this,Hs,async e=>{var t;Js(this,Ns).reset();const{body:n,redirected:r,status:o,headers:s}=e;if(204===o)return ti(this,Ms,Ws).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(ei(this,xs,r?new URL(e.url):void 0),200!==o)return void ti(this,Ms,Ws).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void ti(this,Ms,Ws).call(this,'Invalid content type, expected "text/event-stream"',o);if(Js(this,Cs)===this.CLOSED)return;ei(this,Cs,this.OPEN);const i=new Event("open");if(null==(t=Js(this,Ds))||t.call(this,i),this.dispatchEvent(i),"object"!=typeof n||!n||!("getReader"in n))return ti(this,Ms,Ws).call(this,"Invalid response body, expected a web ReadableStream",o),void this.close();const a=new TextDecoder,c=n.getReader();let u=!0;do{const{done:e,value:t}=await c.read();t&&Js(this,Ns).feed(a.decode(t,{stream:!e})),e&&(u=!1,Js(this,Ns).reset(),ti(this,Ms,Zs).call(this))}while(u)}),Qs(this,Gs,e=>{ei(this,Ls,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&ti(this,Ms,Zs).call(this,ks(e))}),Qs(this,Xs,e=>{"string"==typeof e.id&&ei(this,Us,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Js(this,xs)?Js(this,xs).origin:Js(this,Bs).origin,lastEventId:e.id||""});Js(this,Fs)&&(!e.event||"message"===e.event)&&Js(this,Fs).call(this,t),this.dispatchEvent(t)}),Qs(this,Ks,e=>{ei(this,Ps,e)}),Qs(this,zs,()=>{ei(this,Os,void 0),Js(this,Cs)===this.CONNECTING&&ti(this,Ms,qs).call(this)});try{if(e instanceof URL)ei(this,Bs,e);else{if("string"!=typeof e)throw new Error("Invalid URL");ei(this,Bs,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")}ei(this,Ns,bs({onEvent:Js(this,Xs),onRetry:Js(this,Ks)})),ei(this,Cs,this.CONNECTING),ei(this,Ps,3e3),ei(this,_s,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),ei(this,Rs,null!=(r=null==t?void 0:t.withCredentials)&&r),ti(this,Ms,qs).call(this)}get readyState(){return Js(this,Cs)}get url(){return Js(this,Bs).href}get withCredentials(){return Js(this,Rs)}get onerror(){return Js(this,Vs)}set onerror(e){ei(this,Vs,e)}get onmessage(){return Js(this,Fs)}set onmessage(e){ei(this,Fs,e)}get onopen(){return Js(this,Ds)}set onopen(e){ei(this,Ds,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(){Js(this,Os)&&clearTimeout(Js(this,Os)),Js(this,Cs)!==this.CLOSED&&(Js(this,Ls)&&Js(this,Ls).abort(),ei(this,Cs,this.CLOSED),ei(this,Ls,void 0))}}Cs=new WeakMap,Bs=new WeakMap,xs=new WeakMap,Rs=new WeakMap,_s=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Us=new WeakMap,Ls=new WeakMap,Ns=new WeakMap,Vs=new WeakMap,Fs=new WeakMap,Ds=new WeakMap,Ms=new WeakSet,qs=function(){ei(this,Cs,this.CONNECTING),ei(this,Ls,new AbortController),Js(this,_s)(Js(this,Bs),ti(this,Ms,$s).call(this)).then(Js(this,Hs)).catch(Js(this,Gs))},Hs=new WeakMap,Gs=new WeakMap,$s=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Js(this,Us)?{"Last-Event-ID":Js(this,Us)}:void 0},cache:"no-store",signal:null==(e=Js(this,Ls))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Xs=new WeakMap,Ks=new WeakMap,Ws=function(e,t){var n;Js(this,Cs)!==this.CLOSED&&ei(this,Cs,this.CLOSED);const r=new Es("error",{code:t,message:e});null==(n=Js(this,Vs))||n.call(this,r),this.dispatchEvent(r)},Zs=function(e,t){var n;if(Js(this,Cs)===this.CLOSED)return;ei(this,Cs,this.CONNECTING);const r=new Es("error",{code:t,message:e});null==(n=Js(this,Vs))||n.call(this,r),this.dispatchEvent(r),ei(this,Os,setTimeout(Js(this,zs),Js(this,Ps)))},zs=new WeakMap,ni.CONNECTING=0,ni.OPEN=1,ni.CLOSED=2,Object.defineProperty(ni,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});const ri="16.0.0",oi={};function si(e){return Math.floor(e/1e3)}function ii(e){const t=oi[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;const{serverTime:n,localTimeRecorded:r}=t,o=si((new Date).getTime());return o-r>300?null:o-r+n}function ai(e){return Array.isArray(e)?e.join(","):e.toString()}const ci=["transaction"];class ui{url;filter;originalSegments;neighborRoot;httpClient;constructor(e,t,n=""){this.url=new URL(e),this.filter=[],this.originalSegments=this.url.pathname.split("/").filter(e=>e.length>0),this.neighborRoot=n,this.httpClient=t}setPath(...e){const t=e.flatMap(e=>e.split("/").filter(e=>e.length>0));this.url.pathname=this.originalSegments.concat(t).join("/")}call(){return this.checkFilter(),this._sendNormalRequest(this.url).then(e=>this._parseResponse(e))}stream(e={}){this.checkFilter();const t=new URL(this.url);t.searchParams.set("X-Client-Name","js-stellar-sdk"),t.searchParams.set("X-Client-Version",ri);const{headers:n}=this.httpClient.defaults;if(n){["X-App-Name","X-App-Version"].forEach(e=>{let r;if(n instanceof Headers)r=n.get(e)??void 0;else if(Array.isArray(n)){const t=n.find(([t])=>t===e);r=t?.[1]}else r=n[e];r&&t.searchParams.set(e,r)})}let r,o;const s=()=>{o=setTimeout(()=>{r?.close(),r=i()},e.reconnectTimeout||15e3)},i=()=>{try{r=new ni(t.toString())}catch(t){e.onerror&&e.onerror(t)}if(s(),!r)return r;let n=!1;const a=()=>{n||(clearTimeout(o),r.close(),i(),n=!0)},c=n=>{if("close"===n.type)return void a();const r=n.data?this._parseRecord(JSON.parse(n.data)):n;r.paging_token&&t.searchParams.set("cursor",r.paging_token),clearTimeout(o),s(),void 0!==e.onmessage&&e.onmessage(r)},u=t=>{e.onerror&&e.onerror(t)};return r.addEventListener?(r.addEventListener("message",c.bind(this)),r.addEventListener("error",u.bind(this)),r.addEventListener("close",a.bind(this))):(r.onmessage=c.bind(this),r.onerror=u.bind(this)),r};return i(),()=>{clearTimeout(o),r?.close()}}cursor(e){return this.url.searchParams.set("cursor",e),this}limit(e){return this.url.searchParams.set("limit",e.toString()),this}order(e){return this.url.searchParams.set("order",e),this}join(e){return this.url.searchParams.set("join",e),this}forEndpoint(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}checkFilter(){if(this.filter.length>=2)throw new I("Too many filters specified",this.filter);if(1===this.filter.length){const e=this.originalSegments.concat(this.filter[0]);this.url.pathname=e.join("/")}}_requestFnForLink(e){return async(t={})=>{let n;n=e.templated?new URL(function(e,t,n){const r=[],o=e.replace(/\{\?([^}]+)\}/g,(e,t)=>(r.push(...t.split(",")),"")).replace(/\{([^?][^}]*)\}/g,(e,n)=>{const r=t[n];return void 0===r?"":encodeURIComponent(ai(r))}),s=new URL(o,n);return r.forEach(e=>{const n=t[e];void 0!==n&&s.searchParams.set(e,ai(n))}),s.toString()}(e.href,t),this.url):new URL(e.href,this.url);const r=await this._sendNormalRequest(n);return this._parseResponse(r)}}_parseRecord(e){return e._links?(Object.keys(e._links).forEach(t=>{const n=e._links[t];let r=!1;if(void 0!==e[t]&&(e[`${t}_attr`]=e[t],r=!0),r&&ci.indexOf(t)>=0){const n=this._parseRecord(e[t]);e[t]=async()=>n}else e[t]=this._requestFnForLink(n)}),e):e}async _sendNormalRequest(e){const t=new URL(e);return t.protocol=this.url.protocol,t.host=this.url.host,this.httpClient.get(t.toString()).then(e=>e.data).catch(this._handleNetworkError)}_parseResponse(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}_toCollectionPage(e){for(let t=0;t<e._embedded.records.length;t+=1)e._embedded.records[t]=this._parseRecord(e._embedded.records[t]);return{records:e._embedded.records,next:async()=>{const t=await this._sendNormalRequest(new URL(e._links.next.href,this.url));return this._toCollectionPage(t)},prev:async()=>{const t=await this._sendNormalRequest(new URL(e._links.prev.href,this.url));return this._toCollectionPage(t)}}}async _handleNetworkError(e){return e.response&&e.response.status?404===e.response.status?Promise.reject(new k(e.response.statusText??"Not Found",e.response.data)):Promise.reject(new E(e.response.statusText??"Unknown",e.response.data)):Promise.reject(new Error(e.message))}}class li extends ui{constructor(e,t){super(e,t),this.setPath("accounts")}accountId(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forSigner(e){return this.url.searchParams.set("signer",e),this}forAsset(e){return this.url.searchParams.set("asset",`${e}`),this}sponsor(e){return this.url.searchParams.set("sponsor",e),this}forLiquidityPool(e){return this.url.searchParams.set("liquidity_pool",e),this}}class di extends ui{constructor(e,t){super(e,t),this.setPath("assets")}forCode(e){return this.url.searchParams.set("asset_code",e),this}forIssuer(e){return this.url.searchParams.set("asset_issuer",e),this}}class pi extends ui{constructor(e,t){super(e,t),this.setPath("claimable_balances")}claimableBalance(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}sponsor(e){return this.url.searchParams.set("sponsor",e),this}claimant(e){return this.url.searchParams.set("claimant",e),this}asset(e){return this.url.searchParams.set("asset",e.toString()),this}}class hi extends ui{constructor(e,t){super(e,t,"effects"),this.setPath("effects")}forAccount(e){return this.forEndpoint("accounts",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}forOperation(e){return this.forEndpoint("operations",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}}class fi extends ui{constructor(e,t,n){super(e,t),this.setPath("friendbot"),this.url.searchParams.set("addr",n)}}class mi extends ui{constructor(e,t){super(e,t),this.setPath("ledgers")}ledger(e){return this.filter.push(["ledgers",e.toString()]),this}}class gi extends ui{constructor(e,t){super(e,t),this.setPath("liquidity_pools")}forAssets(...e){const t=e.map(e=>e.toString()).join(",");return this.url.searchParams.set("reserves",t),this}forAccount(e){return this.url.searchParams.set("account",e),this}liquidityPoolId(e){if(!e.match(/[a-fA-F0-9]{64}/))throw new TypeError(`${e} does not look like a liquidity pool ID`);const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e.toLowerCase()]),t}}class yi extends ui{constructor(e,t){super(e,t,"offers"),this.setPath("offers")}offer(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}buying(e){const t=e.getIssuer();return e.isNative()||void 0===t?this.url.searchParams.set("buying_asset_type","native"):(this.url.searchParams.set("buying_asset_type",e.getAssetType()),this.url.searchParams.set("buying_asset_code",e.getCode()),this.url.searchParams.set("buying_asset_issuer",t)),this}selling(e){const t=e.getIssuer();return e.isNative()||void 0===t?this.url.searchParams.set("selling_asset_type","native"):(this.url.searchParams.set("selling_asset_type",e.getAssetType()),this.url.searchParams.set("selling_asset_code",e.getCode()),this.url.searchParams.set("selling_asset_issuer",t)),this}sponsor(e){return this.url.searchParams.set("sponsor",e),this}seller(e){return this.url.searchParams.set("seller",e),this}}class wi extends ui{constructor(e,t){super(e,t,"operations"),this.setPath("operations")}operation(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}forClaimableBalance(e){return this.forEndpoint("claimable_balances",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}class Ai extends ui{constructor(e,t,n,r){super(e,t),this.setPath("order_book");const o=n.getIssuer();n.isNative()||void 0===o?this.url.searchParams.set("selling_asset_type","native"):(this.url.searchParams.set("selling_asset_type",n.getAssetType()),this.url.searchParams.set("selling_asset_code",n.getCode()),this.url.searchParams.set("selling_asset_issuer",o));const s=r.getIssuer();r.isNative()||void 0===s?this.url.searchParams.set("buying_asset_type","native"):(this.url.searchParams.set("buying_asset_type",r.getAssetType()),this.url.searchParams.set("buying_asset_code",r.getCode()),this.url.searchParams.set("buying_asset_issuer",s))}}class Si extends ui{constructor(e,t){super(e,t,"payments"),this.setPath("payments")}forAccount(e){return this.forEndpoint("accounts",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}class bi extends ui{constructor(e,t,n,r,o){if(super(e,t),this.setPath("paths/strict-receive"),"string"==typeof n)this.url.searchParams.set("source_account",n);else{const e=n.map(e=>e.isNative()?"native":`${e.getCode()}:${e.getIssuer()}`).join(",");this.url.searchParams.set("source_assets",e)}this.url.searchParams.set("destination_amount",o);const s=r.getIssuer();r.isNative()||void 0===s?this.url.searchParams.set("destination_asset_type","native"):(this.url.searchParams.set("destination_asset_type",r.getAssetType()),this.url.searchParams.set("destination_asset_code",r.getCode()),this.url.searchParams.set("destination_asset_issuer",s))}}class vi extends ui{constructor(e,t,n,r,o){super(e,t),this.setPath("paths/strict-send");const s=n.getIssuer();if(n.isNative()?this.url.searchParams.set("source_asset_type","native"):void 0!==s&&(this.url.searchParams.set("source_asset_type",n.getAssetType()),this.url.searchParams.set("source_asset_code",n.getCode()),this.url.searchParams.set("source_asset_issuer",s)),this.url.searchParams.set("source_amount",r),"string"==typeof o)this.url.searchParams.set("destination_account",o);else{const e=o.map(e=>e.isNative()?"native":`${e.getCode()}:${e.getIssuer()}`).join(",");this.url.searchParams.set("destination_assets",e)}}}const Ti=[6e4,3e5,9e5,36e5,864e5,6048e5];class Ei extends ui{constructor(e,t,n,r,o,s,i,a){super(e,t),this.setPath("trade_aggregations");const c=n.getIssuer();n.isNative()||void 0===c?this.url.searchParams.set("base_asset_type","native"):(this.url.searchParams.set("base_asset_type",n.getAssetType()),this.url.searchParams.set("base_asset_code",n.getCode()),this.url.searchParams.set("base_asset_issuer",c));const u=r.getIssuer();if(r.isNative()||void 0===u?this.url.searchParams.set("counter_asset_type","native"):(this.url.searchParams.set("counter_asset_type",r.getAssetType()),this.url.searchParams.set("counter_asset_code",r.getCode()),this.url.searchParams.set("counter_asset_issuer",u)),"number"!=typeof o||"number"!=typeof s)throw new I("Invalid time bounds",[o,s]);if(this.url.searchParams.set("start_time",o.toString()),this.url.searchParams.set("end_time",s.toString()),!this.isValidResolution(i))throw new I("Invalid resolution",i);if(this.url.searchParams.set("resolution",i.toString()),!this.isValidOffset(a,i))throw new I("Invalid offset",a);this.url.searchParams.set("offset",a.toString())}isValidResolution(e){return Ti.some(t=>t===e)}isValidOffset(e,t){const n=36e5;return!(e>t||e>=24*n||e%n!==0)}}class ki extends ui{constructor(e,t){super(e,t,"trades"),this.setPath("trades")}forAssetPair(e,t){const n=e.getIssuer();e.isNative()||void 0===n?this.url.searchParams.set("base_asset_type","native"):(this.url.searchParams.set("base_asset_type",e.getAssetType()),this.url.searchParams.set("base_asset_code",e.getCode()),this.url.searchParams.set("base_asset_issuer",n));const r=t.getIssuer();return t.isNative()||void 0===r?this.url.searchParams.set("counter_asset_type","native"):(this.url.searchParams.set("counter_asset_type",t.getAssetType()),this.url.searchParams.set("counter_asset_code",t.getCode()),this.url.searchParams.set("counter_asset_issuer",r)),this}forOffer(e){return this.url.searchParams.set("offer_id",e),this}forType(e){return this.url.searchParams.set("trade_type",e),this}forAccount(e){return this.forEndpoint("accounts",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}}class Ii extends ui{constructor(e,t){super(e,t,"transactions"),this.setPath("transactions")}transaction(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}forClaimableBalance(e){return this.forEndpoint("claimable_balances",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}function Ci(e){return new tr(e).div(1e7).toString()}var Bi,xi=Object.freeze({__proto__:null,AccountResponse:ys,get HorizonApi(){return is},SERVER_TIME_MAP:oi,Server:class{serverURL;httpClient;constructor(e,t={}){this.serverURL=new URL(e);const n=void 0===t.allowHttp?_.isAllowHttp():t.allowHttp,r={};if(t.appName&&(r["X-App-Name"]=t.appName),t.appVersion&&(r["X-App-Version"]=t.appVersion),t.authToken&&(r["X-Auth-Token"]=t.authToken),t.headers&&Object.assign(r,t.headers),this.httpClient=function(e){const t=v({headers:{...e,"X-Client-Name":"js-stellar-sdk","X-Client-Version":ri}});return t.interceptors.response.use(e=>{const t=e.config.url;if(!t)return e;const n=new URL(t),r=n.port,o=r?`${n.hostname}:${r}`:n.hostname;let s=0;if(e.headers instanceof Headers){const t=e.headers.get("date");t&&(s=si(Date.parse(t)))}else if("object"==typeof e.headers&&"date"in e.headers){const t=e.headers;"string"==typeof t.date&&(s=si(Date.parse(t.date)))}const i=si((new Date).getTime());return Number.isNaN(s)||(oi[o]={serverTime:s,localTimeRecorded:i}),e}),t}(r),"https:"!==this.serverURL.protocol&&!n)throw new Error("Cannot connect to insecure horizon server")}async fetchTimebounds(e,t=!1){const n=this.serverURL.port,r=ii(n?`${this.serverURL.hostname}:${n}`:this.serverURL.hostname);return r?{minTime:0,maxTime:r+e}:t?{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+e}:(await this.httpClient.get(this.serverURL.toString()),this.fetchTimebounds(e,!0))}async fetchBaseFee(){const e=await this.feeStats();return parseInt(e.last_ledger_base_fee,10)||100}async feeStats(){const e=new ui(this.serverURL,this.httpClient);return e.filter.push(["fee_stats"]),e.call()}async root(){return new ui(this.serverURL,this.httpClient).call()}async submitTransaction(e,t={skipMemoRequiredCheck:!1}){t.skipMemoRequiredCheck||await this.checkMemoRequired(e);const n=encodeURIComponent(e.toEnvelope().toXDR().toString("base64")),r=new URL(this.serverURL);return r.pathname=r.pathname.split("/").concat(["transactions"]).filter(e=>e.length>0).join("/"),this.httpClient.post(r.toString(),`tx=${n}`,{timeout:6e4,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{if(!e.data.result_xdr)return e.data;const t=se.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();let n,r;return t.length&&(n=t.map((e,t)=>{if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;let n=new tr(0),o=new tr(0);const s=e.value().value().success(),i=s.offersClaimed().map(e=>{const t=e.value();let r="";switch(e.switch()){case se.ClaimAtomType.claimAtomTypeV0():r=wn.encodeEd25519PublicKey(t.sellerEd25519());break;case se.ClaimAtomType.claimAtomTypeOrderBook():r=wn.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error(`Invalid offer result type: ${e.switch()}`)}const s=new tr(t.amountBought().toString()),i=new tr(t.amountSold().toString());n=n.plus(i),o=o.plus(s);const a=In.fromOperation(t.assetSold()),c=In.fromOperation(t.assetBought()),u={type:a.getAssetType(),assetCode:a.getCode(),issuer:a.getIssuer()},l={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:u,amountSold:Ci(i),assetBought:l,amountBought:Ci(s)}}),a=s.offer().switch().name;let c;if("function"==typeof s.offer().value&&s.offer().value()){const e=s.offer().value();c={offerId:e.offerId().toString(),selling:{},buying:{},amount:Ci(e.amount().toString()),price:{n:e.price().n(),d:e.price().d()}};const t=In.fromOperation(e.selling());c.selling={type:t.getAssetType(),assetCode:t.getCode(),issuer:t.getIssuer()};const n=In.fromOperation(e.buying());c.buying={type:n.getAssetType(),assetCode:n.getCode(),issuer:n.getIssuer()}}return{offersClaimed:i,effect:a,operationIndex:t,currentOffer:c,amountBought:Ci(n),amountSold:Ci(o),isFullyOpen:!i.length&&"manageOfferDeleted"!==a,wasPartiallyFilled:!!i.length&&"manageOfferDeleted"!==a,wasImmediatelyFilled:!!i.length&&"manageOfferDeleted"===a,wasImmediatelyDeleted:!i.length&&"manageOfferDeleted"===a}}).filter(e=>!!e)),{...e.data,offerResults:r?n:void 0}}).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new C(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}async submitAsyncTransaction(e,t={skipMemoRequiredCheck:!1}){t.skipMemoRequiredCheck||await this.checkMemoRequired(e);const n=encodeURIComponent(e.toEnvelope().toXDR().toString("base64")),r=new URL(this.serverURL);return r.pathname=r.pathname.split("/").concat(["transactions_async"]).filter(e=>e.length>0).join("/"),this.httpClient.post(r.toString(),`tx=${n}`,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>e.data).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new C(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}accounts(){return new li(this.serverURL,this.httpClient)}claimableBalances(){return new pi(this.serverURL,this.httpClient)}ledgers(){return new mi(this.serverURL,this.httpClient)}transactions(){return new Ii(this.serverURL,this.httpClient)}offers(){return new yi(this.serverURL,this.httpClient)}orderbook(e,t){return new Ai(this.serverURL,this.httpClient,e,t)}trades(){return new ki(this.serverURL,this.httpClient)}operations(){return new wi(this.serverURL,this.httpClient)}liquidityPools(){return new gi(this.serverURL,this.httpClient)}strictReceivePaths(e,t,n){return new bi(this.serverURL,this.httpClient,e,t,n)}strictSendPaths(e,t,n){return new vi(this.serverURL,this.httpClient,e,t,n)}payments(){return new Si(this.serverURL,this.httpClient)}effects(){return new hi(this.serverURL,this.httpClient)}friendbot(e){return new fi(this.serverURL,this.httpClient,e)}assets(){return new di(this.serverURL,this.httpClient)}async loadAccount(e){const t=await this.accounts().accountId(e).call();return new ys(t)}tradeAggregation(e,t,n,r,o,s){return new Ei(this.serverURL,this.httpClient,e,t,n,r,o,s)}async checkMemoRequired(e){if(e instanceof co&&(e=e.innerTransaction),"none"!==e.memo.type)return;const t=new Set;for(let n=0;n<e.operations.length;n+=1){const r=e.operations[n];switch(r.type){case"payment":case"pathPaymentStrictReceive":case"pathPaymentStrictSend":case"accountMerge":break;default:continue}const o=r.destination;if(!t.has(o)&&(t.add(o),!o.startsWith("M")))try{if("MQ=="===(await this.loadAccount(o)).data_attr["config.memo_required"])throw new B("account requires memo",o,n)}catch(e){if(e instanceof B)throw e;if(!(e instanceof k))throw e;continue}}}},get ServerApi(){return hs},getCurrentServerTime:ii});(e=>{var t;function n(e){return"transactionData"in e}(t=e.GetTransactionStatus||(e.GetTransactionStatus={})).SUCCESS="SUCCESS",t.NOT_FOUND="NOT_FOUND",t.FAILED="FAILED",e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=n,e.isSimulationRestore=function(e){return n(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}})(Bi||(Bi={}));async function Ri(e,t,n,r=null){const o=await e.post(t,{jsonrpc:"2.0",id:1,method:n,params:r});if(s=o.data,i="error",Object.prototype.hasOwnProperty.call(s,i))throw o.data.error;return o.data?.result;var s,i}function _i(e){const{errorResultXdr:t,diagnosticEventsXdr:n}=e;return delete e.errorResultXdr,delete e.diagnosticEventsXdr,t?{...e,...void 0!==n&&n.length>0&&{diagnosticEvents:n.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))},errorResult:se.TransactionResult.fromXDR(t,"base64")}:{...e}}function Pi(e){const t=se.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),n={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:se.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:se.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:t,events:{contractEventsXdr:(e.events?.contractEventsXdr??[]).map(e=>e.map(e=>se.ContractEvent.fromXDR(e,"base64"))),transactionEventsXdr:(e.events?.transactionEventsXdr??[]).map(e=>se.TransactionEvent.fromXDR(e,"base64"))}};switch(t.switch()){case 3:case 4:{const e=t.value();null!==e.sorobanMeta()&&(n.returnValue=e.sorobanMeta()?.returnValue()??void 0)}}return e.diagnosticEventsXdr&&(n.diagnosticEventsXdr=e.diagnosticEventsXdr.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))),n}function Oi(e){return{status:e.status,txHash:e.txHash,...Pi(e)}}function Ui(e){return{latestLedger:e.latestLedger,oldestLedger:e.oldestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor,events:(e.events??[]).map(e=>{const t={...e};return delete t.contractId,{...t,...""!==e.contractId&&{contractId:new go(e.contractId)},topic:(e.topic??[]).map(e=>se.ScVal.fromXDR(e,"base64")),value:se.ScVal.fromXDR(e.value,"base64")}})}}function Li(e){return{latestLedger:e.latestLedger,entries:(e.entries??[]).map(e=>{if(!e.key||!e.xdr)throw new TypeError(`invalid ledger entry: ${JSON.stringify(e)}`);return{lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:se.LedgerKey.fromXDR(e.key,"base64"),val:se.LedgerEntryData.fromXDR(e.xdr,"base64"),...void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq}}})}}function Ni(e){if(!Bi.isSimulationRaw(e))return e;const t={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:e.events?.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))??[]};return"string"==typeof e.error?{...t,error:e.error}:function(e,t){const n={...t,transactionData:new fo(e.transactionData),minResourceFee:e.minResourceFee,...(e.results?.length??0)>0&&{result:e.results.map(e=>({auth:(e.auth??[]).map(e=>se.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:e.xdr?se.ScVal.fromXDR(e.xdr,"base64"):se.ScVal.scvVoid()}))[0]},...(e.stateChanges?.length??0)>0&&{stateChanges:e.stateChanges?.map(e=>({type:e.type,key:se.LedgerKey.fromXDR(e.key,"base64"),before:e.before?se.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?se.LedgerEntry.fromXDR(e.after,"base64"):null}))}};return e.restorePreamble&&""!==e.restorePreamble.transactionData?{...n,restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new fo(e.restorePreamble.transactionData)}}:n}(e,t)}function Vi(e){if(!e.metadataXdr||!e.headerXdr){let t;throw t=e.metadataXdr||e.headerXdr?e.metadataXdr?"headerXdr":"metadataXdr":"metadataXdr and headerXdr",new TypeError(`invalid ledger missing fields: ${t}`)}const t=se.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64"),n=se.LedgerHeaderHistoryEntry.fromXDR(e.headerXdr,"base64");return{hash:e.hash,sequence:e.sequence,ledgerCloseTime:e.ledgerCloseTime,metadataXdr:t,headerXdr:n}}function Fi(e){const t=se.LedgerHeader.fromXDR(e.headerXdr,"base64"),n=se.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64");let r;if(e.metadataXdr||e.headerXdr?e.metadataXdr?e.headerXdr||(r="headerXdr"):r="metadataXdr":r="metadataXdr and headerXdr",r)throw new TypeError(`invalid getLatestLedger response missing fields: ${r}`);return{id:e.id,sequence:e.sequence,protocolVersion:e.protocolVersion,closeTime:e.closeTime,headerXdr:t,metadataXdr:n}}function Di(e,t){if("innerTransaction"in e)return Di(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");const n=Ni(t);if(!Bi.isSimulationSuccess(n))throw new Error(`simulation incorrect: ${JSON.stringify(n)}`);let r;try{r=BigInt(e.fee)}catch{r=BigInt(0)}const o=e.toEnvelope().v1().tx().ext().value();o&&r-o.resourceFee().toBigInt()>BigInt(0)&&(r-=o.resourceFee().toBigInt());const s=Ro.cloneFrom(e,{fee:r.toString(),sorobanData:n.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){s.clearOperations();const t=e.operations[0],r=t.auth??[];s.addOperation(Qr.invokeHostFunction({source:t.source,func:t.func,auth:r.length>0?r:n.result.auth}))}return s}var Mi=(e=>(e.Temporary="temporary",e.Persistent="persistent",e))(Mi||{});const qi=e=>1e3;class Hi{serverURL;httpClient;constructor(e,t={}){var n;if(this.serverURL=new URL(e),this.httpClient=(n=t.headers,v({headers:{...n,"X-Client-Name":"js-stellar-sdk","X-Client-Version":"16.0.0"}})),"https:"!==this.serverURL.protocol&&!t.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")}async getAccount(e){const t=await this.getAccountEntry(e);return new uo(e,t.seqNum().toString())}async getAccountEntry(e){const t=se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e).xdrPublicKey()}));try{return(await this.getLedgerEntry(t)).val.account()}catch{throw new Error(`Account not found: ${e}`)}}async getTrustline(e,t){const n=se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(e).xdrAccountId(),asset:t.toTrustLineXDRObject()}));try{return(await this.getLedgerEntry(n)).val.trustLine()}catch{throw new Error(`Trustline for ${t.getCode()}:${t.getIssuer()} not found for ${e}`)}}async getClaimableBalance(e){let t;if(wn.isValidClaimableBalance(e)){const n=wn.decodeClaimableBalance(e),r=fe.Buffer.concat([fe.Buffer.from("\0\0\0"),n.subarray(0,1)]);t=se.ClaimableBalanceId.fromXDR(fe.Buffer.concat([r,n.subarray(1)]))}else if(e.match(/[a-f0-9]{72}/i))t=se.ClaimableBalanceId.fromXDR(e,"hex");else{if(!e.match(/[a-f0-9]{64}/i))throw new TypeError(`expected 72-char hex ID or strkey, not ${e}`);t=se.ClaimableBalanceId.fromXDR(e.padStart(72,"0"),"hex")}const n=se.LedgerKey.claimableBalance(new se.LedgerKeyClaimableBalance({balanceId:t}));try{return(await this.getLedgerEntry(n)).val.claimableBalance()}catch{throw new Error(`Claimable balance ${e} not found`)}}async getAssetBalance(e,t,n){let r=e;if("string"==typeof e)r=e;else if(e instanceof Xr)r=e.toString();else{if(!(e instanceof go))throw new TypeError(`invalid address: ${e}`);r=e.toString()}if(wn.isValidEd25519PublicKey(r)){const[e,n]=await Promise.all([this.getTrustline(r,t),this.getLatestLedger()]);return{latestLedger:n.sequence,balanceEntry:{amount:e.balance().toString(),authorized:Boolean(1&e.flags()),clawback:Boolean(4&e.flags()),authorizedToMaintainLiabilities:Boolean(2&e.flags()),revocable:Boolean(2&e.flags())}}}if(wn.isValidContract(r))return this.getSACBalance(r,t,n);throw new Error(`invalid address: ${e}`)}async getHealth(){return Ri(this.httpClient,this.serverURL.toString(),"getHealth")}async getContractData(e,t,n="persistent"){let r,o;if("string"==typeof e)r=new go(e).address().toScAddress();else if(e instanceof Xr)r=e.toScAddress();else{if(!(e instanceof go))throw new TypeError(`unknown contract type: ${e}`);r=e.address().toScAddress()}switch(n){case"temporary":o=se.ContractDataDurability.temporary();break;case"persistent":o=se.ContractDataDurability.persistent();break;default:throw new TypeError(`invalid durability: ${n}`)}const s=se.LedgerKey.contractData(new se.LedgerKeyContractData({key:t,contract:r,durability:o}));try{return await this.getLedgerEntry(s)}catch{throw{code:404,message:`Contract data not found for ${Xr.fromScAddress(r).toString()} with key ${t.toXDR("base64")} and durability: ${n}`}}}async getContractWasmByContractId(e){const t=new go(e).getFootprint(),n=await this.getLedgerEntries(t);if(!n.entries.length||!n.entries[0]?.val)return Promise.reject({code:404,message:"Could not obtain contract hash from server"});const r=n.entries[0].val.contractData().val().instance().executable().wasmHash();return this.getContractWasmByHash(r)}async getContractWasmByHash(e,t=void 0){const n="string"==typeof e?fe.Buffer.from(e,t):e,r=se.LedgerKey.contractCode(new se.LedgerKeyContractCode({hash:n})),o=await this.getLedgerEntries(r);if(!o.entries.length||!o.entries[0]?.val)return Promise.reject({code:404,message:"Could not obtain contract wasm from server"});return o.entries[0].val.contractCode().code()}getLedgerEntries(...e){return this._getLedgerEntries(...e).then(Li)}_getLedgerEntries(...e){return Ri(this.httpClient,this.serverURL.toString(),"getLedgerEntries",{keys:e.map(e=>e.toXDR("base64"))})}async getLedgerEntry(e){const t=await this._getLedgerEntries(e).then(Li);if(1!==t.entries.length)throw new Error(`failed to find an entry for key ${e.toXDR("base64")}`);return t.entries[0]}async pollTransaction(e,t){const n=(t?.attempts??0)<1?30:t?.attempts??30;let r;for(let o=1;o<=n;o++){if(r=await this.getTransaction(e),r.status!==Bi.GetTransactionStatus.NOT_FOUND)return r;await P.sleep((t?.sleepStrategy??qi)(o))}return r}async getTransaction(e){return this._getTransaction(e).then(t=>{const n={};t.status!==Bi.GetTransactionStatus.NOT_FOUND&&Object.assign(n,Pi(t));return{status:t.status,txHash:e,latestLedger:t.latestLedger,latestLedgerCloseTime:t.latestLedgerCloseTime,oldestLedger:t.oldestLedger,oldestLedgerCloseTime:t.oldestLedgerCloseTime,...n}})}async _getTransaction(e){return Ri(this.httpClient,this.serverURL.toString(),"getTransaction",{hash:e})}async getTransactions(e){return this._getTransactions(e).then(e=>({transactions:(e.transactions||[]).map(Oi),latestLedger:e.latestLedger,latestLedgerCloseTimestamp:e.latestLedgerCloseTimestamp,oldestLedger:e.oldestLedger,oldestLedgerCloseTimestamp:e.oldestLedgerCloseTimestamp,cursor:e.cursor}))}async _getTransactions(e){return Ri(this.httpClient,this.serverURL.toString(),"getTransactions",e)}async getEvents(e){return this._getEvents(e).then(Ui)}async _getEvents(e){return Ri(this.httpClient,this.serverURL.toString(),"getEvents",{filters:e.filters??[],pagination:{...e.cursor&&{cursor:e.cursor},...e.limit&&{limit:e.limit}},...e.startLedger&&{startLedger:e.startLedger},...e.endLedger&&{endLedger:e.endLedger}})}async getNetwork(){return Ri(this.httpClient,this.serverURL.toString(),"getNetwork")}async getLatestLedger(){return this._getLatestLedger().then(Fi)}async _getLatestLedger(){return Ri(this.httpClient,this.serverURL.toString(),"getLatestLedger")}async simulateTransaction(e,t,n){return this._simulateTransaction(e,t,n).then(Ni)}async _simulateTransaction(e,t,n){return Ri(this.httpClient,this.serverURL.toString(),"simulateTransaction",{transaction:e.toXDR(),authMode:n,...void 0!==t&&{resourceConfig:{instructionLeeway:t.cpuInstructions}}})}async prepareTransaction(e){const t=await this.simulateTransaction(e);if(Bi.isSimulationError(t))throw new Error(t.error);return Di(e,t).build()}async sendTransaction(e){return this._sendTransaction(e).then(_i)}async _sendTransaction(e){return Ri(this.httpClient,this.serverURL.toString(),"sendTransaction",{transaction:e.toXDR()})}async requestAirdrop(e,t){const n="string"==typeof e?e:e.accountId();if(!(t=t||(await this.getNetwork()).friendbotUrl))throw new Error("No friendbot URL configured for current network");try{const r=await this.httpClient.post(`${t}?addr=${encodeURIComponent(n)}`);let o;if(r.data.result_meta_xdr)o=se.TransactionMeta.fromXDR(r.data.result_meta_xdr,"base64");else{const t=await this.getTransaction(r.data.hash);if(t.status!==Bi.GetTransactionStatus.SUCCESS)throw new Error(`Funding account ${e} failed`);o=t.resultMetaXdr}const s=function(e){let t=[];switch(e.switch()){case 0:t=e.operations();break;case 1:case 2:case 3:case 4:t=e.value().operations();break;default:throw new Error("Unexpected transaction meta switch value")}const n=t.flatMap(e=>e.changes()).find(e=>e.switch()===se.LedgerEntryChangeType.ledgerEntryCreated()&&e.created().data().switch()===se.LedgerEntryType.account())?.created()?.data()?.account()?.seqNum()?.toString();if(n)return n;throw new Error("No account created in transaction")}(o);return new uo(n,s)}catch(e){if(400===e.response?.status&&e.response.data?.detail?.includes("createAccountAlreadyExist"))return this.getAccount(n);throw e}}async fundAddress(e,t){if(!wn.isValidEd25519PublicKey(e)&&!wn.isValidContract(e))throw new Error(`Invalid address: ${e}. Expected a Stellar account (G...) or contract (C...) address.`);if(!(t=t||(await this.getNetwork()).friendbotUrl))throw new Error("No friendbot URL configured for current network");try{const n=await this.httpClient.post(`${t}?addr=${encodeURIComponent(e)}`),r=await this.getTransaction(n.data.hash);if(r.status!==Bi.GetTransactionStatus.SUCCESS)throw new Error(`Funding address ${e} failed: transaction status ${r.status}`);return r}catch(e){if(400===e.response?.status)throw new Error(e.response.data?.detail??"Bad Request");throw e}}async getFeeStats(){return Ri(this.httpClient,this.serverURL.toString(),"getFeeStats")}async getVersionInfo(){return Ri(this.httpClient,this.serverURL.toString(),"getVersionInfo")}async getSACBalance(e,t,n){const r=e instanceof Xr?e.toString():e;if(!wn.isValidContract(r))throw new TypeError(`expected contract ID, got ${r}`);const o=n??await this.getNetwork().then(e=>e.passphrase),s=t.contractId(o),i=Eo(["Balance",r],{type:["symbol","address"]}),a=se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:new Xr(s).toScAddress(),durability:se.ContractDataDurability.persistent(),key:i})),c=await this.getLedgerEntries(a);if(0===c.entries.length)return{latestLedger:c.latestLedger};const{lastModifiedLedgerSeq:u,liveUntilLedgerSeq:l,val:d}=c.entries[0];if(d.switch().value!==se.LedgerEntryType.contractData().value)return{latestLedger:c.latestLedger};const p=ko(d.contractData().val());return{latestLedger:c.latestLedger,balanceEntry:{liveUntilLedgerSeq:l,lastModifiedLedgerSeq:u,amount:p.amount.toString(),authorized:p.authorized,clawback:p.clawback}}}async getLedgers(e){return this._getLedgers(e).then(e=>({ledgers:(e.ledgers||[]).map(Vi),latestLedger:e.latestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedger:e.oldestLedger,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor}))}async _getLedgers(e){return Ri(this.httpClient,this.serverURL.toString(),"getLedgers",e)}}var Gi=Object.freeze({__proto__:null,get Api(){return Bi},BasicSleepStrategy:qi,Durability:Mi,LinearSleepStrategy:e=>1e3*e,Server:Hi,assembleTransaction:Di,parseRawEvents:Ui,parseRawSimulation:Ni});class $i{constructor(e){this.value=e}value;unwrapErr(){throw new Error("No error")}unwrap(){return this.value}isOk(){return!0}isErr(){return!1}}class Xi{constructor(e){this.error=e}error;unwrapErr(){return this.error}unwrap(){throw new Error(this.error.message)}isOk(){return!1}isErr(){return!0}}const Ki=300,Wi="GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";const Zi=/Error\(Contract, #(\d+)\)/;function zi(e){const t=new ie.XdrReader(e),n=[];for(;!t.eof;)n.push(se.ScSpecEntry.read(t));return n}async function ji(e,t){return e.publicKey?t.getAccount(e.publicKey):new uo(Wi,"0")}class Yi{constructor(e){this.assembled=e;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.assembled.options;this.server=t??new Hi(o,{allowHttp:n,headers:r})}assembled;server;sendTransactionResponse;getTransactionResponseAll;getTransactionResponse;static Errors={SendFailed:class extends Error{},SendResultOnly:class extends Error{},TransactionStillPending:class extends Error{}};static init=async(e,t)=>{const n=new Yi(e);return await n.send(t)};send=async e=>{if(this.sendTransactionResponse=await this.server.sendTransaction(this.assembled.signed),"PENDING"!==this.sendTransactionResponse.status)throw new Yi.Errors.SendFailed(`Sending the transaction to the network failed!\n${JSON.stringify(this.sendTransactionResponse,null,2)}`);e?.onSubmitted&&e.onSubmitted(this.sendTransactionResponse);const{hash:t}=this.sendTransactionResponse,n=this.assembled.options.timeoutInSeconds??Ki;if(this.getTransactionResponseAll=await async function(e,t,n,r=1.5,o=!1){const s=[];let i=0;if(s.push(await e()),!t(s[s.length-1]))return s;const a=new Date(Date.now()+1e3*n).valueOf();let c=1e3,u=c;for(;Date.now()<a&&t(s[s.length-1]);)i+=1,o&&console.info(`Waiting ${c}ms before trying again (bringing the total wait time to ${u}ms so far, of total ${1e3*n}ms)`),await new Promise(e=>setTimeout(e,c)),c*=r,new Date(Date.now()+c).valueOf()>a&&(c=a-Date.now(),o&&console.info(`was gonna wait too long; new waitTime: ${c}ms`)),u=c+u,s.push(await e(s[s.length-1])),o&&t(s[s.length-1])&&console.info(`${i}. Called ${e}; ${s.length} prev attempts. Most recent: ${JSON.stringify(s[s.length-1],null,2)}`);return s}(async()=>{const n=await this.server.getTransaction(t);return e?.onProgress&&e.onProgress(n),n},e=>e.status===Bi.GetTransactionStatus.NOT_FOUND,n),this.getTransactionResponse=this.getTransactionResponseAll[this.getTransactionResponseAll.length-1],this.getTransactionResponse.status===Bi.GetTransactionStatus.NOT_FOUND)throw new Yi.Errors.TransactionStillPending(`Waited ${n} seconds for transaction to complete, but it did not. Returning anyway. Check the transaction status manually. Sent transaction: ${JSON.stringify(this.sendTransactionResponse,null,2)}\nAll attempts to get the result: ${JSON.stringify(this.getTransactionResponseAll,null,2)}`);return this};get result(){if("getTransactionResponse"in this&&this.getTransactionResponse){if("returnValue"in this.getTransactionResponse)return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue);throw new Error("Transaction failed! Cannot parse result.")}if(this.sendTransactionResponse){const e=this.sendTransactionResponse.errorResult?.result();if(e)throw new Yi.Errors.SendFailed(`Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${e}`);throw new Yi.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`")}throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled.signed)}`)}}class Ji extends Error{}class Qi extends Error{}class ea extends Error{}class ta extends Error{}class na extends Error{}class ra extends Error{}class oa extends Error{}class sa extends Error{}class ia extends Error{}class aa extends Error{}class ca extends Error{}class ua extends Error{}class la extends Error{}class da{constructor(e){this.options=e,this.options.simulate=this.options.simulate??!0;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.options;this.server=t??new Hi(o,{allowHttp:n,headers:r})}options;raw;originalOp;built;simulation;simulationResult;simulationTransactionData;server;signed;static Errors={ExpiredState:Ji,RestorationFailure:Qi,NeedsMoreSignatures:ea,NoSignatureNeeded:ta,NoUnsignedNonInvokerAuthEntries:na,NoSigner:ra,NotYetSimulated:oa,FakeAccount:sa,SimulationFailed:ia,InternalWalletError:aa,ExternalServiceError:ca,InvalidClientRequest:ua,UserRejected:la};toJSON(){return JSON.stringify({method:this.options.method,tx:this.built?.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map(e=>e.toXDR("base64")),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}static validateInvokeContractOp(e,t){if(1!==e.operations.length)throw new Error("Transaction envelope must contain exactly one operation.");const n=e.operations[0];if("invokeHostFunction"!==n.type)throw new Error("Transaction envelope does not contain an invokeHostFunction operation.");const r=n;if("hostFunctionTypeInvokeContract"!==r.func.switch().name)throw new Error("Transaction envelope does not contain an invokeContract host function.");const o=r.func.value();let s,i;try{s=o.contractAddress(),i=o.functionName().toString("utf-8")}catch{throw new Error("Could not extract contract address or method name from the transaction envelope.")}if(!s||!i)throw new Error("Could not extract contract address or method name from the transaction envelope.");const a=Xr.fromScAddress(s).toString();if(a!==t)throw new Error(`Transaction envelope targets contract ${a}, but this Client is configured for ${t}.`);return o}static fromJSON(e,{tx:t,simulationResult:n,simulationTransactionData:r}){const o=new da(e);o.built=Ro.fromXDR(t,e.networkPassphrase);const s=da.validateInvokeContractOp(o.built,e.contractId).functionName().toString("utf-8");if(s!==e.method)throw new Error(`Transaction envelope calls method '${s}', but the provided method is '${e.method}'.`);return o.simulationResult={auth:n.auth.map(e=>se.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:se.ScVal.fromXDR(n.retval,"base64")},o.simulationTransactionData=se.SorobanTransactionData.fromXDR(r,"base64"),o}toXDR(){if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return this.built?.toEnvelope().toXDR("base64")}static fromXDR(e,t,n){const r=se.TransactionEnvelope.fromXDR(t,"base64"),o=Ro.fromXDR(r,e.networkPassphrase),s=da.validateInvokeContractOp(o,e.contractId).functionName().toString("utf-8"),i=new da({...e,method:s,parseResultXdr:e=>n.funcResToNative(s,e)});return i.built=o,i}handleWalletError(e){if(!e)return;const{message:t,code:n}=e,r=`${t}${e.ext?` (${e.ext.join(", ")})`:""}`;switch(n){case-1:throw new da.Errors.InternalWalletError(r);case-2:throw new da.Errors.ExternalServiceError(r);case-3:throw new da.Errors.InvalidClientRequest(r);case-4:throw new da.Errors.UserRejected(r);default:throw new Error(`Unhandled error: ${r}`)}}static build(e){const t=new go(e.contractId);return da.buildWithOp(t.call(e.method,...e.args??[]),e)}static async buildWithOp(e,t){const n=new da(t);n.originalOp=e;const r=await ji(t,n.server);return n.raw=new Ro(r,{fee:t.fee??xo,networkPassphrase:t.networkPassphrase}).setTimeout(t.timeoutInSeconds??Ki).addOperation(e),t.simulate&&await n.simulate(),n}static async buildFootprintRestoreTransaction(e,t,n,r){const o=new da(e);return o.raw=new Ro(n,{fee:r,networkPassphrase:e.networkPassphrase}).setSorobanData(t instanceof fo?t.build():t).addOperation(Qr.restoreFootprint({})).setTimeout(e.timeoutInSeconds??Ki),await o.simulate({restore:!1}),o}simulate=async({restore:e}={})=>{if(!this.built){if(!this.raw)throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");this.built=this.raw.build()}if(e=e??this.options.restore,delete this.simulationResult,delete this.simulationTransactionData,this.simulation=await this.server.simulateTransaction(this.built),e&&Bi.isSimulationRestore(this.simulation)){const e=await ji(this.options,this.server),t=await this.restoreFootprint(this.simulation.restorePreamble,e);if(t.status===Bi.GetTransactionStatus.SUCCESS){const t=this.originalOp?this.originalOp:new go(this.options.contractId).call(this.options.method,...this.options.args??[]);return this.raw=new Ro(e,{fee:this.options.fee??xo,networkPassphrase:this.options.networkPassphrase}).addOperation(t).setTimeout(this.options.timeoutInSeconds??Ki),delete this.built,await this.simulate(),this}throw new da.Errors.RestorationFailure(`Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n${JSON.stringify(t)}`)}return Bi.isSimulationSuccess(this.simulation)&&(this.built=Di(this.built,this.simulation).build()),this};get simulationData(){if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};const e=this.simulation;if(!e)throw new da.Errors.NotYetSimulated("Transaction has not yet been simulated");if(Bi.isSimulationError(e))throw new da.Errors.SimulationFailed(`Transaction simulation failed: "${e.error}"`);if(Bi.isSimulationRestore(e))throw new da.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=e.result??{auth:[],retval:se.ScVal.scvVoid()},this.simulationTransactionData=e.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}get result(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(t){if("object"!=typeof(e=t)||null===e||!("toString"in e))throw t;const n=this.parseError(t.toString());if(n)return n;throw t}var e}parseError(e){if(!this.options.errorTypes)return;const t=e.match(Zi);if(!t)return;const n=parseInt(t[1],10),r=this.options.errorTypes[n];return r?new Xi(r):void 0}sign=async({force:e=!1,signTransaction:t=this.options.signTransaction}={})=>{if(!this.built)throw new Error("Transaction has not yet been simulated");if(!e&&this.isReadCall)throw new da.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");if(!t)throw new da.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");if(!this.options.publicKey)throw new da.Errors.FakeAccount("This transaction was constructed using a default account. Provide a valid publicKey in the AssembledTransactionOptions.");const n=this.needsNonInvokerSigningBy().filter(e=>!e.startsWith("C"));if(n.length)throw new da.Errors.NeedsMoreSignatures(`Transaction requires signatures from ${n}. See \`needsNonInvokerSigningBy\` for details.`);const r=this.options.timeoutInSeconds??Ki;this.built=Ro.cloneFrom(this.built,{fee:this.built.fee,timebounds:void 0,sorobanData:this.simulationData.transactionData}).setTimeout(r).build();const o={networkPassphrase:this.options.networkPassphrase};this.options.address&&(o.address=this.options.address),void 0!==this.options.submit&&(o.submit=this.options.submit),this.options.submitUrl&&(o.submitUrl=this.options.submitUrl);const{signedTxXdr:s,error:i}=await t(this.built.toXDR(),o);this.handleWalletError(i),this.signed=Ro.fromXDR(s,this.options.networkPassphrase)};async send(e){if(!this.signed)throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");return await Yi.init(this,e)}signAndSend=async({force:e=!1,signTransaction:t=this.options.signTransaction,watcher:n}={})=>{if(!this.signed){const n=t||this.options.signTransaction,r=this.options.submit&&n?(e,t)=>n(e,{...t,submit:!1}):t;await this.sign({force:e,signTransaction:r})}return this.send(n)};needsNonInvokerSigningBy=({includeAlreadySigned:e=!1}={})=>{if(!this.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in this.built))throw new Error(`Unexpected Transaction type; no operations: ${JSON.stringify(this.built)}`);const t=this.built.operations[0];return[...new Set((t.auth??[]).map(e=>Go(e.credentials())).filter(t=>null!==t&&(e||"scvVoid"===t.signature().switch().name)).map(e=>Xr.fromScAddress(e.address()).toString()))]};signAuthEntries=async({expiration:e=(async()=>(await this.server.getLatestLedger()).sequence+100)(),signAuthEntry:t=this.options.signAuthEntry,address:n=this.options.publicKey,authorizeEntry:r=Fo}={})=>{if(!this.built)throw new Error("Transaction has not yet been assembled or simulated");if(r===Fo){const e=this.needsNonInvokerSigningBy();if(0===e.length)throw new da.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");if(-1===e.indexOf(n??""))throw new da.Errors.NoSignatureNeeded(`No auth entries for public key "${n}"`);if(!t)throw new da.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`")}const o=this.built.operations[0].auth??[];for(const[s,i]of o.entries()){const a=Go(se.SorobanCredentials.fromXDR(i.credentials().toXDR()));if(null===a)continue;if(Xr.fromScAddress(a.address()).toString()!==n)continue;const c=t??Promise.resolve;o[s]=await r(i,async e=>{const{signedAuthEntry:t,error:r}=await c(e.toXDR("base64"),{address:n});return this.handleWalletError(r),fe.Buffer.from(t,"base64")},await e,this.options.networkPassphrase)}};get isReadCall(){const e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}async restoreFootprint(e,t){if(!this.options.signTransaction)throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");t=t??await ji(this.options,this.server);const n=await da.buildFootprintRestoreTransaction({...this.options},e.transactionData,t,e.minResourceFee),r=await n.signAndSend();if(!r.getTransactionResponse)throw new da.Errors.RestorationFailure(`The attempt at automatic restore failed. \n${JSON.stringify(r)}`);return r.getTransactionResponse}}function pa(e){const t=function(e){const t=new Map,n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let r=0;const o=t=>{if(r+t>e.byteLength)throw new Error("Buffer overflow");const o=new Uint8Array(n,r,t);return r+=t,o};function s(){let e=0,t=0;for(;;){const n=o(1)[0];if(e|=(127&n)<<t,!(128&n))break;if((t+=7)>=32)throw new Error("Invalid WASM value")}return e>>>0}if("0,97,115,109"!==[...o(4)].join())throw new Error("Invalid WASM magic");if("1,0,0,0"!==[...o(4)].join())throw new Error("Invalid WASM version");for(;r<e.byteLength;){const e=o(1)[0],n=s(),i=r;if(0===e){const e=s();if(e>0&&r+e<=i+n){const s=o(e),a=o(n-(r-i));try{const e=new TextDecoder("utf-8",{fatal:!0}).decode(s);a.length>0&&t.set(e,(t.get(e)||[]).concat(a))}catch{}}}r=i+n}return t}(e),n=t.get("contractspecv0");if(!n||0===n.length)throw new Error("Could not obtain contract spec from wasm");return fe.Buffer.from(n[0])}function ha(e){return/^\d+$/.test(e.name().toString())}const fa={U32:{type:"integer",minimum:0,maximum:4294967295},I32:{type:"integer",minimum:-2147483648,maximum:2147483647},U64:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},Timepoint:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},Duration:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},I64:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:21},U128:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:39},I128:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:40},U256:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:78},I256:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:79},Address:{type:"string",format:"address",description:"Address can be a public key or contract id"},MuxedAddress:{type:"string",format:"address",description:"Stellar public key with M prefix combining a G address and unique ID"},ScString:{type:"string",description:"ScString is a string"},ScSymbol:{type:"string",description:"ScSymbol is a string"},DataUrl:{type:"string",pattern:"^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$"}};function ma(e){let t;switch(e.switch().value){case se.ScSpecType.scSpecTypeVal().value:t="Val";break;case se.ScSpecType.scSpecTypeBool().value:return{type:"boolean"};case se.ScSpecType.scSpecTypeVoid().value:return{type:"null"};case se.ScSpecType.scSpecTypeError().value:t="Error";break;case se.ScSpecType.scSpecTypeU32().value:t="U32";break;case se.ScSpecType.scSpecTypeI32().value:t="I32";break;case se.ScSpecType.scSpecTypeU64().value:t="U64";break;case se.ScSpecType.scSpecTypeI64().value:t="I64";break;case se.ScSpecType.scSpecTypeTimepoint().value:t="Timepoint";break;case se.ScSpecType.scSpecTypeDuration().value:t="Duration";break;case se.ScSpecType.scSpecTypeU128().value:t="U128";break;case se.ScSpecType.scSpecTypeI128().value:t="I128";break;case se.ScSpecType.scSpecTypeU256().value:t="U256";break;case se.ScSpecType.scSpecTypeI256().value:t="I256";break;case se.ScSpecType.scSpecTypeBytes().value:t="DataUrl";break;case se.ScSpecType.scSpecTypeString().value:t="ScString";break;case se.ScSpecType.scSpecTypeSymbol().value:t="ScSymbol";break;case se.ScSpecType.scSpecTypeAddress().value:t="Address";break;case se.ScSpecType.scSpecTypeMuxedAddress().value:t="MuxedAddress";break;case se.ScSpecType.scSpecTypeOption().value:return ma(e.option().valueType());case se.ScSpecType.scSpecTypeResult().value:return ma(e.result().okType());case se.ScSpecType.scSpecTypeVec().value:return{type:"array",items:ma(e.vec().elementType())};case se.ScSpecType.scSpecTypeMap().value:{const t=e.map();return{type:"array",items:{type:"array",items:[ma(t.keyType()),ma(t.valueType())],minItems:2,maxItems:2}}}case se.ScSpecType.scSpecTypeTuple().value:{const t=e.tuple(),n=t.valueTypes().length,r=n;return{type:"array",items:t.valueTypes().map(ma),minItems:n,maxItems:r}}case se.ScSpecType.scSpecTypeBytesN().value:return{$ref:"#/definitions/DataUrl",maxLength:e.bytesN().n()};case se.ScSpecType.scSpecTypeUdt().value:t=e.udt().name().toString();break}return{$ref:`#/definitions/${t}`}}function ga(e){const t={},n=[];e.forEach(e=>{const r=e.type(),o=e.name().toString();t[o]=ma(r),r.switch().value!==se.ScSpecType.scSpecTypeOption().value&&n.push(o)});const r={properties:t};return n.length>0&&(r.required=n),r}class ya{entries=[];static fromWasm(e){const t=pa(e);return new ya(t)}constructor(e){if(fe.Buffer.isBuffer(e))this.entries=zi(e);else if("string"==typeof e)this.entries=zi(fe.Buffer.from(e,"base64"));else{if(0===e.length)throw new Error("Contract spec must have at least one entry");const t=e[0];this.entries="string"==typeof t?e.map(e=>se.ScSpecEntry.fromXDR(e,"base64")):e}}funcs(){return this.entries.filter(e=>e.switch().value===se.ScSpecEntryKind.scSpecEntryFunctionV0().value).map(e=>e.functionV0())}getFunc(e){const t=this.findEntry(e);if(t.switch().value!==se.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error(`${e} is not a function`);return t.functionV0()}funcArgsToScVals(e,t){return this.getFunc(e).inputs().map(e=>this.nativeToScVal(function(e,t){const n=t.name().toString(),r=Object.entries(e).find(([e])=>e===n);if(!r)throw new Error(`Missing field ${n}`);return r[1]}(t,e),e.type()))}funcResToNative(e,t){const n="string"==typeof t?se.ScVal.fromXDR(t,"base64"):t,r=this.getFunc(e).outputs();if(0===r.length){const e=n.switch();if(e.value!==se.ScValType.scvVoid().value)throw new Error(`Expected void, got ${e.name}`);return null}if(r.length>1)throw new Error("Multiple outputs not supported");const o=r[0];return o.switch().value===se.ScSpecType.scSpecTypeResult().value?n.switch().value===se.ScValType.scvError().value?new Xi({message:n.error().toXDR("base64")}):new $i(this.scValToNative(n,o.result().okType())):this.scValToNative(n,o)}findEntry(e){const t=this.entries.find(t=>t.value().name().toString()===e);if(!t)throw new Error(`no such entry: ${e}`);return t}nativeToScVal(e,t){const n=t.switch(),r=n.value;if(n.value===se.ScSpecType.scSpecTypeUdt().value){const n=t.udt();return this.nativeToUdt(e,n.name().toString())}if(r===se.ScSpecType.scSpecTypeOption().value){const n=t.option();return null==e?se.ScVal.scvVoid():this.nativeToScVal(e,n.valueType())}switch(typeof e){case"object":if(null===e){if(r===se.ScSpecType.scSpecTypeVoid().value)return se.ScVal.scvVoid();throw new TypeError(`Type ${t} was not void, but value was null`)}if(e instanceof se.ScVal)return e;if(e instanceof Xr){if(t.switch().value!==se.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.toScVal()}if(e instanceof go){if(t.switch().value!==se.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.address().toScVal()}if(e instanceof Uint8Array||fe.Buffer.isBuffer(e)){const n=Uint8Array.from(e);switch(r){case se.ScSpecType.scSpecTypeBytesN().value:{const e=t.bytesN();if(n.length!==e.n())throw new TypeError(`expected ${e.n()} bytes, but got ${n.length}`);return se.ScVal.scvBytes(n)}case se.ScSpecType.scSpecTypeBytes().value:return se.ScVal.scvBytes(n);default:throw new TypeError(`invalid type (${t}) specified for Bytes and BytesN`)}}if(Array.isArray(e))switch(r){case se.ScSpecType.scSpecTypeVec().value:{const n=t.vec().elementType();return se.ScVal.scvVec(e.map(e=>this.nativeToScVal(e,n)))}case se.ScSpecType.scSpecTypeTuple().value:{const n=t.tuple().valueTypes();if(e.length!==n.length)throw new TypeError(`Tuple expects ${n.length} values, but ${e.length} were provided`);return se.ScVal.scvVec(e.map((e,t)=>this.nativeToScVal(e,n[t])))}case se.ScSpecType.scSpecTypeMap().value:{const n=t.map(),r=n.keyType(),o=n.valueType();return se.ScVal.scvMap(e.map(e=>{const t=this.nativeToScVal(e[0],r),n=this.nativeToScVal(e[1],o);return new se.ScMapEntry({key:t,val:n})}))}default:throw new TypeError(`Type ${t} was not vec, but value was Array`)}if(e.constructor===Map){if(r!==se.ScSpecType.scSpecTypeMap().value)throw new TypeError(`Type ${t} was not map, but value was Map`);const n=t.map(),o=[],s=e.entries();let i=s.next();for(;!i.done;){const[e,t]=i.value,r=this.nativeToScVal(e,n.keyType()),a=this.nativeToScVal(t,n.valueType());o.push(new se.ScMapEntry({key:r,val:a})),i=s.next()}return se.ScVal.scvMap(o)}if("Object"!==(e.constructor?.name??""))throw new TypeError(`cannot interpret ${e.constructor?.name} value as ScVal (${JSON.stringify(e)})`);throw new TypeError(`Received object ${e} did not match the provided type ${t}`);case"number":case"bigint":switch(r){case se.ScSpecType.scSpecTypeU32().value:if(BigInt(e)<BigInt(se.Uint32.MIN_VALUE)||BigInt(e)>BigInt(se.Uint32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for U32`);return se.ScVal.scvU32(Number(e));case se.ScSpecType.scSpecTypeI32().value:if(BigInt(e)<-BigInt(se.Int32.MIN_VALUE)||BigInt(e)>BigInt(se.Int32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for I32`);return se.ScVal.scvI32(Number(e));case se.ScSpecType.scSpecTypeU64().value:case se.ScSpecType.scSpecTypeI64().value:case se.ScSpecType.scSpecTypeU128().value:case se.ScSpecType.scSpecTypeI128().value:case se.ScSpecType.scSpecTypeU256().value:case se.ScSpecType.scSpecTypeI256().value:case se.ScSpecType.scSpecTypeTimepoint().value:case se.ScSpecType.scSpecTypeDuration().value:{const t=n.name.substring(10).toLowerCase();return new bo(t,e).toScVal()}default:throw new TypeError(`invalid type (${t}) specified for integer`)}case"string":return function(e,t){switch(t.value){case se.ScSpecType.scSpecTypeString().value:return se.ScVal.scvString(e);case se.ScSpecType.scSpecTypeSymbol().value:return se.ScVal.scvSymbol(e);case se.ScSpecType.scSpecTypeAddress().value:case se.ScSpecType.scSpecTypeMuxedAddress().value:return Xr.fromString(e).toScVal();case se.ScSpecType.scSpecTypeU64().value:return new bo("u64",e).toScVal();case se.ScSpecType.scSpecTypeI64().value:return new bo("i64",e).toScVal();case se.ScSpecType.scSpecTypeU128().value:return new bo("u128",e).toScVal();case se.ScSpecType.scSpecTypeI128().value:return new bo("i128",e).toScVal();case se.ScSpecType.scSpecTypeU256().value:return new bo("u256",e).toScVal();case se.ScSpecType.scSpecTypeI256().value:return new bo("i256",e).toScVal();case se.ScSpecType.scSpecTypeBytes().value:case se.ScSpecType.scSpecTypeBytesN().value:return se.ScVal.scvBytes(fe.Buffer.from(e,"base64"));case se.ScSpecType.scSpecTypeTimepoint().value:return se.ScVal.scvTimepoint(new se.Uint64(e));case se.ScSpecType.scSpecTypeDuration().value:return se.ScVal.scvDuration(new se.Uint64(e));default:throw new TypeError(`invalid type ${t.name} specified for string value`)}}(e,n);case"boolean":if(r!==se.ScSpecType.scSpecTypeBool().value)throw TypeError(`Type ${t} was not bool, but value was bool`);return se.ScVal.scvBool(e);case"undefined":if(!t)return se.ScVal.scvVoid();switch(r){case se.ScSpecType.scSpecTypeVoid().value:case se.ScSpecType.scSpecTypeOption().value:return se.ScVal.scvVoid();default:throw new TypeError(`Type ${t} was not void, but value was undefined`)}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError(`failed to convert typeof ${typeof e} (${e})`)}}nativeToUdt(e,t){const n=this.findEntry(t);switch(n.switch()){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError(`expected number for enum ${t}, but got ${typeof e}`);return this.nativeToEnum(e,n.udtEnumV0());case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,n.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,n.udtUnionV0());default:throw new Error(`failed to parse udt ${t}`)}}nativeToUnion(e,t){const n=e.tag,r=t.cases().find(e=>e.value().name().toString()===n);if(!r)throw new TypeError(`no such enum entry: ${n} in ${t}`);const o=se.ScVal.scvSymbol(n);switch(r.switch()){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return se.ScVal.scvVec([o]);case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const n=r.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==n.length)throw new TypeError(`union ${t} expects ${n.length} values, but got ${e.values.length}`);const r=e.values.map((e,t)=>this.nativeToScVal(e,n[t]));return r.unshift(o),se.ScVal.scvVec(r)}throw new Error(`failed to parse union case ${r} with ${e}`)}default:throw new Error(`failed to parse union ${t} with ${e}`)}}nativeToStruct(e,t){const n=t.fields();if(n.some(ha)){if(!n.every(ha))throw new Error("mixed numeric and non-numeric field names are not allowed");return se.ScVal.scvVec(n.map((t,r)=>this.nativeToScVal(e[r],n[r].type())))}return se.ScVal.scvMap(n.map(t=>{const n=t.name().toString();return new se.ScMapEntry({key:this.nativeToScVal(n,se.ScSpecTypeDef.scSpecTypeSymbol()),val:this.nativeToScVal(e[n],t.type())})}))}nativeToEnum(e,t){if(t.cases().some(t=>t.value()===e))return se.ScVal.scvU32(e);throw new TypeError(`no such enum entry: ${e} in ${t}`)}scValStrToNative(e,t){return this.scValToNative(se.ScVal.fromXDR(e,"base64"),t)}scValToNative(e,t){const n=t.switch(),r=n.value;if(r===se.ScSpecType.scSpecTypeOption().value)return e.switch().value===se.ScValType.scvVoid().value?null:this.scValToNative(e,t.option().valueType());if(r===se.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case se.ScValType.scvVoid().value:return null;case se.ScValType.scvU64().value:case se.ScValType.scvI64().value:case se.ScValType.scvTimepoint().value:case se.ScValType.scvDuration().value:case se.ScValType.scvU128().value:case se.ScValType.scvI128().value:case se.ScValType.scvU256().value:case se.ScValType.scvI256().value:return To(e);case se.ScValType.scvVec().value:if(r===se.ScSpecType.scSpecTypeVec().value){const n=t.vec();return(e.vec()??[]).map(e=>this.scValToNative(e,n.elementType()))}if(r===se.ScSpecType.scSpecTypeTuple().value){const n=t.tuple().valueTypes();return(e.vec()??[]).map((e,t)=>this.scValToNative(e,n[t]))}throw new TypeError(`Type ${t} was not vec, but ${e} is`);case se.ScValType.scvAddress().value:return Xr.fromScVal(e).toString();case se.ScValType.scvMap().value:{const o=e.map()??[];if(r===se.ScSpecType.scSpecTypeMap().value){const e=t.map(),n=e.keyType(),r=e.valueType();return o.map(e=>[this.scValToNative(e.key(),n),this.scValToNative(e.val(),r)])}throw new TypeError(`ScSpecType ${n.name} was not map, but ${JSON.stringify(e,null,2)} is`)}case se.ScValType.scvBool().value:case se.ScValType.scvU32().value:case se.ScValType.scvI32().value:case se.ScValType.scvBytes().value:return e.value();case se.ScValType.scvString().value:case se.ScValType.scvSymbol().value:if(r!==se.ScSpecType.scSpecTypeString().value&&r!==se.ScSpecType.scSpecTypeSymbol().value)throw new Error(`ScSpecType ${n.name} was not string or symbol, but ${JSON.stringify(e,null,2)} is`);return e.value()?.toString();default:throw new TypeError(`failed to convert ${JSON.stringify(e,null,2)} to native type from type ${n.name}`)}}scValUdtToNative(e,t){const n=this.findEntry(t.name().toString());switch(n.switch()){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,n.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,n.udtUnionV0());default:throw new Error(`failed to parse udt ${t.name().toString()}: ${n}`)}}unionToNative(e,t){const n=e.vec();if(!n)throw new Error(`${JSON.stringify(e,null,2)} is not a vec`);if(0===n.length&&0!==t.cases.length)throw new Error(`${e} has length 0, but the there are at least one case in the union`);const r=n[0].sym().toString();if(n[0].switch().value!==se.ScValType.scvSymbol().value)throw new Error(`${n[0]} is not a symbol`);const o=t.cases().find(function(e){return function(t){switch(t.switch().value){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(r));if(!o)throw new Error(`failed to find entry ${r} in union ${t.name().toString()}`);const s={tag:r};if(o.switch().value===se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){const e=o.tupleCase().type().map((e,t)=>this.scValToNative(n[t+1],e));s.values=e}return s}structToNative(e,t){const n={},r=t.fields();if(r.some(ha)){const t=e.vec()?.map((e,t)=>this.scValToNative(e,r[t].type()));return t}return e.map()?.forEach((e,t)=>{const o=r[t];n[o.name().toString()]=this.scValToNative(e.val(),o.type())}),n}enumToNative(e){if(e.switch().value!==se.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}errorCases(){return this.entries.filter(e=>e.switch().value===se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value).flatMap(e=>e.value().cases())}jsonSchema(e){const t={};this.entries.forEach(e=>{switch(e.switch().value){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:{const n=e.udtEnumV0();t[n.name().toString()]=function(e){const t=e.doc().toString(),n=e.cases(),r=[];n.forEach(e=>{const t=e.name().toString(),n=e.doc().toString();r.push({description:n,title:t,enum:[e.value()],type:"number"})});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case se.ScSpecEntryKind.scSpecEntryUdtStructV0().value:{const n=e.udtStructV0();t[n.name().toString()]=function(e){const t=e.fields();if(t.some(ha)){if(!t.every(ha))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((e,n)=>ma(t[n].type())),minItems:t.length,maxItems:t.length}}const n=e.doc().toString(),{properties:r,required:o}=ga(t);return{description:n,properties:r,required:o,additionalProperties:!1,type:"object"}}(n);break}case se.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:{const n=e.udtUnionV0();t[n.name().toString()]=function(e){const t=e.doc().toString(),n=e.cases(),r=[];n.forEach(e=>{switch(e.switch().value){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:{const t=e.voidCase().name().toString();r.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break}case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:{const t=e.tupleCase(),n=t.name().toString();r.push({type:"object",title:n,properties:{tag:n,values:{type:"array",items:t.type().map(ma)}},required:["tag","values"],additionalProperties:!1})}}});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case se.ScSpecEntryKind.scSpecEntryFunctionV0().value:{const n=e.functionV0(),r=n.name().toString(),{input:o}=function(e){const{properties:t,required:n}=ga(e.inputs()),r={additionalProperties:!1,properties:t,type:"object"};n?.length>0&&(r.required=n);const o={properties:{args:r}},s=e.outputs(),i=s.length>0?ma(s[0]):ma(se.ScSpecTypeDef.scSpecTypeVoid()),a=e.doc().toString();return a.length>0&&(o.description=a),o.additionalProperties=!1,i.additionalProperties=!1,{input:o,output:i}}(n);t[r]=o;break}case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}});const n={$schema:"http://json-schema.org/draft-07/schema#",definitions:{...fa,...t}};return e&&(n.$ref=`#/definitions/${e}`),n}}function wa(e){const t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","enum","implements","interface","let","package","private","protected","public","static","async","await","constructor","null","true","false"].includes(t)?t+"_":/^\d/.test(t)?"_"+t:""===t||/^_+$/.test(t)?"_unnamed":t}function Aa(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Sa(e,t=!1){switch(e.switch()){case se.ScSpecType.scSpecTypeVal():return"any";case se.ScSpecType.scSpecTypeBool():return"boolean";case se.ScSpecType.scSpecTypeVoid():return"null";case se.ScSpecType.scSpecTypeError():return"Error";case se.ScSpecType.scSpecTypeU32():case se.ScSpecType.scSpecTypeI32():return"number";case se.ScSpecType.scSpecTypeU64():case se.ScSpecType.scSpecTypeI64():case se.ScSpecType.scSpecTypeTimepoint():case se.ScSpecType.scSpecTypeDuration():case se.ScSpecType.scSpecTypeU128():case se.ScSpecType.scSpecTypeI128():case se.ScSpecType.scSpecTypeU256():case se.ScSpecType.scSpecTypeI256():return"bigint";case se.ScSpecType.scSpecTypeBytes():case se.ScSpecType.scSpecTypeBytesN():return"Buffer";case se.ScSpecType.scSpecTypeString():case se.ScSpecType.scSpecTypeSymbol():return"string";case se.ScSpecType.scSpecTypeAddress():case se.ScSpecType.scSpecTypeMuxedAddress():return t?"string | Address":"string";case se.ScSpecType.scSpecTypeVec():return`Array<${Sa(e.vec().elementType(),t)}>`;case se.ScSpecType.scSpecTypeMap():return`Map<${Sa(e.map().keyType(),t)}, ${Sa(e.map().valueType(),t)}>`;case se.ScSpecType.scSpecTypeTuple():return`[${e.tuple().valueTypes().map(e=>Sa(e,t)).join(", ")}]`;case se.ScSpecType.scSpecTypeOption():for(;e.option().valueType().switch()===se.ScSpecType.scSpecTypeOption();)e=e.option().valueType();return`${Sa(e.option().valueType(),t)} | null`;case se.ScSpecType.scSpecTypeResult():return`Result<${Sa(e.result().okType(),t)}, ${Sa(e.result().errorType(),t)}>`;case se.ScSpecType.scSpecTypeUdt():return wa(e.udt().name().toString());default:return"unknown"}}function ba(e,t){switch(e.switch()){case se.ScSpecType.scSpecTypeUdt():return void t.typeFileImports.add(wa(e.udt().name().toString()));case se.ScSpecType.scSpecTypeAddress():case se.ScSpecType.scSpecTypeMuxedAddress():return void t.stellarImports.add("Address");case se.ScSpecType.scSpecTypeBytes():case se.ScSpecType.scSpecTypeBytesN():return void(t.needsBufferImport=!0);case se.ScSpecType.scSpecTypeVal():return void t.stellarImports.add("xdr");case se.ScSpecType.scSpecTypeResult():t.stellarContractImports.add("Result");break;case se.ScSpecType.scSpecTypeBool():case se.ScSpecType.scSpecTypeVoid():case se.ScSpecType.scSpecTypeError():case se.ScSpecType.scSpecTypeU32():case se.ScSpecType.scSpecTypeI32():case se.ScSpecType.scSpecTypeU64():case se.ScSpecType.scSpecTypeI64():case se.ScSpecType.scSpecTypeTimepoint():case se.ScSpecType.scSpecTypeDuration():case se.ScSpecType.scSpecTypeU128():case se.ScSpecType.scSpecTypeI128():case se.ScSpecType.scSpecTypeU256():case se.ScSpecType.scSpecTypeI256():case se.ScSpecType.scSpecTypeString():case se.ScSpecType.scSpecTypeSymbol():return}const n=function(e){switch(e.switch()){case se.ScSpecType.scSpecTypeVec():return[e.vec().elementType()];case se.ScSpecType.scSpecTypeMap():return[e.map().keyType(),e.map().valueType()];case se.ScSpecType.scSpecTypeTuple():return e.tuple().valueTypes();case se.ScSpecType.scSpecTypeOption():return[e.option().valueType()];case se.ScSpecType.scSpecTypeResult():return[e.result().okType(),e.result().errorType()];default:return[]}}(e);n.forEach(e=>ba(e,t))}function va(e){const t={typeFileImports:new Set,stellarContractImports:new Set,stellarImports:new Set,needsBufferImport:!1};return e.forEach(e=>ba(e,t)),t}function Ta(e,t){const n=[],r=e.typeFileImports,o=[...e.stellarContractImports,...t?.additionalStellarContractImports||[]],s=[...e.stellarImports,...t?.additionalStellarImports||[]];if(t?.includeTypeFileImports&&r.size>0&&n.push(`import {${Array.from(r).join(", ")}} from './types.js';`),o.length>0){const e=Array.from(new Set(o));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk/contract';`)}if(s.length>0){const e=Array.from(new Set(s));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk';`)}return e.needsBufferImport&&n.push("import { Buffer } from 'buffer';"),n.join("\n")}function Ea(e,t=0){if(""===e.trim())return"";const n=" ".repeat(t);const r=e.replace(/\*\//g,"* /").replace(/@(?!(param|returns?|type|throws?|example|deprecated|see|link|since|author|version|description|summary)\b)/g,"\\@").split("\n").map(e=>`${n} * ${e}`.trimEnd());return`${n}/**\n${r.join("\n")}\n${n} */\n`}const ka="__constructor";class Ia{constructor(e,t){if(this.spec=e,this.options=t,void 0===t.server){const{allowHttp:e,headers:n}=t;t.server=new Hi(t.rpcUrl,{allowHttp:e,headers:n})}this.spec.funcs().forEach(n=>{const r=n.name().toString();if(r===ka)return;const o=(n,o)=>da.build({method:r,args:n&&e.funcArgsToScVals(r,n),...t,...o,errorTypes:e.errorCases().reduce((e,t)=>({...e,[t.value()]:{message:t.doc().toString()}}),{}),parseResultXdr:t=>e.funcResToNative(r,t)});this[wa(r)]=0===e.getFunc(r).inputs().length?e=>o(void 0,e):o})}spec;options;static async deploy(e,t){const{wasmHash:n,salt:r,format:o,fee:s,timeoutInSeconds:i,simulate:a,...c}=t,u=await async function(e,t,n="hex"){if(!t||!t.rpcUrl)throw new TypeError("options must contain rpcUrl");const{rpcUrl:r,allowHttp:o,headers:s}=t,i=new Hi(r,{allowHttp:o,headers:s}),a=await i.getContractWasmByHash(e,n);return ya.fromWasm(a)}(n,c,o),l=Qr.createCustomContract({address:new Xr(t.address||t.publicKey),wasmHash:"string"==typeof n?fe.Buffer.from(n,o??"hex"):n,salt:r,constructorArgs:e?u.funcArgsToScVals(ka,e):[]});return da.buildWithOp(l,{fee:s,timeoutInSeconds:i,simulate:a,...c,contractId:"ignored",method:ka,parseResultXdr:e=>new Ia(u,{...c,contractId:Xr.fromScVal(e).toString()})})}static async fromWasmHash(e,t,n="hex"){if(!t||!t.rpcUrl)throw new TypeError("options must contain rpcUrl");const{rpcUrl:r,allowHttp:o,headers:s}=t,i=t.server??new Hi(r,{allowHttp:o,headers:s}),a=await i.getContractWasmByHash(e,n);return Ia.fromWasm(a,t)}static async fromWasm(e,t){const n=await ya.fromWasm(e);return new Ia(n,t)}static async from(e){if(!e||!e.rpcUrl||!e.contractId)throw new TypeError("options must contain rpcUrl and contractId");const{rpcUrl:t,contractId:n,allowHttp:r,headers:o}=e,s=new Hi(t,{allowHttp:r,headers:o}),i=await s.getContractWasmByContractId(n);return Ia.fromWasm(i,e)}txFromJSON=e=>{const{method:t,...n}=JSON.parse(e);return da.fromJSON({...this.options,method:t,parseResultXdr:e=>this.spec.funcResToNative(t,e)},n)};txFromXDR=e=>da.fromXDR(this.options,e,this.spec)}var Ca=Object.freeze({__proto__:null,AssembledTransaction:da,Client:Ia,DEFAULT_TIMEOUT:Ki,Err:Xi,NULL_ACCOUNT:Wi,Ok:$i,SentTransaction:Yi,Spec:ya,Watcher:class{},basicNodeSigner:(e,t)=>({signTransaction:async(n,r)=>{const o=Ro.fromXDR(n,r?.networkPassphrase||t);return o.sign(e),{signedTxXdr:o.toXDR(),signerAddress:e.publicKey()}},signAuthEntry:async t=>({signedAuthEntry:e.sign(nt(fe.Buffer.from(t,"base64"))).toString("base64"),signerAddress:e.publicKey()})})});class Ba{generate(e){const{contractName:t}=e;return{packageJson:this.generatePackageJson(t),tsConfig:this.generateTsConfig(),gitignore:this.generateGitignore(),readme:this.generateReadme(t)}}generatePackageJson(e){const t={name:e.toLowerCase().replace(/[^a-z0-9-]/g,"-"),version:"0.0.1",description:`Generated TypeScript bindings for ${e} Stellar contract`,type:"module",main:"dist/index.js",types:"dist/index.d.ts",scripts:{build:"tsc"},dependencies:{"@stellar/stellar-sdk":"^16.0.0",buffer:"6.0.3"},devDependencies:{typescript:"^5.6.3"}};return JSON.stringify(t,null,2)}generateTsConfig(){return JSON.stringify({compilerOptions:{target:"ESNext",module:"NodeNext",moduleResolution:"nodenext",declaration:!0,outDir:"./dist",strictNullChecks:!0,skipLibCheck:!0},include:["src/*"]},null,2)}generateGitignore(){return["# Dependencies","node_modules/","","# Build outputs","dist/","*.tgz","","# IDE",".vscode/",".idea/","","# OS",".DS_Store","Thumbs.db","","# Logs","*.log","npm-debug.log*","","# Runtime data","*.pid","*.seed"].join("\n")}generateReadme(e){return[`# ${e} Contract Bindings`,"",`TypeScript bindings for the ${e} Stellar smart contract.`,"","## Installation","","```bash","npm install","```","","## Build","","```bash","npm run build","```","","## Usage","","```typescript",'import { Client } from "./src";',"","const client = new Client({",' contractId: "YOUR_CONTRACT_ID",',' rpcUrl: "https://soroban-testnet.stellar.org:443",',' networkPassphrase: "Test SDF Network ; September 2015",',"});","","// Call contract methods","// const result = await client.methodName();","```","","## Generated Files","","- `src/index.ts` - Entry point exporting the Client","- `src/types.ts` - Type definitions for contract structs, enums, and unions","- `src/contract.ts` - Client implementation","- `tsconfig.json` - TypeScript configuration","- `package.json` - NPM package configuration","","This package was generated using the Js-Stellar-SDK contract binding generator."].join("\n")}}class xa{spec;constructor(e){this.spec=e}generate(){const e=this.spec.entries.map(e=>this.generateEntry(e)).filter(e=>e).join("\n\n");return`${this.generateImports()}\n\n ${e}\n `}generateEntry(e){switch(e.switch()){case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().every((e,t)=>e.name().toString().trim()===t.toString())?this.generateTupleStruct(e.udtStructV0()):this.generateStruct(e.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.generateUnion(e.udtUnionV0());case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.generateEnum(e.udtEnumV0());case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():return this.generateErrorEnum(e.udtErrorEnumV0());default:return null}}generateImports(){return Ta(va(this.spec.entries.flatMap(e=>{switch(e.switch()){case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().map(e=>e.type());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return e.udtUnionV0().cases().flatMap(e=>e.switch()===se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0()?e.tupleCase().type():[]);case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():default:return[]}})),{includeTypeFileImports:!1})}generateStruct(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Struct: ${t}`,0)}export interface ${t} {\n${e.fields().map(e=>{const t=wa(e.name().toString()),n=Sa(e.type());return`${Ea(e.doc().toString(),2)} ${t}: ${n};`}).join("\n")}\n}`}generateUnion(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Union: ${t}`,0)} export type ${t} =\n${e.cases().map(e=>this.generateUnionCase(e)).map(e=>e.types.length>0?`${Ea(e.doc,2)} { tag: "${Aa(e.name)}"; values: readonly [${e.types.join(", ")}] }`:`${Ea(e.doc,2)} { tag: "${Aa(e.name)}"; values: void }`).join(" |\n")};`}generateEnum(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Enum: ${t}`,0)}export enum ${t} {\n${e.cases().map(e=>{const t=wa(e.name().toString()),n=e.value();return`${Ea(e.doc().toString()||`Enum Case: ${t}`,2)} ${t} = ${n}`}).join(",\n")}\n}`}generateErrorEnum(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Error Enum: ${t}`,0)}export const ${t} = {\n${e.cases().map(e=>this.generateEnumCase(e)).map(e=>`${Ea(e.doc,2)} ${e.value} : { message: "${Aa(e.name)}" }`).join(",\n")}\n}`}generateUnionCase(e){switch(e.switch()){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():{const t=e.voidCase();return{doc:t.doc().toString(),name:t.name().toString(),types:[]}}case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const t=e.tupleCase();return{doc:t.doc().toString(),name:t.name().toString(),types:t.type().map(e=>Sa(e))}}default:throw new Error(`Unknown union case kind: ${e.switch()}`)}}generateEnumCase(e){return{doc:e.doc().toString(),name:e.name().toString(),value:e.value()}}generateTupleStruct(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Tuple Struct: ${t}`,0)}export type ${t} = readonly [${e.fields().map(e=>Sa(e.type())).join(", ")}];`}}class Ra{spec;constructor(e){this.spec=e}generate(){let e="";try{const t=this.spec.getFunc("__constructor");e=this.generateDeployMethod(t)}catch{e=this.generateDeployMethod(void 0)}const t=this.spec.funcs().filter(e=>"__constructor"!==e.name().toString()).map(e=>this.generateInterfaceMethod(e)).join("\n"),n=this.generateImports(),r=this.spec.entries.map(e=>`"${e.toXDR("base64")}"`),o=this.spec.funcs().filter(e=>"__constructor"!==e.name().toString()).map(e=>this.generateFromJSONMethod(e)).join(",");return`${n}\n\nexport interface Client {\n${t}\n}\n\nexport class Client extends ContractClient {\n constructor(public readonly options: ContractClientOptions) {\n super(\n new Spec([${r.join(", ")}]),\n options\n );\n }\n\n ${e}\n public readonly fromJSON = {\n ${o}\n };\n}`}generateImports(){return Ta(va(this.spec.funcs().flatMap(e=>{const t=e.inputs(),n=e.outputs();return t.map(e=>e.type()).concat(n)})),{includeTypeFileImports:!0,additionalStellarContractImports:["Spec","AssembledTransaction","Client as ContractClient","ClientOptions as ContractClientOptions","MethodOptions"]})}generateInterfaceMethod(e){const t=wa(e.name().toString()),n=e.inputs().map(e=>({name:wa(e.name().toString()),type:Sa(e.type(),!0)})),r=e.outputs().length>0?Sa(e.outputs()[0]):"void";return`${Ea(e.doc().toString(),2)} ${t}(${this.formatMethodParameters(n)}): Promise<AssembledTransaction<${r}>>;`}generateFromJSONMethod(e){return` ${wa(e.name().toString())} : this.txFromJSON<${e.outputs().length>0?Sa(e.outputs()[0]):"void"}>`}generateDeployMethod(e){if(!e){return` static deploy<T = Client>(${this.formatConstructorParameters([])}): Promise<AssembledTransaction<T>> {\n return ContractClient.deploy(null, options);\n }`}const t=e.inputs().map(e=>({name:wa(e.name().toString()),type:Sa(e.type(),!0)}));return` static deploy<T = Client>(${this.formatConstructorParameters(t)}): Promise<AssembledTransaction<T>> {\n return ContractClient.deploy(${t.length>0?`{ ${t.map(e=>e.name).join(", ")} }, `:""}options);\n }`}formatMethodParameters(e){const t=[];if(e.length>0){const n=`{ ${e.map(e=>`${e.name}: ${e.type}`).join("; ")} }`;t.push(`{ ${e.map(e=>e.name).join(", ")} }: ${n}`)}return t.push("options?: MethodOptions"),t.join(", ")}formatConstructorParameters(e){const t=[];if(e.length>0){const n=`{ ${e.map(e=>`${e.name}: ${e.type}`).join("; ")} }`;t.push(`{ ${e.map(e=>e.name).join(", ")} }: ${n}`)}return t.push('options: MethodOptions & Omit<ContractClientOptions, \'contractId\'> & { wasmHash: Buffer | string; salt?: Buffer | Uint8Array; format?: "hex" | "base64"; address?: string; }'),t.join(", ")}}class _a extends Error{constructor(e,t){super(e),this.cause=t,this.name="WasmFetchError"}cause}async function Pa(e,t){try{const n=se.LedgerKey.contractCode(new se.LedgerKeyContractCode({hash:se.Hash.fromXDR(t,"raw")})),r=await e.getLedgerEntries(n);if(!r.entries||0===r.entries.length)throw new _a("WASM not found for the given hash");const o=r.entries[0];if(o.key.switch()!==se.LedgerEntryType.contractCode())throw new _a("Invalid ledger entry type returned");const s=o.val.contractCode();return fe.Buffer.from(s.code())}catch(e){if(e instanceof _a)throw e;throw new _a("Failed to fetch WASM from hash",e)}}async function Oa(e,t){try{const n=new go(t.toString()),r=await e.getLedgerEntries(n.getFootprint());if(!r.entries||0===r.entries.length)throw new _a("Contract instance not found");const o=r.entries[0];if(o.key.switch()!==se.LedgerEntryType.contractData())throw new _a("Invalid ledger entry type returned");const s=o.val.contractData().val().instance();if(function(e){return e.executable().switch()===se.ContractExecutableType.contractExecutableStellarAsset()}(s))return{type:"stellar-asset-contract"};const i=s.executable().wasmHash();return{type:"wasm",wasmBytes:await Pa(e,i)}}catch(e){if(e instanceof _a)throw e;throw new _a("Failed to fetch WASM from contract",e)}}class Ua{spec;constructor(e){this.spec=e}static fromSpec(e){return new Ua(e)}static fromWasm(e){const t=new ya(pa(e));return new Ua(t)}static async fromWasmHash(e,t){const n=await async function(e,t){try{const n=fe.Buffer.from(e,"hex");if(32!==n.length)throw new _a(`Invalid WASM hash length: expected 32 bytes, got ${n.length}`);return{type:"wasm",wasmBytes:await Pa(t,n)}}catch(t){throw new _a(`Failed to fetch WASM from hash ${e}`,t)}}(e,t);if("wasm"!==n.type)throw new Error("Fetched contract is not of type 'wasm'");return Ua.fromWasm(n.wasmBytes)}static async fromContractId(e,t){const n=await async function(e,t){try{if(!wn.isValidContract(e))throw new _a(`Invalid contract ID: ${e}`);const n=Xr.fromString(e);return await Oa(t,n)}catch(t){throw new _a(`Failed to fetch WASM from contract ${e}`,t)}}(e,t);if("wasm"===n.type)return Ua.fromWasm(n.wasmBytes);const r=new ya("AAAAAAAAAYpSZXR1cm5zIHRoZSBhbGxvd2FuY2UgZm9yIGBzcGVuZGVyYCB0byB0cmFuc2ZlciBmcm9tIGBmcm9tYC4KClRoZSBhbW91bnQgcmV0dXJuZWQgaXMgdGhlIGFtb3VudCB0aGF0IHNwZW5kZXIgaXMgYWxsb3dlZCB0byB0cmFuc2ZlcgpvdXQgb2YgZnJvbSdzIGJhbGFuY2UuIFdoZW4gdGhlIHNwZW5kZXIgdHJhbnNmZXJzIGFtb3VudHMsIHRoZSBhbGxvd2FuY2UKd2lsbCBiZSByZWR1Y2VkIGJ5IHRoZSBhbW91bnQgdHJhbnNmZXJyZWQuCgojIEFyZ3VtZW50cwoKKiBgZnJvbWAgLSBUaGUgYWRkcmVzcyBob2xkaW5nIHRoZSBiYWxhbmNlIG9mIHRva2VucyB0byBiZSBkcmF3biBmcm9tLgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIHNwZW5kaW5nIHRoZSB0b2tlbnMgaGVsZCBieSBgZnJvbWAuAAAAAAAJYWxsb3dhbmNlAAAAAAAAAgAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAEAAAALAAAAAAAAAIlSZXR1cm5zIHRydWUgaWYgYGlkYCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBpZGAgLSBUaGUgYWRkcmVzcyBmb3Igd2hpY2ggdG9rZW4gYXV0aG9yaXphdGlvbiBpcyBiZWluZyBjaGVja2VkLgAAAAAAAAphdXRob3JpemVkAAAAAAABAAAAAAAAAAJpZAAAAAAAEwAAAAEAAAABAAAAAAAAA59TZXQgdGhlIGFsbG93YW5jZSBieSBgYW1vdW50YCBmb3IgYHNwZW5kZXJgIHRvIHRyYW5zZmVyL2J1cm4gZnJvbQpgZnJvbWAuCgpUaGUgYW1vdW50IHNldCBpcyB0aGUgYW1vdW50IHRoYXQgc3BlbmRlciBpcyBhcHByb3ZlZCB0byB0cmFuc2ZlciBvdXQgb2YKZnJvbSdzIGJhbGFuY2UuIFRoZSBzcGVuZGVyIHdpbGwgYmUgYWxsb3dlZCB0byB0cmFuc2ZlciBhbW91bnRzLCBhbmQKd2hlbiBhbiBhbW91bnQgaXMgdHJhbnNmZXJyZWQgdGhlIGFsbG93YW5jZSB3aWxsIGJlIHJlZHVjZWQgYnkgdGhlCmFtb3VudCB0cmFuc2ZlcnJlZC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHRvIGJlIGRyYXduIGZyb20uCiogYHNwZW5kZXJgIC0gVGhlIGFkZHJlc3MgYmVpbmcgYXV0aG9yaXplZCB0byBzcGVuZCB0aGUgdG9rZW5zIGhlbGQgYnkKYGZyb21gLgoqIGBhbW91bnRgIC0gVGhlIHRva2VucyB0byBiZSBtYWRlIGF2YWlsYWJsZSB0byBgc3BlbmRlcmAuCiogYGV4cGlyYXRpb25fbGVkZ2VyYCAtIFRoZSBsZWRnZXIgbnVtYmVyIHdoZXJlIHRoaXMgYWxsb3dhbmNlIGV4cGlyZXMuIENhbm5vdApiZSBsZXNzIHRoYW4gdGhlIGN1cnJlbnQgbGVkZ2VyIG51bWJlciB1bmxlc3MgdGhlIGFtb3VudCBpcyBiZWluZyBzZXQgdG8gMC4KQW4gZXhwaXJlZCBlbnRyeSAod2hlcmUgZXhwaXJhdGlvbl9sZWRnZXIgPCB0aGUgY3VycmVudCBsZWRnZXIgbnVtYmVyKQpzaG91bGQgYmUgdHJlYXRlZCBhcyBhIDAgYW1vdW50IGFsbG93YW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJhcHByb3ZlIiwgZnJvbTogQWRkcmVzcywKc3BlbmRlcjogQWRkcmVzc10sIGRhdGEgPSBbYW1vdW50OiBpMTI4LCBleHBpcmF0aW9uX2xlZGdlcjogdTMyXWAAAAAAB2FwcHJvdmUAAAAABAAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAABFleHBpcmF0aW9uX2xlZGdlcgAAAAAAAAQAAAAAAAAAAAAAAJhSZXR1cm5zIHRoZSBiYWxhbmNlIG9mIGBpZGAuCgojIEFyZ3VtZW50cwoKKiBgaWRgIC0gVGhlIGFkZHJlc3MgZm9yIHdoaWNoIGEgYmFsYW5jZSBpcyBiZWluZyBxdWVyaWVkLiBJZiB0aGUKYWRkcmVzcyBoYXMgbm8gZXhpc3RpbmcgYmFsYW5jZSwgcmV0dXJucyAwLgAAAAdiYWxhbmNlAAAAAAEAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAsAAAAAAAABYkJ1cm4gYGFtb3VudGAgZnJvbSBgZnJvbWAuCgpSZWR1Y2VzIGZyb20ncyBiYWxhbmNlIGJ5IHRoZSBhbW91bnQsIHdpdGhvdXQgdHJhbnNmZXJyaW5nIHRoZSBiYWxhbmNlCnRvIGFub3RoZXIgaG9sZGVyJ3MgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAABGJ1cm4AAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAALaQnVybiBgYW1vdW50YCBmcm9tIGBmcm9tYCwgY29uc3VtaW5nIHRoZSBhbGxvd2FuY2Ugb2YgYHNwZW5kZXJgLgoKUmVkdWNlcyBmcm9tJ3MgYmFsYW5jZSBieSB0aGUgYW1vdW50LCB3aXRob3V0IHRyYW5zZmVycmluZyB0aGUgYmFsYW5jZQp0byBhbm90aGVyIGhvbGRlcidzIGJhbGFuY2UuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gYnVybiB0aGUgYW1vdW50IGZyb20gZnJvbSdzIGJhbGFuY2UsIGlmCnRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlciBoYXMKb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZSB3aWxsIGJlCnJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSBidXJuLCBhbmQgaGF2aW5nIGl0cyBhbGxvd2FuY2UKY29uc3VtZWQgZHVyaW5nIHRoZSBidXJuLgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAACWJ1cm5fZnJvbQAAAAAAAAMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAABUUNsYXdiYWNrIGBhbW91bnRgIGZyb20gYGZyb21gIGFjY291bnQuIGBhbW91bnRgIGlzIGJ1cm5lZCBpbiB0aGUKY2xhd2JhY2sgcHJvY2Vzcy4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2UgZnJvbSB3aGljaCB0aGUgY2xhd2JhY2sgd2lsbAp0YWtlIHRva2Vucy4KKiBgYW1vdW50YCAtIFRoZSBhbW91bnQgb2YgdG9rZW5zIHRvIGJlIGNsYXdlZCBiYWNrLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbImNsYXdiYWNrIiwgYWRtaW46IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAACAUmV0dXJucyB0aGUgbnVtYmVyIG9mIGRlY2ltYWxzIHVzZWQgdG8gcmVwcmVzZW50IGFtb3VudHMgb2YgdGhpcyB0b2tlbi4KCiMgUGFuaWNzCgpJZiB0aGUgY29udHJhY3QgaGFzIG5vdCB5ZXQgYmVlbiBpbml0aWFsaXplZC4AAAAIZGVjaW1hbHMAAAAAAAAAAQAAAAQAAAAAAAAA801pbnRzIGBhbW91bnRgIHRvIGB0b2AuCgojIEFyZ3VtZW50cwoKKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSBtaW50ZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgbWludGVkLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbIm1pbnQiLCBhZG1pbjogQWRkcmVzcywgdG86IEFkZHJlc3NdLCBkYXRhCj0gYW1vdW50OiBpMTI4YAAAAAAEbWludAAAAAIAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAFlSZXR1cm5zIHRoZSBuYW1lIGZvciB0aGlzIHRva2VuLgoKIyBQYW5pY3MKCklmIHRoZSBjb250cmFjdCBoYXMgbm90IHlldCBiZWVuIGluaXRpYWxpemVkLgAAAAAAAARuYW1lAAAAAAAAAAEAAAAQAAAAAAAAAQxTZXRzIHRoZSBhZG1pbmlzdHJhdG9yIHRvIHRoZSBzcGVjaWZpZWQgYWRkcmVzcyBgbmV3X2FkbWluYC4KCiMgQXJndW1lbnRzCgoqIGBuZXdfYWRtaW5gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCBoZW5jZWZvcnRoIGJlIHRoZSBhZG1pbmlzdHJhdG9yCm9mIHRoaXMgdG9rZW4gY29udHJhY3QuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsic2V0X2FkbWluIiwgYWRtaW46IEFkZHJlc3NdLCBkYXRhID0KW25ld19hZG1pbjogQWRkcmVzc11gAAAACXNldF9hZG1pbgAAAAAAAAEAAAAAAAAACW5ld19hZG1pbgAAAAAAABMAAAAAAAAAAAAAAEZSZXR1cm5zIHRoZSBhZG1pbiBvZiB0aGUgY29udHJhY3QuCgojIFBhbmljcwoKSWYgdGhlIGFkbWluIGlzIG5vdCBzZXQuAAAAAAAFYWRtaW4AAAAAAAAAAAAAAQAAABMAAAAAAAABUFNldHMgd2hldGhlciB0aGUgYWNjb3VudCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4gSWYKYGF1dGhvcml6ZWRgIGlzIHRydWUsIGBpZGAgc2hvdWxkIGJlIGFibGUgdG8gdXNlIGl0cyBiYWxhbmNlLgoKIyBBcmd1bWVudHMKCiogYGlkYCAtIFRoZSBhZGRyZXNzIGJlaW5nIChkZS0pYXV0aG9yaXplZC4KKiBgYXV0aG9yaXplYCAtIFdoZXRoZXIgb3Igbm90IGBpZGAgY2FuIHVzZSBpdHMgYmFsYW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJzZXRfYXV0aG9yaXplZCIsIGlkOiBBZGRyZXNzXSwgZGF0YSA9ClthdXRob3JpemU6IGJvb2xdYAAAAA5zZXRfYXV0aG9yaXplZAAAAAAAAgAAAAAAAAACaWQAAAAAABMAAAAAAAAACWF1dGhvcml6ZQAAAAAAAAEAAAAAAAAAAAAAAFtSZXR1cm5zIHRoZSBzeW1ib2wgZm9yIHRoaXMgdG9rZW4uCgojIFBhbmljcwoKSWYgdGhlIGNvbnRyYWN0IGhhcyBub3QgeWV0IGJlZW4gaW5pdGlhbGl6ZWQuAAAAAAZzeW1ib2wAAAAAAAAAAAABAAAAEAAAAAAAAAFiVHJhbnNmZXIgYGFtb3VudGAgZnJvbSBgZnJvbWAgdG8gYHRvYC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKd2l0aGRyYXduIGZyb20uCiogYHRvYCAtIFRoZSBhZGRyZXNzIHdoaWNoIHdpbGwgcmVjZWl2ZSB0aGUgdHJhbnNmZXJyZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgdHJhbnNmZXJyZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsidHJhbnNmZXIiLCBmcm9tOiBBZGRyZXNzLCB0bzogQWRkcmVzc10sCmRhdGEgPSBhbW91bnQ6IGkxMjhgAAAAAAAIdHJhbnNmZXIAAAADAAAAAAAAAARmcm9tAAAAEwAAAAAAAAACdG8AAAAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAADMVRyYW5zZmVyIGBhbW91bnRgIGZyb20gYGZyb21gIHRvIGB0b2AsIGNvbnN1bWluZyB0aGUgYWxsb3dhbmNlIHRoYXQKYHNwZW5kZXJgIGhhcyBvbiBgZnJvbWAncyBiYWxhbmNlLiBBdXRob3JpemVkIGJ5IHNwZW5kZXIKKGBzcGVuZGVyLnJlcXVpcmVfYXV0aCgpYCkuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gdHJhbnNmZXIgdGhlIGFtb3VudCBmcm9tIGZyb20ncyBiYWxhbmNlCmlmIHRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlcgpoYXMgb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZQp3aWxsIGJlIHJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSB0cmFuc2ZlciwgYW5kIGhhdmluZyBpdHMKYWxsb3dhbmNlIGNvbnN1bWVkIGR1cmluZyB0aGUgdHJhbnNmZXIuCiogYGZyb21gIC0gVGhlIGFkZHJlc3MgaG9sZGluZyB0aGUgYmFsYW5jZSBvZiB0b2tlbnMgd2hpY2ggd2lsbCBiZQp3aXRoZHJhd24gZnJvbS4KKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSB0cmFuc2ZlcnJlZCB0b2tlbnMuCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSB0cmFuc2ZlcnJlZC4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJ0cmFuc2ZlciIsIGZyb206IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAANdHJhbnNmZXJfZnJvbQAAAAAAAAQAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAABQAAAAAAAAAAAAAAB0FwcHJvdmUAAAAAAQAAAAdhcHByb3ZlAAAAAAQAAAAAAAAABGZyb20AAAATAAAAAQAAAAAAAAAHc3BlbmRlcgAAAAATAAAAAQAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAAARZXhwaXJhdGlvbl9sZWRnZXIAAAAAAAAEAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAIVHJhbnNmZXIAAAABAAAACHRyYW5zZmVyAAAAAwAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAADVRyYW5zZmVyTXV4ZWQAAAAAAAABAAAACHRyYW5zZmVyAAAABAAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAAC3RvX211eGVkX2lkAAAAAAQAAAAAAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAgAAAAUAAAAAAAAAAAAAAARCdXJuAAAAAQAAAARidXJuAAAAAgAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAARNaW50AAAAAQAAAARtaW50AAAAAgAAAAAAAAACdG8AAAAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAhDbGF3YmFjawAAAAEAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAACFNldEFkbWluAAAAAQAAAAlzZXRfYWRtaW4AAAAAAAABAAAAAAAAAAluZXdfYWRtaW4AAAAAAAATAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAANU2V0QXV0aG9yaXplZAAAAAAAAAEAAAAOc2V0X2F1dGhvcml6ZWQAAAAAAAIAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAAAAAAJYXV0aG9yaXplAAAAAAAAAQAAAAAAAAAA");return Ua.fromSpec(r)}generate(e){this.validateOptions(e);const t=new xa(this.spec),n=new Ra(this.spec),r=t.generate(),o=n.generate();let s='export { Client } from "./client.js";';""!==r.trim()&&(s=s.concat('\nexport * from "./types.js";'));const i=new Ba,{packageJson:a,tsConfig:c,readme:u,gitignore:l}=i.generate(e);return{index:s,types:r,client:o,packageJson:a,tsConfig:c,readme:u,gitignore:l}}validateOptions(e){if(!e.contractName||""===e.contractName.trim())throw new Error("contractName is required and cannot be empty")}}e.Account=uo,e.AccountRequiresMemoError=B,e.Address=Xr,e.Asset=In,e.AssetType=En,e.AuthClawbackEnabledFlag=8,e.AuthImmutableFlag=4,e.AuthRequiredFlag=1,e.AuthRevocableFlag=2,e.BASE_FEE=xo,e.BadRequestError=I,e.BadResponseError=C,e.BindingGenerator=Ua,e.Claimant=Rn,e.Config=_,e.Contract=go,e.Federation=Yo,e.FeeBumpTransaction=co,e.Friendbot=ps,e.Horizon=xi,e.Hyper=oe.Hyper,e.Int128=Ao,e.Int256=So,e.Keypair=Tn,e.LiquidityPoolAsset=xn,e.LiquidityPoolFeeV18=30,e.LiquidityPoolId=_n,e.Memo=io,e.MemoHash=oo,e.MemoID=no,e.MemoNone=to,e.MemoReturn=so,e.MemoText=ro,e.MuxedAccount=ho,e.NetworkError=E,e.Networks=Oo,e.NotFoundError=k,e.Operation=Qr,e.ScInt=vo,e.SignerKey=mo,e.Soroban=Uo,e.SorobanDataBuilder=fo,e.StellarBase=Wo,e.StellarToml=ee,e.StrKey=wn,e.TimeoutInfinite=0,e.Transaction=ao,e.TransactionBase=Bn,e.TransactionBuilder=Ro,e.Uint128=yo,e.Uint256=wo,e.UnsignedHyper=oe.UnsignedHyper,e.Utils=P,e.WebAuth=ds,e.XdrLargeInt=bo,e.authorizeEntry=Fo,e.authorizeInvocation=Do,e.buildAuthorizationEntryPreimage=Mo,e.buildInvocationTree=$o,e.buildWithDelegatesEntry=qo,e.cereal=ie,e.contract=Ca,e.decodeAddressToMuxedAccount=Pn,e.encodeMuxedAccount=Un,e.encodeMuxedAccountToAddress=On,e.extractBaseAddress=Ln,e.getLiquidityPoolId=Cn,e.hash=nt,e.httpClient=T,e.humanizeEvents=No,e.nativeToScVal=Eo,e.rpc=Gi,e.scValToBigInt=To,e.scValToNative=ko,e.scvSortedMap=Io,e.sign=cn,e.verify=un,e.walkInvocationTree=Xo,e.xdr=se});
|
|
199
|
+
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const rt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ot,n:st,Gx:it,Gy:at,a:ct,d:ut,h:lt}=rt,dt=32,pt=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,pt),t},ht=(e,t,n="")=>{const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name&&"BYTES_PER_ELEMENT"in o&&1===o.BYTES_PER_ELEMENT;var o;const s=e?.length,i=void 0!==t;if(!r||i&&s!==t){const o=(n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${s}`:"type="+typeof e);throw r?new RangeError(o):new TypeError(o)}return e},ft=e=>new Uint8Array(e),mt=e=>Uint8Array.from(e),gt=(e,t)=>e.toString(16).padStart(t,"0"),yt=e=>Array.from(ht(e)).map(e=>gt(e,2)).join(""),wt=48,At=57,St=65,bt=70,vt=97,Tt=102,Et=e=>e>=wt&&e<=At?e-wt:e>=St&&e<=bt?e-(St-10):e>=vt&&e<=Tt?e-(vt-10):void 0,kt=e=>{const t="hex invalid";if("string"!=typeof e)return pt(t);const n=e.length,r=n/2;if(n%2)return pt(t);const o=ft(r);for(let n=0,s=0;n<r;n++,s+=2){const r=Et(e.charCodeAt(s)),i=Et(e.charCodeAt(s+1));if(void 0===r||void 0===i)return pt(t);o[n]=16*r+i}return o},It=()=>globalThis?.crypto,Ct=(...e)=>{let t=0;for(const n of e)t+=ht(n).length;const n=ft(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n},Bt=BigInt,xt=(e,t,n,r="bad number: out of range")=>{if(!(e=>"bigint"==typeof e)(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Rt=(e,t=ot)=>{const n=e%t;return n>=0n?n:t+n},_t=(1n<<255n)-1n,Pt=e=>{e<0n&&pt("negative coordinate");let t=19n*(e>>255n)+(e&_t);return t=19n*(t>>255n)+(t&_t),t%ot},Ot=e=>Rt(e,st),Ut=e=>{const t=en[e];return"function"!=typeof t&&pt("hashes."+e+" not set"),t},Lt=e=>ht(e,64,"digest"),Nt=e=>e instanceof Ft?e:pt("Point expected"),Vt=2n**256n;class Ft{static BASE;static ZERO;X;Y;Z;T;constructor(e,t,n,r){const o=Vt;this.X=xt(e,0n,o),this.Y=xt(t,0n,o),this.Z=xt(n,1n,o),this.T=xt(r,0n,o),Object.freeze(this)}static CURVE(){return rt}static fromAffine(e){return new Ft(e.x,e.y,1n,Pt(e.x*e.y))}static fromBytes(e,t=!1){const n=ut,r=mt(ht(e,dt)),o=e[31];r[31]=-129&o;const s=Ht(r);xt(s,0n,t?Vt:ot);const i=Pt(s*s),a=Rt(i-1n),c=Pt(n*i+1n);let{isValid:u,value:l}=Xt(a,c);u||pt("bad point: y not sqrt");const d=1n==(1n&l),p=!!(128&o);return!t&&0n===l&&p&&pt("bad point: x==0, isLastByteOdd"),p!==d&&(l=Rt(-l)),new Ft(l,s,1n,Pt(l*s))}static fromHex(e,t){return Ft.fromBytes(kt(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const e=ct,t=ut;if(this.is0())return pt("bad point: ZERO");const{X:n,Y:r,Z:o,T:s}=this,i=Pt(n*n),a=Pt(r*r),c=Pt(o*o),u=Pt(c*c),l=Pt(i*e);if(Pt(c*(l+a))!==Rt(u+Pt(t*Pt(i*a))))return pt("bad point: equation left != right (1)");return Pt(n*r)!==Pt(o*s)?pt("bad point: equation left != right (2)"):this}equals(e){const{X:t,Y:n,Z:r}=this,{X:o,Y:s,Z:i}=Nt(e),a=Pt(t*i),c=Pt(o*r),u=Pt(n*i),l=Pt(s*r);return a===c&&u===l}is0(){return this.equals(Mt)}negate(){return new Ft(Rt(-this.X),this.Y,this.Z,Rt(-this.T))}double(){const{X:e,Y:t,Z:n}=this,r=ct,o=Pt(e*e),s=Pt(t*t),i=Pt(2n*n*n),a=Pt(r*o),c=Rt(e+t),u=Rt(Pt(c*c)-o-s),l=Rt(a+s),d=Rt(l-i),p=Rt(a-s),h=Pt(u*d),f=Pt(l*p),m=Pt(u*p),g=Pt(d*l);return new Ft(h,f,g,m)}add(e){const{X:t,Y:n,Z:r,T:o}=this,{X:s,Y:i,Z:a,T:c}=Nt(e),u=ct,l=ut,d=Pt(t*s),p=Pt(n*i),h=Pt(Pt(o*l)*c),f=Pt(r*a),m=Rt(Pt(Rt(t+n)*Rt(s+i))-d-p),g=Rt(f-h),y=Rt(f+h),w=Rt(p-Pt(u*d)),A=Pt(m*g),S=Pt(y*w),b=Pt(m*w),v=Pt(g*y);return new Ft(A,S,v,b)}subtract(e){return this.add(Nt(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return Mt;if(xt(e,1n,st),!t&&this.is0())return Mt;if(1n===e)return this;if(this.equals(Dt))return sn(e).p;let n=Mt,r=Dt;for(let o=this;e>0n;o=o.double(),e>>=1n)1n&e?n=n.add(o):t&&(r=r.add(o));return n}multiplyUnsafe(e){return this.multiply(e,!1)}toAffine(){const{X:e,Y:t,Z:n}=this;if(this.equals(Mt))return{x:0n,y:1n};const r=((e,t)=>{(0n===e||t<=0n)&&pt("no inverse n="+e+" mod="+t);let n=Rt(e,t),r=t,o=0n,s=1n;for(;0n!==n;){const e=r%n,t=o-s*(r/n);r=n,n=e,o=s,s=t}return 1n===r?Rt(o,t):pt("no inverse")})(n,ot);1n!==Pt(n*r)&&pt("invalid inverse");return{x:Pt(e*r),y:Pt(t*r)}}toBytes(){const{x:e,y:t}=this.toAffine(),n=qt(t);return n[31]|=1n&e?128:0,n}toHex(){return yt(this.toBytes())}clearCofactor(){return this.multiply(Bt(lt),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.multiply(st/2n,!1).double();return st%2n&&(e=e.add(this)),e.is0()}}const Dt=new Ft(it,at,1n,Rt(it*at)),Mt=new Ft(0n,1n,1n,0n);Ft.BASE=Dt,Ft.ZERO=Mt;const qt=e=>kt(gt(xt(e,0n,Vt),64)).reverse(),Ht=e=>Bt("0x"+yt(mt(ht(e)).reverse())),Gt=(e,t)=>{let n=e;for(;t-- >0n;)n=Pt(n*n);return n},$t=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Xt=(e,t)=>{const n=Pt(t*Pt(t*t)),r=Pt(Pt(n*n)*t),o=(e=>{const t=Pt(e*e),n=Pt(t*e),r=Pt(Gt(n,2n)*n),o=Pt(Gt(r,1n)*e),s=Pt(Gt(o,5n)*o),i=Pt(Gt(s,10n)*s),a=Pt(Gt(i,20n)*i),c=Pt(Gt(a,40n)*a),u=Pt(Gt(c,80n)*c),l=Pt(Gt(u,80n)*c),d=Pt(Gt(l,10n)*s);return{pow_p_5_8:Pt(Gt(d,2n)*e),b2:n}})(Pt(e*r)).pow_p_5_8;let s=Pt(e*Pt(n*o));const i=Pt(t*Pt(s*s)),a=s,c=Pt(s*$t),u=i===e,l=i===Rt(-e),d=i===Rt(-e*$t);return u&&(s=a),(l||d)&&(s=c),1n==(1n&Rt(s))&&(s=Rt(-s)),{isValid:u||l,value:s}},Kt=e=>Ot(Ht(e)),Wt=(...e)=>Lt(Ut("sha512")(Ct(...e))),Zt=e=>{const t=mt(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;const r=t.slice(32,64),o=Kt(n),s=Dt.multiply(o),i=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:i}},zt=e=>Zt(Wt(ht(e,dt))),jt=e=>e.finish(Wt(e.hashable)),Yt=(e,t)=>{const n=ht(e),r=zt(t),o=Wt(r.prefix,n);return jt(((e,t,n)=>{const{pointBytes:r,scalar:o}=e,s=Kt(t),i=Dt.multiply(s).toBytes();return{hashable:Ct(i,r,n),finish:e=>{const t=Ot(s+Kt(e)*o);return ht(Ct(i,qt(t)),64)}}})(r,o,n))},Jt={zip215:!0},Qt=(e,t,n,r=Jt)=>jt(((e,t,n,r=Jt)=>{e=ht(e,64),t=ht(t),n=ht(n,dt);const{zip215:o=!0}=r,s=e.subarray(0,dt),i=Ht(e.subarray(dt,64));let a,c,u,l=Uint8Array.of(),d=!1;try{a=Ft.fromBytes(n,o),c=Ft.fromBytes(s,o),u=Dt.multiply(i,!1),l=Ct(s,n,t),d=!0}catch(e){}return{hashable:l,finish:e=>{if(!d)return!1;if(!o&&a.isSmallOrder())return!1;const t=Kt(e);return c.add(a.multiply(t,!1)).subtract(u).clearCofactor().is0()}}})(e,t,n,r)),en={sha512Async:async e=>{const t=It()?.subtle??pt("crypto.subtle must be defined, consider polyfill"),n=Ct(e);return ft(await t.digest("SHA-512",n.buffer))},sha512:void 0},tn=Object.freeze({getExtendedPublicKeyAsync:e=>((...e)=>Promise.resolve(Ut("sha512Async")(Ct(...e))).then(Lt))(ht(e,dt)).then(Zt),getExtendedPublicKey:zt,randomSecretKey:e=>(e=void 0===e?((e=dt)=>It().getRandomValues(ft(e)))(dt):e,ht(e,dt))}),nn=Math.ceil(32)+1;let rn;const on=(e,t)=>{const n=t.negate();return e?n:t},sn=e=>{const t=rn||(rn=(()=>{const e=[];let t=Dt,n=t;for(let r=0;r<nn;r++){n=t,e.push(n);for(let r=1;r<128;r++)n=n.add(t),e.push(n);t=n.double()}return e})());let n=Mt,r=Dt;const o=Bt(255),s=Bt(8);for(let i=0;i<nn;i++){let a=Number(e&o);e>>=s,a>128&&(a-=256,e+=1n);const c=128*i,u=c,l=c+Math.abs(a)-1,d=i%2!=0,p=a<0;0===a?r=r.add(on(d,t[u])):n=n.add(on(p,t[l]))}return 0n!==e&&pt("invalid wnaf"),{p:n,f:r}};function an(e){return fe.Buffer.from(zt(e).pointBytes)}function cn(e,t){return fe.Buffer.from(Yt(fe.Buffer.from(e),t))}function un(e,t,n){return Qt(fe.Buffer.from(t),fe.Buffer.from(e),fe.Buffer.from(n),{zip215:!1})}en.sha512=tt;const ln=(e,t)=>{const n="number"==typeof e;let r=String(e);for(;r.endsWith(t);)r=r.slice(0,-1);return n?Number(r):r};var dn,pn={};var hn=(dn||(dn=1,function(e){var t=function(e,t){return t||(t={}),e.split("").forEach(function(e,n){e in t||(t[e]=n)}),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=t(n.alphabet,n.charmap);var r={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};r.charmap=t(r.alphabet,r.charmap);var o={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function s(t){if(this.buf=[],this.shift=8,this.carry=0,t){switch(t.type){case"rfc4648":this.charmap=e.rfc4648.charmap;break;case"crockford":this.charmap=e.crockford.charmap;break;case"base32hex":this.charmap=e.base32hex.charmap;break;default:throw new Error("invalid type")}t.charmap&&(this.charmap=t.charmap)}}function i(t){if(this.buf="",this.shift=3,this.carry=0,t){switch(t.type){case"rfc4648":this.alphabet=e.rfc4648.alphabet;break;case"crockford":this.alphabet=e.crockford.alphabet;break;case"base32hex":this.alphabet=e.base32hex.alphabet;break;default:throw new Error("invalid type")}t.alphabet?this.alphabet=t.alphabet:t.lc&&(this.alphabet=this.alphabet.toLowerCase())}}o.charmap=t(o.alphabet,o.charmap),s.prototype.charmap=n.charmap,s.prototype.write=function(e){var t=this.charmap,n=this.buf,r=this.shift,o=this.carry;return e.toUpperCase().split("").forEach(function(e){if("="!=e){var s=255&t[e];(r-=5)>0?o|=s<<r:r<0?(n.push(o|s>>-r),o=s<<(r+=8)&255):(n.push(o|s),r=8,o=0)}}),this.shift=r,this.carry=o,this},s.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},i.prototype.alphabet=n.alphabet,i.prototype.write=function(e){var t,n,r,o=this.shift,s=this.carry;for(r=0;r<e.length;r++)t=s|(n=e[r])>>o,this.buf+=this.alphabet[31&t],o>5&&(t=n>>(o-=5),this.buf+=this.alphabet[31&t]),s=n<<(o=5-o),o=8-o;return this.shift=o,this.carry=s,this},i.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},e.encode=function(e,t){return new i(t).finalize(e)},e.decode=function(e,t){return new s(t).finalize(e)},e.Decoder=s,e.Encoder=i,e.charmap=t,e.crockford=r,e.rfc4648=n,e.base32hex=o}(pn)),pn),fn=te(hn);const mn={ed25519PublicKey:48,ed25519SecretSeed:144,med25519PublicKey:96,preAuthTx:152,sha256Hash:184,signedPayload:120,contract:16,liquidityPool:88,claimableBalance:8},gn={G:"ed25519PublicKey",S:"ed25519SecretSeed",M:"med25519PublicKey",T:"preAuthTx",X:"sha256Hash",P:"signedPayload",C:"contract",L:"liquidityPool",B:"claimableBalance"};function yn(e){return Object.prototype.hasOwnProperty.call(mn,e)}class wn{static types=gn;static encodeEd25519PublicKey(e){return bn("ed25519PublicKey",e)}static decodeEd25519PublicKey(e){return Sn("ed25519PublicKey",e)}static isValidEd25519PublicKey(e){return An("ed25519PublicKey",e)}static encodeEd25519SecretSeed(e){return bn("ed25519SecretSeed",e)}static decodeEd25519SecretSeed(e){return Sn("ed25519SecretSeed",e)}static isValidEd25519SecretSeed(e){return An("ed25519SecretSeed",e)}static encodeMed25519PublicKey(e){return bn("med25519PublicKey",e)}static decodeMed25519PublicKey(e){return Sn("med25519PublicKey",e)}static isValidMed25519PublicKey(e){return An("med25519PublicKey",e)}static encodePreAuthTx(e){return bn("preAuthTx",e)}static decodePreAuthTx(e){return Sn("preAuthTx",e)}static encodeSha256Hash(e){return bn("sha256Hash",e)}static decodeSha256Hash(e){return Sn("sha256Hash",e)}static encodeSignedPayload(e){return bn("signedPayload",e)}static decodeSignedPayload(e){return Sn("signedPayload",e)}static isValidSignedPayload(e){return An("signedPayload",e)}static encodeContract(e){return bn("contract",e)}static decodeContract(e){return Sn("contract",e)}static isValidContract(e){return An("contract",e)}static encodeClaimableBalance(e){return bn("claimableBalance",e)}static decodeClaimableBalance(e){return Sn("claimableBalance",e)}static isValidClaimableBalance(e){return An("claimableBalance",e)}static encodeLiquidityPool(e){return bn("liquidityPool",e)}static decodeLiquidityPool(e){return Sn("liquidityPool",e)}static isValidLiquidityPool(e){return An("liquidityPool",e)}static getVersionByteForPrefix(e){if(e.length<1)return;const t=e[0];return gn[t]}}function An(e,t){if("string"!=typeof t)return!1;switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":case"liquidityPool":if(56!==t.length)return!1;break;case"claimableBalance":if(58!==t.length)return!1;break;case"med25519PublicKey":if(69!==t.length)return!1;break;case"signedPayload":if(t.length<56||t.length>165)return!1;break;default:return!1}let n;try{n=Sn(e,t)}catch{return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":case"liquidityPool":return 32===n.length;case"claimableBalance":return 33===n.length;case"med25519PublicKey":return 40===n.length;case"signedPayload":return n.length>=40&&n.length<=100;default:return!1}}function Sn(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");const n=fn.decode(t),r=n[0],o=n.slice(0,-2),s=o.slice(1),i=n.slice(-2);if(t!==fn.encode(n))throw new Error("invalid encoded string");if(!yn(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(mn).join(", ")}`);const a=mn[e];if(r!==a)throw new Error(`invalid version byte. expected ${a}, got ${r}`);if(!function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}(vn(o),i))throw new Error("invalid checksum");return fe.Buffer.from(s)}function bn(e,t){if(null==t)throw new Error("cannot encode null data");if(!yn(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(mn).join(", ")}`);const n=mn[e];t=fe.Buffer.from(t);const r=fe.Buffer.from([n]),o=fe.Buffer.concat([r,t]),s=fe.Buffer.from(vn(o)),i=fe.Buffer.concat([o,s]);return fn.encode(i)}function vn(e){const t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920];let n=0;for(let r=0;r<e.length;r+=1){const o=e[r];if(void 0===o)continue;n=n<<8^(t[n>>8^o]??0),n&=65535}const r=new Uint8Array(2);return r[0]=255&n,r[1]=n>>8&255,r}en.sha512=tt;class Tn{type;_publicKey;_secretSeed;_secretKey;constructor(e){if("ed25519"!==e.type)throw new Error("Invalid keys type");if(this.type=e.type,"secretKey"in e){if(e.secretKey=fe.Buffer.from(e.secretKey),32!==e.secretKey.length)throw new Error("secretKey length is invalid");if(this._secretSeed=e.secretKey,this._publicKey=an(e.secretKey),this._secretKey=e.secretKey,e.publicKey&&!this._publicKey.equals(fe.Buffer.from(e.publicKey)))throw new Error("secretKey does not match publicKey")}else{if(!("publicKey"in e))throw new Error("At least one of publicKey or secretKey must be provided");if(this._publicKey=fe.Buffer.from(e.publicKey),32!==this._publicKey.length)throw new Error("publicKey length is invalid")}}static fromSecret(e){const t=wn.decodeEd25519SecretSeed(e);return this.fromRawEd25519Seed(t)}static fromRawEd25519Seed(e){return new this({type:"ed25519",secretKey:e})}static master(e){if(!e)throw new Error("No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.");return this.fromRawEd25519Seed(nt(e))}static fromPublicKey(e){const t=wn.decodeEd25519PublicKey(e);if(32!==t.length)throw new Error("Invalid Stellar public key");return new this({type:"ed25519",publicKey:t})}static random(){const e=tn.randomSecretKey();return this.fromRawEd25519Seed(fe.Buffer.from(e))}xdrAccountId(){return se.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrPublicKey(){return se.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrMuxedAccount(e){if(void 0!==e){if("string"!=typeof e)throw new TypeError("expected string for ID, got "+typeof e);return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromString(e),ed25519:this._publicKey}))}return se.MuxedAccount.keyTypeEd25519(this._publicKey)}rawPublicKey(){return this._publicKey}signatureHint(){const e=this.xdrAccountId().toXDR();return e.subarray(e.length-4)}publicKey(){return wn.encodeEd25519PublicKey(this._publicKey)}secret(){if(!this._secretSeed)throw new Error("no secret key available");if("ed25519"===this.type)return wn.encodeEd25519SecretSeed(this._secretSeed);throw new Error("Invalid Keypair type")}rawSecretKey(){if(!this._secretSeed)throw new Error("no secret seed available");return this._secretSeed}canSign(){return!!this._secretKey}sign(e){if(!this._secretKey)throw new Error("cannot sign: no secret key available");return cn(e,this._secretKey)}verify(e,t){try{return un(e,t,this._publicKey)}catch{return!1}}signDecorated(e){const t=this.sign(e),n=this.signatureHint();return new se.DecoratedSignature({hint:n,signature:t})}signPayloadDecorated(e){const t=fe.Buffer.isBuffer(e)?e:fe.Buffer.from(e),n=this.sign(t),r=this.signatureHint();let o=fe.Buffer.from(t.subarray(-4));o.length<4&&(o=fe.Buffer.concat([o,fe.Buffer.alloc(4-o.length,0)]));for(let e=0;e<o.length;e++)o[e]=o[e]^r[e];return new se.DecoratedSignature({hint:o,signature:n})}}const En={native:"native",credit4:"credit_alphanum4",credit12:"credit_alphanum12",liquidityPoolShares:"liquidity_pool_shares"};function kn(e,t){return fe.Buffer.compare(fe.Buffer.from(e,"ascii"),fe.Buffer.from(t,"ascii"))}class In{code;issuer;constructor(e,t){if(!/^[a-zA-Z0-9]{1,12}$/.test(e))throw new Error("Asset code is invalid (maximum alphanumeric, 12 characters at max)");if("xlm"!==String(e).toLowerCase()&&!t)throw new Error("Issuer cannot be null");if(t&&!wn.isValidEd25519PublicKey(t))throw new Error("Issuer is invalid");"xlm"===String(e).toLowerCase()?this.code="XLM":this.code=e,this.issuer=t}static native(){return new In("XLM")}static fromOperation(e){let t,n,r;switch(e.switch()){case se.AssetType.assetTypeNative():return this.native();case se.AssetType.assetTypeCreditAlphanum4():return t=e.alphaNum4(),r=wn.encodeEd25519PublicKey(t.issuer().ed25519()),n=ln(t.assetCode().toString(),"\0"),new this(n,r);case se.AssetType.assetTypeCreditAlphanum12():return t=e.alphaNum12(),r=wn.encodeEd25519PublicKey(t.issuer().ed25519()),n=ln(t.assetCode().toString(),"\0"),new this(n,r);default:throw new Error(`Invalid asset type: ${e.switch().name}`)}}toXDRObject(){return this._toXDRObject(se.Asset)}toChangeTrustXDRObject(){return this._toXDRObject(se.ChangeTrustAsset)}toTrustLineXDRObject(){return this._toXDRObject(se.TrustLineAsset)}contractId(e){const t=nt(fe.Buffer.from(e)),n=se.HashIdPreimage.envelopeTypeContractId(new se.HashIdPreimageContractId({networkId:t,contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject())}));return wn.encodeContract(nt(n.toXDR()))}_toXDRObject(e){if(this.isNative())return e.assetTypeNative();if(!this.issuer)throw new Error("Issuer cannot be null for non-native asset");let t,n;this.code.length<=4?(t=se.AlphaNum4,n="assetTypeCreditAlphanum4"):(t=se.AlphaNum12,n="assetTypeCreditAlphanum12");const r=this.code.length<=4?4:12;return new e(n,new t({assetCode:this.code.padEnd(r,"\0"),issuer:Tn.fromPublicKey(this.issuer).xdrAccountId()}))}getCode(){return String(this.code)}getIssuer(){if(void 0!==this.issuer)return String(this.issuer)}getAssetType(){switch(this.getRawAssetType().value){case se.AssetType.assetTypeNative().value:return En.native;case se.AssetType.assetTypeCreditAlphanum4().value:return En.credit4;case se.AssetType.assetTypeCreditAlphanum12().value:return En.credit12;default:throw new Error("Supported asset types are: native, credit_alphanum4, credit_alphanum12")}}getRawAssetType(){return this.isNative()?se.AssetType.assetTypeNative():this.code.length<=4?se.AssetType.assetTypeCreditAlphanum4():se.AssetType.assetTypeCreditAlphanum12()}isNative(){return!this.issuer}equals(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}toString(){return this.isNative()?"native":`${this.getCode()}:${this.getIssuer()}`}static compare(e,t){if(!(e&&e instanceof In))throw new Error("assetA is invalid");if(!(t&&t instanceof In))throw new Error("assetB is invalid");if(e.equals(t))return 0;const n=e.getRawAssetType().value,r=t.getRawAssetType().value;if(n!==r)return n<r?-1:1;const o=kn(e.getCode(),t.getCode());if(0!==o)return o;const s=e.getIssuer(),i=t.getIssuer();if(void 0===s||void 0===i)throw new Error("Issuer is undefined for non-native asset");return kn(s,i)}}function Cn(e,t){if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");const{assetA:n,assetB:r,fee:o}=t??{};if(!(n&&n instanceof In))throw new Error("assetA is invalid");if(!(r&&r instanceof In))throw new Error("assetB is invalid");if(!o||30!==o)throw new Error("fee is invalid");if(-1!==In.compare(n,r))throw new Error("Assets are not in lexicographic order");return nt(se.LiquidityPoolParameters.liquidityPoolConstantProduct(new se.LiquidityPoolConstantProductParameters({assetA:n.toXDRObject(),assetB:r.toXDRObject(),fee:o})).toXDR())}class Bn{_tx;_signatures;_fee;_networkPassphrase;constructor(e,t,n,r){if("string"!=typeof r)throw new Error("Invalid passphrase provided to Transaction: expected a string but got a "+typeof r);this._networkPassphrase=r,this._tx=e,this._signatures=t,this._fee=n}get signatures(){return this._signatures}set signatures(e){throw new Error("Transaction is immutable")}get tx(){const e=this._tx.toXDR();if(this._tx instanceof se.Transaction)return se.Transaction.fromXDR(e);if(this._tx instanceof se.TransactionV0)return se.TransactionV0.fromXDR(e);if(this._tx instanceof se.FeeBumpTransaction)return se.FeeBumpTransaction.fromXDR(e);throw new Error("Unknown transaction type")}set tx(e){throw new Error("Transaction is immutable")}get fee(){return this._fee}set fee(e){throw new Error("Transaction is immutable")}get networkPassphrase(){return this._networkPassphrase}set networkPassphrase(e){throw new Error("Transaction is immutable")}sign(...e){const t=this.hash();e.forEach(e=>{const n=e.signDecorated(t);this.signatures.push(n)})}getKeypairSignature(e){return e.sign(this.hash()).toString("base64")}addSignature(e="",t=""){if(!t||"string"!=typeof t)throw new Error("Invalid signature");if(!e||"string"!=typeof e)throw new Error("Invalid publicKey");let n,r;const o=fe.Buffer.from(t,"base64");try{n=Tn.fromPublicKey(e),r=n.signatureHint()}catch{throw new Error("Invalid publicKey")}if(!n.verify(this.hash(),o))throw new Error("Invalid signature");this.signatures.push(new se.DecoratedSignature({hint:r,signature:o}))}addDecoratedSignature(e){this.signatures.push(e)}signHashX(e){if("string"==typeof e&&(e=fe.Buffer.from(e,"hex")),e.length>64)throw new Error("preimage cannot be longer than 64 bytes");const t=e,n=nt(e),r=n.subarray(n.length-4);this.signatures.push(new se.DecoratedSignature({hint:r,signature:t}))}hash(){return nt(this.signatureBase())}signatureBase(){throw new Error("Implement in subclass")}toEnvelope(){throw new Error("Implement in subclass")}toXDR(){return this.toEnvelope().toXDR().toString("base64")}}class xn{assetA;assetB;fee;constructor(e,t,n){if(!(e&&e instanceof In))throw new Error("assetA is invalid");if(!(t&&t instanceof In))throw new Error("assetB is invalid");if(-1!==In.compare(e,t))throw new Error("Assets are not in lexicographic order");if(!n||30!==n)throw new Error("fee is invalid");this.assetA=e,this.assetB=t,this.fee=n}static fromOperation(e){const t=e.switch();if(t===se.AssetType.assetTypePoolShare()){const t=e.liquidityPool().constantProduct();return new this(In.fromOperation(t.assetA()),In.fromOperation(t.assetB()),t.fee())}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=new se.LiquidityPoolConstantProductParameters({assetA:this.assetA.toXDRObject(),assetB:this.assetB.toXDRObject(),fee:this.fee}),t=se.LiquidityPoolParameters.liquidityPoolConstantProduct(e);return se.ChangeTrustAsset.assetTypePoolShare(t)}getLiquidityPoolParameters(){return{...this,assetA:this.assetA,assetB:this.assetB,fee:this.fee}}getAssetType(){return"liquidity_pool_shares"}equals(e){return this.assetA.equals(e.assetA)&&this.assetB.equals(e.assetB)&&this.fee===e.fee}toString(){return`liquidity_pool:${Cn("constant_product",this.getLiquidityPoolParameters()).toString("hex")}`}}class Rn{_destination;_predicate;constructor(e,t){if(!wn.isValidEd25519PublicKey(e))throw new Error("Destination is invalid");if(this._destination=e,t){if(!(t instanceof se.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");this._predicate=t}else this._predicate=se.ClaimPredicate.claimPredicateUnconditional()}static predicateUnconditional(){return se.ClaimPredicate.claimPredicateUnconditional()}static predicateAnd(e,t){if(!(e instanceof se.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof se.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateAnd([e,t])}static predicateOr(e,t){if(!(e instanceof se.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof se.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateOr([e,t])}static predicateNot(e){if(!(e instanceof se.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");return se.ClaimPredicate.claimPredicateNot(e)}static predicateBeforeAbsoluteTime(e){return se.ClaimPredicate.claimPredicateBeforeAbsoluteTime(se.Int64.fromString(e))}static predicateBeforeRelativeTime(e){return se.ClaimPredicate.claimPredicateBeforeRelativeTime(se.Int64.fromString(e))}static fromXDR(e){let t;if(e.switch()===se.ClaimantType.claimantTypeV0())return t=e.v0(),new this(wn.encodeEd25519PublicKey(t.destination().ed25519()),t.predicate());throw new Error(`Invalid claimant type: ${e.switch().name}`)}toXDRObject(){const e=new se.ClaimantV0({destination:Tn.fromPublicKey(this._destination).xdrAccountId(),predicate:this._predicate});return se.Claimant.claimantTypeV0(e)}get destination(){return this._destination}set destination(e){throw new Error("Claimant is immutable")}get predicate(){return this._predicate}set predicate(e){throw new Error("Claimant is immutable")}}class _n{liquidityPoolId;constructor(e){if(!e)throw new Error("liquidityPoolId cannot be empty");if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Liquidity pool ID is not a valid hash");this.liquidityPoolId=e}static fromOperation(e){const t=e.switch();if(t===se.AssetType.assetTypePoolShare()){const t=e.liquidityPoolId().toString("hex");return new _n(t)}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=fe.Buffer.from(this.liquidityPoolId,"hex");return se.TrustLineAsset.assetTypePoolShare(e)}getLiquidityPoolId(){return String(this.liquidityPoolId)}getAssetType(){return"liquidity_pool_shares"}equals(e){return this.liquidityPoolId===e.getLiquidityPoolId()}toString(){return`liquidity_pool:${this.liquidityPoolId}`}}function Pn(e){return wn.isValidMed25519PublicKey(e)?function(e){const t=wn.decodeMed25519PublicKey(e);return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):se.MuxedAccount.keyTypeEd25519(wn.decodeEd25519PublicKey(e))}function On(e){return e.switch().value===se.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===se.CryptoKeyType.keyTypeEd25519())return On(e);const t=e.med25519();return wn.encodeMed25519PublicKey(fe.Buffer.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):wn.encodeEd25519PublicKey(e.ed25519())}function Un(e,t){if(!wn.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return se.MuxedAccount.keyTypeMuxedEd25519(new se.MuxedAccountMed25519({id:se.Uint64.fromString(t),ed25519:wn.decodeEd25519PublicKey(e)}))}function Ln(e){if(wn.isValidEd25519PublicKey(e))return e;if(!wn.isValidMed25519PublicKey(e))throw new TypeError(`expected muxed account (M...), got ${e}`);const t=Pn(e);return wn.encodeEd25519PublicKey(t.med25519().ed25519())}var Nn=function e(t){var n,r,o=/^(-?)0([xbo])(?=[^.])/i,s=/^-?(Infinity|NaN)$/,i=/^\s*\+(?!-)|^\s+|\s+$/g,a=b.prototype={constructor:b,toString:null,valueOf:null},c=new b(1),u=20,l=4,d=-7,p=21,h=-1e7,f=1e7,m=!1,g=!0,y=1,w=0,A={prefix:"",negativeSign:"-",positiveSign:"",groupSeparator:",",groupSize:3,secondaryGroupSize:0,decimalSeparator:".",fractionGroupSeparator:"",fractionGroupSize:0,suffix:""},S="0123456789abcdefghijklmnopqrstuvwxyz";function b(e,t){var n,r,a,c,u=this;if(!(u instanceof b))return new b(e,t);if(c=typeof e,null==t){if(k(e))return u.s=e.s,void(!e.c||e.e>f?u.c=u.e=null:e.e<h?u.c=[u.e=0]:(u.e=e.e,u.c=e.c.slice()));if("number"==c){if(0*e!=0)return u.s=isNaN(e)?null:e<0?-1:1,void(u.c=u.e=null);if(u.s=1/e<0?(e=-e,-1):1,e===~~e){for(n=0,r=e;r>=10;r/=10,n++);return void(n>f?u.c=u.e=null:(u.e=n,u.c=[e]))}return v(u,String(e))}if("bigint"==c)return u.s=e<0?(e=-e,-1):1,v(u,String(e));if("string"==c)a=e;else{if(g)throw Error(Mn+"BigNumber, string, number, or BigInt expected: "+e);a=String(e)}if(Vn.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,v(u,a);if(a=a.replace(i,""),s.test(a))return u.s=isNaN(a)?null:a<0?-1:1,void(u.c=u.e=null);if(a=a.replace(o,function(e,n,r){return t="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n}),t)return T(u,a,t,e);if(a=a.replace(/(\d)_(?=\d)/g,"$1"),Vn.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,v(u,a);if(g)throw Error(Mn+"Not a number: "+e);u.s=u.c=u.e=null}else{if("string"!=c){if(g)throw Error(Mn+"String expected: "+e);e=String(e)}jn(t,2,S.length,"Base"),T(u,e.replace(i,""),t,e)}}function v(e,t){var n,r,o;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;48===t.charCodeAt(r);r++);for(o=t.length;48===t.charCodeAt(--o););if(t=t.slice(r,++o))if(o-=r,(n=n-r-1)>f)e.c=e.e=null;else if(n<h)e.c=[e.e=0];else{if(e.e=n,e.c=[],r=(n+1)%Hn,n<0&&(r+=Hn),r<o){for(r&&e.c.push(+t.slice(0,r)),o-=Hn;r<o;)e.c.push(+t.slice(r,r+=Hn));r=Hn-(t=t.slice(r)).length}else r-=o;for(;r--;t+="0");e.c.push(+t)}else e.c=[e.e=0]}function T(e,t,n,o){var s,i,a=S.slice(0,n),c=0,u="",l=!1,d=!1,p=!1;for(e.s=45===t.charCodeAt(0)?(t=t.slice(1),-1):1,i=t.length;c<i;c++){if(s=t.charAt(c),!(a.indexOf(s)>=0)){if("_"==s){if(d&&c+1<i){d=!1;continue}}else if("."==s){if(0==c||!l&&d){if(c+1==i)break;0==c&&(u="0"),u+=s,l=!0,d=!1;continue}}else if(!p&&(t==t.toUpperCase()&&a==a.toLowerCase()&&(t=t.toLowerCase())||t==t.toLowerCase()&&a==a.toUpperCase()&&(t=t.toUpperCase()))){c=-1,u="",p=!0,l=d=!1;continue}if(g)throw Error(Mn+"Not a base "+n+" number: "+o);return void(e.s=e.c=e.e=null)}u+=s,d=!0}v(e,r(u,n,10,e.s))}function E(e,t,n,r){var o,s,i,a,c;if(n=null==n?l:jn(n,0,8),!e.c)return e.toString();if(o=e.c[0],i=e.e,null==t)c=Zn(e.c),c=1==r||2==r&&(i<=d||i>=p)?Qn(c,i):er(c,i,"0");else if(s=(e=x(new b(e),t,n)).e,a=(c=Zn(e.c)).length,1==r||2==r&&(t<=s||s<=d)){for(;a<t;c+="0",a++);c=Qn(c,s)}else if(t-=i+(2===r&&s>i),c=er(c,s,"0"),s+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=s-a)>0)for(s+1==a&&(c+=".");t--;c+="0");return e.s<0&&o?"-"+c:c}function k(e){return e instanceof b||!!e&&!0===e._isBigNumber}function I(e,t){for(var n,r,o=1,s=new b(e[0]);o<e.length;o++)(!(r=new b(e[o])).s||(n=zn(s,r))===t||0===n&&s.s===t)&&(s=r);return s}function C(e,t,n){for(var r=1,o=t.length;!t[--o];t.pop());for(o=t[0];o>=10;o/=10,r++);return(n=r+n*Hn-1)>f?e.c=e.e=null:n<h?e.c=[e.e=0]:(e.e=n,e.c=t),e}function B(e){var t,n={};for(t in A)A.hasOwnProperty(t)&&(n[t]=e.hasOwnProperty(t)?e[t]:A[t]);return n}function x(e,t,n,r){var o,s,i,a,c,u,l,d=e.c,p=$n;if(d){e:{for(o=1,a=d[0];a>=10;a/=10,o++);if((s=t-o)<0)s+=Hn,i=t,c=d[u=0],l=Dn(c/p[o-i-1]%10);else if((u=Fn((s+1)/Hn))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,o=1,i=(s%=Hn)-Hn+1}else{for(c=a=d[u],o=1;a>=10;a/=10,o++);l=(i=(s%=Hn)-Hn+o)<0?0:Dn(c/p[o-i-1]%10)}if(r=r||t<0||null!=d[u+1]||(i<0?c:c%p[o-i-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(s>0?i>0?c/p[o-i]:0:d[u-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,r?(t-=e.e+1,d[0]=p[(Hn-t%Hn)%Hn],e.e=-t||0):d[0]=e.e=0,e;if(0==s?(d.length=u,a=1,u--):(d.length=u+1,a=p[Hn-s],d[u]=i>0?Dn(c/p[o-i]%p[i])*a:0),r)for(;;){if(0==u){for(s=1,i=d[0];i>=10;i/=10,s++);for(i=d[0]+=a,a=1;i>=10;i/=10,a++);s!=a&&(e.e++,d[0]==qn&&(d[0]=1));break}if(d[u]+=a,d[u]!=qn)break;d[u--]=0,a=1}for(s=d.length;0===d[--s];d.pop());}e.e>f?e.c=e.e=null:e.e<h&&(e.c=[e.e=0])}return e}function R(e){var t,n=e.e;return null===n?e.toString():(t=Zn(e.c),t=n<=d||n>=p?Qn(t,n):er(t,n,"0"),e.s<0?"-"+t:t)}b.clone=e,b.ROUND_UP=0,b.ROUND_DOWN=1,b.ROUND_CEIL=2,b.ROUND_FLOOR=3,b.ROUND_HALF_UP=4,b.ROUND_HALF_DOWN=5,b.ROUND_HALF_EVEN=6,b.ROUND_HALF_CEIL=7,b.ROUND_HALF_FLOOR=8,b.EUCLID=9,b.config=b.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(Mn+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(u=jn(e[t],0,Kn,t)),e.hasOwnProperty(t="ROUNDING_MODE")&&(l=jn(e[t],0,8,t)),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(Yn(n=e[t])?(jn(n[0],-Kn,0,t),jn(n[1],0,Kn,t),d=n[0],p=n[1]):d=-(p=jn(n,-Kn,Kn,t)<0?-n:n)),e.hasOwnProperty(t="RANGE")){if(!(n=e[t]))throw Error(Mn+t+" cannot be zero: "+n);Yn(n)?(jn(n[0],-Kn,-1,t),jn(n[1],1,Kn,t),h=n[0],f=n[1]):h=-(f=jn(n,-Kn,Kn,t)<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(Mn+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw m=!n,Error(Mn+"crypto unavailable");m=n}else m=n}if(e.hasOwnProperty(t="STRICT")){if((n=e[t])!==!!n)throw Error(Mn+t+" not true or false: "+n);g=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(y=jn(e[t],0,9,t)),e.hasOwnProperty(t="POW_PRECISION")&&(w=jn(e[t],0,Kn,t)),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(Mn+t+" not an object: "+n);for(t in n)n.hasOwnProperty(t)&&A.hasOwnProperty(t)&&(A[t]=n[t])}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(Mn+t+" invalid: "+n);S=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,p],RANGE:[h,f],CRYPTO:m,STRICT:g,MODULO_MODE:y,POW_PRECISION:w,FORMAT:A,ALPHABET:S}},b.fromFormat=function(e,t){if("string"!=typeof e)throw Error(Mn+"Not a string: "+e);if(null==t)t=A;else{if("object"!=typeof t)throw Error(Mn+"Argument not an object: "+t);t=B(t)}var n,r,o,s,i=t.negativeSign||"-",a=t.positiveSign||"",c=t.prefix||"",u=t.suffix||"",l=t.groupSeparator||"",d=t.decimalSeparator||".",p=t.fractionGroupSeparator||"";if(c&&0===e.indexOf(c)&&(e=e.slice(c.length)),u&&e.lastIndexOf(u)===e.length-u.length&&(e=e.slice(0,-u.length)),0===e.indexOf(i)?(e=e.slice(i.length),r=!0):a&&0===e.indexOf(a)&&(e=e.slice(a.length)),(n=e.indexOf(d))<0){if(l)for(;e.indexOf(l)>-1;)e=e.replace(l,"")}else{if(o=e.slice(0,n),s=e.slice(n+d.length),l)for(;o.indexOf(l)>-1;)o=o.replace(l,"");if(p)for(;s.indexOf(p)>-1;)s=s.replace(p,"");e=o+"."+s}return new b(r?"-"+e:e)},b.isBigNumber=function(e){if(!k(e))return!1;var t,n,r=e.c,o=e.e,s=e.s;if(!Yn(r))return null===r&&null===o&&(null===s||1===s||-1===s);if(1!==s&&-1!==s||o<-Kn||o>Kn||o!==Dn(o))return!1;if(0===r[0])return 0===o&&1===r.length;if((t=(o+1)%Hn)<1&&(t+=Hn),String(r[0]).length!==t)return!1;for(t=0;t<r.length;t++)if((n=r[t])<0||n>=qn||n!==Dn(n))return!1;return 0!==n},b.maximum=b.max=function(){return I(arguments,-1)},b.minimum=b.min=function(){return I(arguments,1)},b.random=function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return Dn(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var n,r,o,s,i,a=0,l=[],d=new b(c);if(e=null==e?u:jn(e,0,Kn),s=Fn(e/Hn),m)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(s*=2));a<s;)(i=131072*n[a]+(n[a+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),n[a]=r[0],n[a+1]=r[1]):(l.push(i%1e14),a+=2);a=s/2}else{if(!crypto.randomBytes)throw m=!1,Error(Mn+"crypto unavailable");for(n=crypto.randomBytes(s*=7);a<s;)(i=281474976710656*(31&n[a])+1099511627776*n[a+1]+4294967296*n[a+2]+16777216*n[a+3]+(n[a+4]<<16)+(n[a+5]<<8)+n[a+6])>=9e15?crypto.randomBytes(7).copy(n,a):(l.push(i%1e14),a+=7);a=s/7}if(!m)for(;a<s;)(i=t())<9e15&&(l[a++]=i%1e14);for(s=l[--a],e%=Hn,s&&e&&(i=$n[Hn-e],l[a]=Dn(s/i)*i);0===l[a];l.pop(),a--);if(a<0)l=[o=0];else{for(o=-1;0===l[0];l.splice(0,1),o-=Hn);for(a=1,i=l[0];i>=10;i/=10,a++);a<Hn&&(o-=Hn-a)}return d.e=o,d.c=l,d}}(),b.sum=function(){for(var e=0,t=new b(0);e<arguments.length;)t=t.plus(arguments[e++]);return t},r=function(){var e="0123456789";function t(e,t,n,r){for(var o,s,i=[0],a=0,c=e.length;a<c;){for(s=i.length;s--;i[s]*=t);for(i[0]+=r.indexOf(e.charAt(a++)),o=0;o<i.length;o++)i[o]>n-1&&(null==i[o+1]&&(i[o+1]=0),i[o+1]+=i[o]/n|0,i[o]%=n)}return i.reverse()}return function(r,o,s,i,a){var c,d,p,h,f,m,g,y,A=r.indexOf("."),v=u,T=l;for(A>=0&&(h=w,w=0,r=r.replace(".",""),m=(y=new b(o)).pow(r.length-A),w=h,y.c=t(er(Zn(m.c),m.e,"0"),10,s,e),y.e=y.c.length),p=h=(g=t(r,o,s,a?(c=S,e):(c=e,S))).length;0==g[--h];g.pop());if(!g[0])return c.charAt(0);if(A<0?--p:(m.c=g,m.e=p,m.s=i,g=(m=n(m,y,v,T,s)).c,f=m.r,p=m.e),A=g[d=p+v+1],h=s/2,f=f||d<0||null!=g[d+1],f=T<4?(null!=A||f)&&(0==T||T==(m.s<0?3:2)):A>h||A==h&&(4==T||f||6==T&&1&g[d-1]||T==(m.s<0?8:7)),d<1||!g[0])r=f?er(c.charAt(1),-v,c.charAt(0)):c.charAt(0);else{if(d<g.length&&(g.length=d),f)for(--s;++g[--d]>s;)g[d]=0,d||(++p,g=[1].concat(g));for(h=g.length;!g[--h];);for(A=0,r="";A<=h;r+=c.charAt(g[A++]));r=er(r,p,c.charAt(0))}return r}}(),n=function(){function e(e,t,n){var r,o,s,i,a=0,c=e.length,u=t%Xn,l=t/Xn|0;for(e=e.slice();c--;)a=((o=u*(s=e[c]%Xn)+(r=l*s+(i=e[c]/Xn|0)*u)%Xn*Xn+a)/n|0)+(r/Xn|0)+l*i,e[c]=o%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var o,s;if(n!=r)s=n>r?1:-1;else for(o=s=0;o<n;o++)if(e[o]!=t[o]){s=e[o]>t[o]?1:-1;break}return s}function n(e,t,n,r){for(var o=0;n--;)e[n]-=o,o=e[n]<t[n]?1:0,e[n]=o*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,o,s,i,a){var c,u,l,d,p,h,f,m,g,y,w,A,S,v,T,E,k,I=r.s==o.s?1:-1,C=r.c,B=o.c;if(!(C&&C[0]&&B&&B[0]))return new b(r.s&&o.s&&(C?!B||C[0]!=B[0]:B)?C&&0==C[0]||!B?0*I:I/0:NaN);for(g=(m=new b(I)).c=[],I=s+(u=r.e-o.e)+1,a||(a=qn,u=Wn(r.e/Hn)-Wn(o.e/Hn),I=I/Hn|0),l=0;B[l]==(C[l]||0);l++);if(B[l]>(C[l]||0)&&u--,I<0)g.push(1),d=!0;else{for(v=C.length,E=B.length,l=0,I+=2,(p=Dn(a/(B[0]+1)))>1&&(B=e(B,p,a),C=e(C,p,a),E=B.length,v=C.length),S=E,w=(y=C.slice(0,E)).length;w<E;y[w++]=0);k=B.slice(),k=[0].concat(k),T=B[0],B[1]>=a/2&&T++;do{if(p=0,(c=t(B,y,E,w))<0){if(A=y[0],E!=w&&(A=A*a+(y[1]||0)),(p=Dn(A/T))>1)for(p>=a&&(p=a-1),f=(h=e(B,p,a)).length,w=y.length;1==t(h,y,f,w);)p--,n(h,E<f?k:B,f,a),f=h.length,c=1;else 0==p&&(c=p=1),f=(h=B.slice()).length;if(f<w&&(h=[0].concat(h)),n(y,h,w,a),w=y.length,-1==c)for(;t(B,y,E,w)<1;)p++,n(y,E<w?k:B,w,a),w=y.length}else 0===c&&(p++,y=[0]);g[l++]=p,y[0]?y[w++]=C[S]||0:(y=[C[S]],w=1)}while((S++<v||null!=y[0])&&I--);d=null!=y[0],g[0]||g.splice(0,1)}if(a==qn){for(l=1,I=g[0];I>=10;I/=10,l++);x(m,s+(m.e=l+u*Hn-1)+1,i,d)}else m.e=u,m.r=+d;return m}}(),a.absoluteValue=a.abs=function(){var e=new b(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return zn(this,new b(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,o,s=this;if(null!=e)return x(new b(s),jn(e,-Kn,Kn)+s.e+1,null==t?l:jn(t,0,8));if(!(n=s.c))return null;if(r=((o=n.length-1)-Wn(this.e/Hn))*Hn,o=n[o])for(;o%10==0;o/=10,r--);return r<0&&(r=0),r},a.dividedBy=a.div=function(e,t){return n(this,new b(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new b(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,o,s,i,a,u,d,p=this;if((e=new b(e)).c&&!e.isInteger())throw Error(Mn+"Exponent not an integer: "+R(e));if(null!=t&&(t=new b(t)),i=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return d=new b(Math.pow(+R(p),i?e.s*(2-Jn(e)):+R(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new b(NaN);(r=!a&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||i&&p.c[1]>=24e7:p.c[0]<8e13||i&&p.c[0]<=9999975e7)))return s=p.s<0&&Jn(e)?-0:0,p.e>-1&&(s=1/s),new b(a?1/s:s);w&&(s=Fn(w/Hn+2))}for(i?(n=new b(.5),a&&(e.s=1),u=Jn(e)):u=(o=Math.abs(+R(e)))%2,d=new b(c);;){if(u){if(!(d=d.times(p)).c)break;s?d.c.length>s&&(d.c.length=s):r&&(d=d.mod(t))}if(o){if(0===(o=Dn(o/2)))break;u=o%2}else if(x(e=e.times(n),e.e+1,1),e.e>14)u=Jn(e);else{if(0===(o=+R(e)))break;u=o%2}p=p.times(p),s?p.c&&p.c.length>s&&(p.c.length=s):r&&(p=p.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):s?x(d,w,l,void 0):d)},a.integerValue=function(e){var t=new b(this);return x(t,t.e+1,null==e?l:jn(e,0,8))},a.isEqualTo=a.eq=function(e,t){return 0===zn(this,new b(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return zn(this,new b(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=zn(this,new b(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Wn(this.e/Hn)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return zn(this,new b(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=zn(this,new b(e,t)))||0===t},a.isNaN=function(){return!this.s},a.isNegative=function(){return this.s<0},a.isPositive=function(){return this.s>0},a.isZero=function(){return!!this.c&&0==this.c[0]},a.minus=function(e,t){var n,r,o,s,i=this,a=i.s;if(t=(e=new b(e,t)).s,!a||!t)return new b(NaN);if(a!=t)return e.s=-t,i.plus(e);var c=i.e/Hn,u=e.e/Hn,d=i.c,p=e.c;if(!c||!u){if(!d||!p)return d?(e.s=-t,e):new b(p?i:NaN);if(!d[0]||!p[0])return p[0]?(e.s=-t,e):new b(d[0]?i:3==l?-0:0)}if(c=Wn(c),u=Wn(u),d=d.slice(),a=c-u){for((s=a<0)?(a=-a,o=d):(u=c,o=p),o.reverse(),t=a;t--;o.push(0));o.reverse()}else for(r=(s=(a=d.length)<(t=p.length))?a:t,a=t=0;t<r;t++)if(d[t]!=p[t]){s=d[t]<p[t];break}if(s&&(o=d,d=p,p=o,e.s=-e.s),(t=(r=p.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=qn-1;r>a;){if(d[--r]<p[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=qn}d[r]-=p[r]}for(;0==d[0];d.splice(0,1),--u);return d[0]?C(e,d,u):(e.s=3==l?-1:1,e.c=[e.e=0],e)},a.modulo=a.mod=function(e,t){var r,o,s=this;return e=new b(e,t),!s.c||!e.s||e.c&&!e.c[0]?new b(NaN):!e.c||s.c&&!s.c[0]?new b(s):(9==y?(o=e.s,e.s=1,r=n(s,e,0,3),e.s=o,r.s*=o):r=n(s,e,0,y),(e=s.minus(r.times(e))).c[0]||1!=y||(e.s=s.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,o,s,i,a,c,u,l,d,p,h,f,m,g,y=this,w=y.c,A=(e=new b(e,t)).c;if(!(w&&A&&w[0]&&A[0]))return!y.s||!e.s||w&&!w[0]&&!A||A&&!A[0]&&!w?e.c=e.e=e.s=null:(e.s*=y.s,w&&A?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Wn(y.e/Hn)+Wn(e.e/Hn),e.s*=y.s,(c=w.length)<(d=A.length)&&(f=w,w=A,A=f,o=c,c=d,d=o),o=c+d,f=[];o--;f.push(0));for(m=qn,g=Xn,o=d;--o>=0;){for(n=0,p=A[o]%g,h=A[o]/g|0,s=o+(i=c);s>o;)n=((u=p*(u=w[--i]%g)+(a=h*u+(l=w[i]/g|0)*p)%g*g+f[s]+n)/m|0)+(a/g|0)+h*l,f[s--]=u%m;f[s]=n}return n?++r:f.splice(0,1),C(e,f,r)},a.negated=function(){var e=new b(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,o=r.s;if(t=(e=new b(e,t)).s,!o||!t)return new b(NaN);if(o!=t)return e.s=-t,r.minus(e);var s=r.e/Hn,i=e.e/Hn,a=r.c,c=e.c;if(!s||!i){if(!a||!c)return new b(o/0);if(!a[0]||!c[0])return c[0]?e:new b(a[0]?r:0*o)}if(s=Wn(s),i=Wn(i),a=a.slice(),o=s-i){for(o>0?(i=s,n=c):(o=-o,n=a),n.reverse();o--;n.push(0));n.reverse()}for((o=a.length)-(t=c.length)<0&&(n=c,c=a,a=n,t=o),o=0;t;)o=(a[--t]=a[t]+c[t]+o)/qn|0,a[t]=qn===a[t]?0:a[t]%qn;return o&&(a=[o].concat(a),++i),C(e,a,i)},a.precision=a.sd=function(e,t){var n,r,o,s=this;if(null!=e&&e!==!!e)return x(new b(s),jn(e,1,Kn),null==t?l:jn(t,0,8));if(!(n=s.c))return null;if(r=(o=n.length-1)*Hn+1,o=n[o]){for(;o%10==0;o/=10,r--);for(o=n[0];o>=10;o/=10,r++);}return e&&s.e+1>r&&(r=s.e+1),r},a.shiftedBy=function(e){return this.times("1e"+jn(e,-Gn,Gn))},a.squareRoot=a.sqrt=function(){var e,t,r,o,s,i=this,a=i.c,c=i.s,d=i.e,p=u+4,h=new b("0.5");if(1!==c||!a||!a[0])return new b(!c||c<0&&(!a||a[0])?NaN:a?i:1/0);if(0==(c=Math.sqrt(+R(i)))||c==1/0?(((t=Zn(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Wn((d+1)/2)-(d<0||d%2),r=new b(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new b(c+""),r.c[0])for((c=(d=r.e)+p)<3&&(c=0);;)if(s=r,r=h.times(s.plus(n(i,s,p,1))),Zn(s.c).slice(0,c)===(t=Zn(r.c)).slice(0,c)){if(r.e<d&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(o||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(x(r,r.e+u+2,1),e=!r.times(r).eq(i));break}if(!o&&(x(s,s.e+u+2,0),s.times(s).eq(i))){r=s;break}p+=4,c+=4,o=1}return x(r,r.e+u+1,l,e)},"function"==typeof BigInt&&(a.toBigInt=function(e){var t=this;return t.c?BigInt(E(t,t.e+1,e)):null});a.toExponential=function(e,t){return E(this,null==e?e:jn(e,0,Kn)+1,t,1)},a.toFixed=function(e,t){return E(this,null==e?e:jn(e,-Kn,Kn)+this.e+1,t)},a.toFormat=function(e,t,n){var r,o,s,i=this;if(null==n)n=A,null!=e&&(null!=t?"object"==typeof t&&(n=B(t),t=null):"object"!=typeof e||Yn(e)||(n=B(e),e=t=null));else{if("object"!=typeof n)throw Error(Mn+"Argument not an object: "+n);n=B(n)}if(null!=e)if(Yn(e)&&e.length<=2){if(r=e[0],o=e[1],e=i.dp(),null!=o&&e>jn(o,0,Kn)&&(e=o),null!=r&&0!==jn(r,0,Kn)){if(null!=o&&r>o)throw Error(Mn+"Minimum must not exceed maximum");e<r&&(e=r)}}else jn(e,-Kn,Kn);if(s=i.toFixed(e,t),i.s<0&&(s=s.slice(1)),i.c){var a,c=s.split("."),u=+n.groupSize,l=+n.secondaryGroupSize,d=n.groupSeparator||"",p=c[0],h=c[1],f=p.length;if(l&&(a=u,u=l,l=a,f-=a),u>0&&f>0){for(a=f%u||u,s=p.substr(0,a);a<f;a+=u)s+=d+p.substr(a,u);l>0&&(s+=d+p.slice(a))}h&&((a=+n.fractionGroupSize)&&(h=h.replace(new RegExp("\\d{"+a+"}\\B","g"),"$&"+(n.fractionGroupSeparator||""))),s+=(n.decimalSeparator||"")+h)}return(n.prefix||"")+(i.s<0?n.negativeSign||"":i.s>0&&n.positiveSign||"")+s+(n.suffix||"")},a.toFraction=function(e){var t,r,o,s,i,a,u,d,p,h,m,g,y=this,w=y.c;if(null!=e&&(!(u=new b(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(Mn+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+R(u));if(!w)return[new b(y.s||0),new b(0)];for(t=new b(c),p=r=new b(c),o=d=new b(c),g=Zn(w),i=t.e=g.length-y.e-1,t.c[0]=$n[(a=i%Hn)<0?Hn+a:a],e=!e||u.comparedTo(t)>0?i>0?t:p:u,a=f,f=1/0,u=new b(g),d.c[0]=0;h=n(u,t,0,1),1!=(s=r.plus(h.times(o))).comparedTo(e);)r=o,o=s,p=d.plus(h.times(s=p)),d=s,t=u.minus(h.times(s=t)),u=s;return s=n(e.minus(r),o,0,1),d=d.plus(s.times(p)),r=r.plus(s.times(o)),d.s=p.s=y.s,m=n(p,o,i*=2,l).minus(y).abs().comparedTo(n(d,r,i,l).minus(y).abs())<1?[p,o]:[d,r],f=a,m},a.toNumber=function(){return+R(this)},a.toObject=function(){var e=this;return{c:e.c?e.c.slice():null,e:e.e,s:e.s}},a.toPrecision=function(e,t){return E(this,null==e?e:jn(e,1,Kn),t,2)},a.toString=function(e){var t,n=this,o=n.s,s=n.e;return null===s?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=s<=d||s>=p?Qn(Zn(n.c),s):er(Zn(n.c),s,"0"):(jn(e,2,S.length,"Base"),t=r(er(Zn(n.c),s,"0"),10,e,o,!0)),o<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return R(this)},a._isBigNumber=!0,null!=t&&b.set(t);return b}(),Vn=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Fn=Math.ceil,Dn=Math.floor,Mn="[BigNumber Error] ",qn=1e14,Hn=14,Gn=9007199254740991,$n=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Xn=1e7,Kn=1e9;function Wn(e){var t=0|e;return e>0||e===t?t:t-1}function Zn(e){for(var t,n,r=1,o=e.length,s=e[0]+"";r<o;){for(t=e[r++]+"",n=Hn-t.length;n--;t="0"+t);s+=t}for(o=s.length;48===s.charCodeAt(--o););return s.slice(0,o+1||1)}function zn(e,t){var n,r,o=e.c,s=t.c,i=e.s,a=t.s,c=e.e,u=t.e;if(!i||!a)return null;if(n=o&&!o[0],r=s&&!s[0],n||r)return n?r?0:-a:i;if(i!=a)return i;if(n=i<0,r=c==u,!o||!s)return r?0:!o^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=o.length)<(u=s.length)?c:u,i=0;i<a;i++)if(o[i]!=s[i])return o[i]>s[i]^n?1:-1;return c==u?0:c>u^n?1:-1}function jn(e,t,n,r){if(e<t||e>n||e!==Dn(e))throw Error(Mn+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e));return e}function Yn(e){return"[object Array]"=={}.toString.call(e)}function Jn(e){var t=e.c.length-1;return Wn(e.e/Hn)==t&&e.c[t]%2!=0}function Qn(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function er(e,t,n){var r,o;if(t<0){for(o=n+".";++t;o+=n);e=o+e}else if(++t>(r=e.length)){for(o=n,t-=r;--t;o+=n);e+=o}else t<r&&(e=e.slice(0,t)+"."+e.slice(t));return e}const tr=Nn.clone({STRICT:!0}),nr=2147483647,rr=new tr(nr);const or=1e7;function sr(e,t){if(t.source)try{e.sourceAccount=Pn(t.source)}catch{throw new Error("Source address is invalid")}}function ir(e,t,n=null){if(void 0===t)return;const r="string"==typeof t?""===t.trim()?NaN:Number(t):t;if("number"!=typeof r||!Number.isFinite(r)||r%1!=0)throw new Error(`${e} value is invalid`);if(r<0)throw new Error(`${e} value must be unsigned`);if(!n||n(r,e))return r;throw new Error(`${e} value is invalid`)}function ar(e){const t=new tr(e).times(or);return se.Int64.fromString(t.toString())}function cr(e){return new tr(e.toString()).div(or).toFixed(7)}function ur(e){return new tr(e.n()).div(new tr(e.d())).toString()}function lr(e){let t;if("object"==typeof e&&"n"in e&&"d"in e)t=new se.Price(e);else{const n=new tr(e);if(!n.gt(0)||!n.isFinite())throw new Error("price must be positive");const r=function(e){let t,n,r=new tr(e);const o=[[new tr(0),new tr(1)],[new tr(1),new tr(0)]];let s=2;for(;!r.gt(nr);){t=r.integerValue(tr.ROUND_FLOOR),n=r.minus(t);const e=o[s-1],i=o[s-2];if(!e||!i)throw new Error(`Continued fraction approximation failed: missing fraction elements at indices ${s-1} and/or ${s-2}`);const a=t.times(e[0]).plus(i[0]),c=t.times(e[1]).plus(i[1]);if(a.gt(nr)||c.gt(nr))break;if(o.push([a,c]),n.eq(0))break;r=new tr(1).div(n),s+=1}const i=o[o.length-1];if(!i)throw new Error("Missing last fraction element in continued fraction approximation");const[a,c]=i;if(a.isZero()||c.isZero()){if(new tr(e).isZero())throw new Error("Couldn't find approximation");const t=o[o.length-1],n=o[o.length-2];if(t&&n){let e=rr;if(t[0].gt(0)&&(e=tr.min(e,rr.minus(n[0]).div(t[0]).integerValue(tr.ROUND_FLOOR))),t[1].gt(0)&&(e=tr.min(e,rr.minus(n[1]).div(t[1]).integerValue(tr.ROUND_FLOOR))),e.gte(1)){const r=e.times(t[0]).plus(n[0]),o=e.times(t[1]).plus(n[1]);if(!r.isZero()&&!o.isZero())return[r.toNumber(),o.toNumber()]}}throw new Error("Couldn't find approximation")}return[a.toNumber(),c.toNumber()]}(e);t=new se.Price({n:parseInt(String(r[0]),10),d:parseInt(String(r[1]),10)})}if(t.n()<0||t.d()<=0)throw new Error("price must be positive");return t}function dr(e,t=!1){if("string"!=typeof e)return!1;let n;try{n=new tr(e)}catch{return!1}return!(!t&&n.isZero()||n.isNegative()||n.times(or).gt(new tr("9223372036854775807").toString())||(n.decimalPlaces()??0)>7||n.isNaN()||!n.isFinite())}function pr(e){return`${e} argument must be of type String, represent a positive number and have at most 7 digits after the decimal`}function hr(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.amount,!0))throw new TypeError(pr("amount"));const r=ar(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=void 0!==e.offerId?e.offerId.toString():"0",i=se.Int64.fromString(s),a=new se.ManageSellOfferOp({selling:t,buying:n,amount:r,price:o,offerId:i}),c={sourceAccount:null,body:se.OperationBody.manageSellOffer(a)};return sr(c,e),new se.Operation(c)}function fr(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.amount))throw new TypeError(pr("amount"));const r=ar(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=new se.CreatePassiveSellOfferOp({selling:t,buying:n,amount:r,price:o}),i={sourceAccount:null,body:se.OperationBody.createPassiveSellOffer(s)};return sr(i,e),new se.Operation(i)}function mr(e){let t;try{t=se.OperationBody.accountMerge(Pn(e.destination))}catch{throw new Error("destination is invalid")}const n={sourceAccount:null,body:t};return sr(n,e),new se.Operation(n)}function gr(e){if(!wn.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");const t=Tn.fromPublicKey(e.trustor).xdrAccountId();let n,r;if(e.assetCode.length<=4){const t=fe.Buffer.from(e.assetCode.padEnd(4,"\0"));n=se.AssetCode.assetTypeCreditAlphanum4(t)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");{const t=fe.Buffer.from(e.assetCode.padEnd(12,"\0"));n=se.AssetCode.assetTypeCreditAlphanum12(t)}}if("boolean"==typeof e.authorize)r=e.authorize?se.TrustLineFlags.authorizedFlag().value:0;else{if(null==e.authorize)throw new Error("authorize is required");r=e.authorize}const o=new se.AllowTrustOp({trustor:t,asset:n,authorize:r}),s={sourceAccount:null,body:se.OperationBody.allowTrust(o)};return sr(s,e),new se.Operation(s)}function yr(e){if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new tr(e.bumpTo)}catch{throw new Error("bumpTo must be a stringified number")}const t=se.Int64.fromString(e.bumpTo),n=new se.BumpSequenceOp({bumpTo:t}),r={sourceAccount:null,body:se.OperationBody.bumpSequence(n)};return sr(r,e),new se.Operation(r)}function wr(e){const t=e.asset??e.line;let n;if(t instanceof In)n=t.toChangeTrustXDRObject();else{if(!(t instanceof xn))throw new TypeError("asset must be Asset or LiquidityPoolAsset");n=t.toXDRObject()}if(void 0!==e.limit&&!dr(e.limit,!0))throw new TypeError(pr("limit"));const r=e.limit?ar(e.limit):se.Int64.fromString("9223372036854775807"),o=new se.ChangeTrustOp({line:n,limit:r}),s={sourceAccount:null,body:se.OperationBody.changeTrust(o)};return sr(s,e),new se.Operation(s)}function Ar(e){if(!wn.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!dr(e.startingBalance,!0))throw new TypeError(pr("startingBalance"));const t=new se.CreateAccountOp({destination:Tn.fromPublicKey(e.destination).xdrAccountId(),startingBalance:ar(e.startingBalance)}),n={sourceAccount:null,body:se.OperationBody.createAccount(t)};return sr(n,e),new se.Operation(n)}function Sr(e){if(!(e.asset instanceof In))throw new Error("must provide an asset for create claimable balance operation");if(!dr(e.amount))throw new TypeError(pr("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");const t=e.asset.toXDRObject(),n=ar(e.amount),r=e.claimants.map(e=>e.toXDRObject()),o=new se.CreateClaimableBalanceOp({asset:t,amount:n,claimants:r}),s={sourceAccount:null,body:se.OperationBody.createClaimableBalance(o)};return sr(s,e),new se.Operation(s)}function br(e={}){vr(e.balanceId);const t=se.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n=new se.ClaimClaimableBalanceOp({balanceId:t}),r={sourceAccount:null,body:se.OperationBody.claimClaimableBalance(n)};return sr(r,e),new se.Operation(r)}function vr(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}function Tr(e={}){vr(e.balanceId);const t=se.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n={sourceAccount:null,body:se.OperationBody.clawbackClaimableBalance(new se.ClawbackClaimableBalanceOp({balanceId:t}))};return sr(n,e),new se.Operation(n)}function Er(e={}){const t={sourceAccount:null,body:se.OperationBody.inflation()};return sr(t,e),new se.Operation(t)}function kr(e){if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if("string"!=typeof e.value&&!fe.Buffer.isBuffer(e.value)&&null!==e.value&&void 0!==e.value)throw new Error("value must be a string, Buffer or null");let t;if(t="string"==typeof e.value?fe.Buffer.from(e.value):e.value??null,null!==t&&t.length>64)throw new Error("value cannot be longer that 64 bytes");const n=new se.ManageDataOp({dataName:e.name,dataValue:t}),r={sourceAccount:null,body:se.OperationBody.manageData(n)};return sr(r,e),new se.Operation(r)}function Ir(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!dr(e.buyAmount,!0))throw new TypeError(pr("buyAmount"));const r=ar(e.buyAmount);if(void 0===e.price)throw new TypeError("price argument is required");const o=lr(e.price),s=void 0!==e.offerId?e.offerId.toString():"0",i=se.Int64.fromString(s),a=new se.ManageBuyOfferOp({selling:t,buying:n,buyAmount:r,price:o,offerId:i}),c={sourceAccount:null,body:se.OperationBody.manageBuyOffer(a)};return sr(c,e),new se.Operation(c)}function Cr(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!dr(e.sendMax))throw new TypeError(pr("sendMax"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!dr(e.destAmount))throw new TypeError(pr("destAmount"));let t;try{t=Pn(e.destination)}catch{throw new Error("destination is invalid")}const n=e.path?e.path:[],r=new se.PathPaymentStrictReceiveOp({sendAsset:e.sendAsset.toXDRObject(),sendMax:ar(e.sendMax),destination:t,destAsset:e.destAsset.toXDRObject(),destAmount:ar(e.destAmount),path:n.map(e=>e.toXDRObject())}),o={sourceAccount:null,body:se.OperationBody.pathPaymentStrictReceive(r)};return sr(o,e),new se.Operation(o)}function Br(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!dr(e.sendAmount))throw new TypeError(pr("sendAmount"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!dr(e.destMin))throw new TypeError(pr("destMin"));const t=e.sendAsset.toXDRObject(),n=ar(e.sendAmount);let r;try{r=Pn(e.destination)}catch{throw new Error("destination is invalid")}const o=e.destAsset.toXDRObject(),s=ar(e.destMin),i=(e.path??[]).map(e=>e.toXDRObject()),a=new se.PathPaymentStrictSendOp({sendAsset:t,sendAmount:n,destination:r,destAsset:o,destMin:s,path:i}),c={sourceAccount:null,body:se.OperationBody.pathPaymentStrictSend(a)};return sr(c,e),new se.Operation(c)}function xr(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!dr(e.amount))throw new TypeError(pr("amount"));let t;try{t=Pn(e.destination)}catch{throw new Error("destination is invalid")}const n=new se.PaymentOp({destination:t,asset:e.asset.toXDRObject(),amount:ar(e.amount)}),r={sourceAccount:null,body:se.OperationBody.payment(n)};return sr(r,e),new se.Operation(r)}function Rr(e,t){if(e>=0&&e<=255)return!0;throw new Error(`${t} value must be between 0 and 255`)}function _r(e){let t=null;if(e.inflationDest){if(!wn.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t=Tn.fromPublicKey(e.inflationDest).xdrAccountId()}const n=ir("clearFlags",e.clearFlags)??null,r=ir("setFlags",e.setFlags)??null,o=ir("masterWeight",e.masterWeight,Rr)??null,s=ir("lowThreshold",e.lowThreshold,Rr)??null,i=ir("medThreshold",e.medThreshold,Rr)??null,a=ir("highThreshold",e.highThreshold,Rr)??null;if(void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");const c=e.homeDomain;let u=null;if(e.signer){const t=ir("signer.weight",e.signer.weight,Rr);let n,r=0;if(e.signer.ed25519PublicKey){if(!wn.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const t=wn.decodeEd25519PublicKey(e.signer.ed25519PublicKey);n=se.SignerKey.signerKeyTypeEd25519(t),r+=1}if(e.signer.preAuthTx){let t;if(t="string"==typeof e.signer.preAuthTx?fe.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!fe.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");n=se.SignerKey.signerKeyTypePreAuthTx(t),r+=1}if(e.signer.sha256Hash){let t;if(t="string"==typeof e.signer.sha256Hash?fe.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!fe.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");n=se.SignerKey.signerKeyTypeHashX(t),r+=1}if(e.signer.ed25519SignedPayload){if(!wn.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const t=wn.decodeSignedPayload(e.signer.ed25519SignedPayload),o=se.SignerKeyEd25519SignedPayload.fromXDR(t);n=se.SignerKey.signerKeyTypeEd25519SignedPayload(o),r+=1}if(1!==r)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx, or signer.ed25519SignedPayload.");if(void 0===t)throw new Error("signer weight is required.");if(void 0===n)throw new Error("signer key is required.");u=new se.Signer({key:n,weight:t})}const l=new se.SetOptionsOp({inflationDest:t,clearFlags:n,setFlags:r,masterWeight:o,lowThreshold:s,medThreshold:i,highThreshold:a,homeDomain:c,signer:u}),d={sourceAccount:null,body:se.OperationBody.setOptions(l)};return sr(d,e),new se.Operation(d)}function Pr(e){if(!wn.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");const t=new se.BeginSponsoringFutureReservesOp({sponsoredId:Tn.fromPublicKey(e.sponsoredId).xdrAccountId()}),n={sourceAccount:null,body:se.OperationBody.beginSponsoringFutureReserves(t)};return sr(n,e),new se.Operation(n)}function Or(e={}){const t={sourceAccount:null,body:se.OperationBody.endSponsoringFutureReserves()};return sr(t,e),new se.Operation(t)}function Ur(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");const t=se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e.account).xdrAccountId()})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Lr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.asset instanceof In)t=e.asset.toTrustLineXDRObject();else{if(!(e.asset instanceof _n))throw new TypeError("asset must be an Asset or LiquidityPoolId");t=e.asset.toXDRObject()}const n=se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),asset:t})),r=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(n),o={sourceAccount:null,body:se.OperationBody.revokeSponsorship(r)};return sr(o,e),new se.Operation(o)}function Nr(e={}){if(!wn.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");const t=se.LedgerKey.offer(new se.LedgerKeyOffer({sellerId:Tn.fromPublicKey(e.seller).xdrAccountId(),offerId:se.Int64.fromString(e.offerId)})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Vr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");const t=se.LedgerKey.data(new se.LedgerKeyData({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Fr(e={}){if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");const t=se.LedgerKey.claimableBalance(new se.LedgerKeyClaimableBalance({balanceId:se.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Dr(e={}){if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");const t=se.LedgerKey.liquidityPool(new se.LedgerKeyLiquidityPool({liquidityPoolId:fe.Buffer.from(e.liquidityPoolId,"hex")})),n=se.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:se.OperationBody.revokeSponsorship(n)};return sr(r,e),new se.Operation(r)}function Mr(e={}){if(!wn.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.signer.ed25519PublicKey){if(!wn.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const n=wn.decodeEd25519PublicKey(e.signer.ed25519PublicKey);t=se.SignerKey.signerKeyTypeEd25519(n)}else if(e.signer.preAuthTx){let n;if(n="string"==typeof e.signer.preAuthTx?fe.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!fe.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");t=se.SignerKey.signerKeyTypePreAuthTx(n)}else if(e.signer.sha256Hash){let n;if(n="string"==typeof e.signer.sha256Hash?fe.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!fe.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");t=se.SignerKey.signerKeyTypeHashX(n)}else{if(!e.signer.ed25519SignedPayload)throw new Error("signer is invalid");{if(!wn.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const n=wn.decodeSignedPayload(e.signer.ed25519SignedPayload),r=se.SignerKeyEd25519SignedPayload.fromXDR(n);t=se.SignerKey.signerKeyTypeEd25519SignedPayload(r)}}const n=new se.RevokeSponsorshipOpSigner({accountId:Tn.fromPublicKey(e.account).xdrAccountId(),signerKey:t}),r=se.RevokeSponsorshipOp.revokeSponsorshipSigner(n),o={sourceAccount:null,body:se.OperationBody.revokeSponsorship(r)};return sr(o,e),new se.Operation(o)}function qr(e){if(!dr(e.amount))throw new TypeError(pr("amount"));let t;try{t=Pn(e.from)}catch{throw new Error("from address is invalid")}const n=new se.ClawbackOp({amount:ar(e.amount),asset:e.asset.toXDRObject(),from:t}),r={sourceAccount:null,body:se.OperationBody.clawback(n)};return sr(r,e),new se.Operation(r)}function Hr(e){if("object"!=typeof e.flags||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");const t={authorized:se.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:se.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:se.TrustLineFlags.trustlineClawbackEnabledFlag()};let n=0,r=0;Object.keys(e.flags).forEach(o=>{if(!Object.prototype.hasOwnProperty.call(t,o))throw new Error(`unsupported flag name specified: ${o}`);const s=e.flags[o],i=t[o];if(!i)throw new Error(`Invalid flag name: ${o}`);if("boolean"!=typeof s&&void 0!==s)throw new TypeError(`opts.flags.${o} must be a boolean (got ${typeof s})`);!0===s?r|=i.value:!1===s&&(n|=i.value)});const o=Tn.fromPublicKey(e.trustor).xdrAccountId(),s=e.asset.toXDRObject(),i={sourceAccount:null,body:se.OperationBody.setTrustLineFlags(new se.SetTrustLineFlagsOp({trustor:o,asset:s,clearFlags:n,setFlags:r}))};return sr(i,e),new se.Operation(i)}function Gr(e={}){const{liquidityPoolId:t,maxAmountA:n,maxAmountB:r,minPrice:o,maxPrice:s}=e;if(!t)throw new TypeError("liquidityPoolId argument is required");const i=fe.Buffer.from(t,"hex");if(!dr(n,!0))throw new TypeError(pr("maxAmountA"));const a=ar(n);if(!dr(r,!0))throw new TypeError(pr("maxAmountB"));const c=ar(r);if(void 0===o)throw new TypeError("minPrice argument is required");const u=lr(o);if(void 0===s)throw new TypeError("maxPrice argument is required");const l=lr(s),d=new se.LiquidityPoolDepositOp({liquidityPoolId:i,maxAmountA:a,maxAmountB:c,minPrice:u,maxPrice:l}),p={sourceAccount:null,body:se.OperationBody.liquidityPoolDeposit(d)};return sr(p,e),new se.Operation(p)}function $r(e={}){if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");const t=fe.Buffer.from(e.liquidityPoolId,"hex");if(!dr(e.amount))throw new TypeError(pr("amount"));const n=ar(e.amount);if(!dr(e.minAmountA,!0))throw new TypeError(pr("minAmountA"));const r=ar(e.minAmountA);if(!dr(e.minAmountB,!0))throw new TypeError(pr("minAmountB"));const o=ar(e.minAmountB),s=new se.LiquidityPoolWithdrawOp({liquidityPoolId:t,amount:n,minAmountA:r,minAmountB:o}),i={sourceAccount:null,body:se.OperationBody.liquidityPoolWithdraw(s)};return sr(i,e),new se.Operation(i)}class Xr{_type;_key;constructor(e){if(wn.isValidEd25519PublicKey(e))this._type="account",this._key=wn.decodeEd25519PublicKey(e);else if(wn.isValidContract(e))this._type="contract",this._key=wn.decodeContract(e);else if(wn.isValidMed25519PublicKey(e))this._type="muxedAccount",this._key=wn.decodeMed25519PublicKey(e);else if(wn.isValidClaimableBalance(e))this._type="claimableBalance",this._key=wn.decodeClaimableBalance(e);else{if(!wn.isValidLiquidityPool(e))throw new Error(`Unsupported address type: ${e}`);this._type="liquidityPool",this._key=wn.decodeLiquidityPool(e)}}static fromString(e){return new Xr(e)}static account(e){return new Xr(wn.encodeEd25519PublicKey(e))}static contract(e){return new Xr(wn.encodeContract(e))}static claimableBalance(e){return new Xr(wn.encodeClaimableBalance(e))}static liquidityPool(e){return new Xr(wn.encodeLiquidityPool(e))}static muxedAccount(e){return new Xr(wn.encodeMed25519PublicKey(e))}static fromScVal(e){return Xr.fromScAddress(e.address())}static fromScAddress(e){switch(e.switch().value){case se.ScAddressType.scAddressTypeAccount().value:return Xr.account(e.accountId().ed25519());case se.ScAddressType.scAddressTypeContract().value:return Xr.contract(e.contractId());case se.ScAddressType.scAddressTypeMuxedAccount().value:{const t=fe.Buffer.concat([e.muxedAccount().ed25519(),e.muxedAccount().id().toXDR("raw")]);return Xr.muxedAccount(t)}case se.ScAddressType.scAddressTypeClaimableBalance().value:{const t=e.claimableBalanceId();return Xr.claimableBalance(fe.Buffer.concat([fe.Buffer.from([t.switch().value]),t.v0()]))}case se.ScAddressType.scAddressTypeLiquidityPool().value:return Xr.liquidityPool(e.liquidityPoolId());default:throw new Error(`Unsupported address type: ${e.switch().name}`)}}toString(){switch(this._type){case"account":return wn.encodeEd25519PublicKey(this._key);case"contract":return wn.encodeContract(this._key);case"claimableBalance":return wn.encodeClaimableBalance(this._key);case"liquidityPool":return wn.encodeLiquidityPool(this._key);case"muxedAccount":return wn.encodeMed25519PublicKey(this._key);default:throw new Error("Unsupported address type")}}toScVal(){return se.ScVal.scvAddress(this.toScAddress())}toScAddress(){switch(this._type){case"account":return se.ScAddress.scAddressTypeAccount(se.PublicKey.publicKeyTypeEd25519(this._key));case"contract":return se.ScAddress.scAddressTypeContract(this._key);case"liquidityPool":return se.ScAddress.scAddressTypeLiquidityPool(this._key);case"claimableBalance":return se.ScAddress.scAddressTypeClaimableBalance(se.ClaimableBalanceId.claimableBalanceIdTypeV0(this._key.subarray(1)));case"muxedAccount":return se.ScAddress.scAddressTypeMuxedAccount(new se.MuxedEd25519Account({ed25519:this._key.subarray(0,32),id:se.Uint64.fromXDR(this._key.subarray(32,40),"raw")}));default:throw new Error("Unsupported address type")}}toBuffer(){return this._key}get type(){return this._type}}function Kr(e){if(!e.func)throw new TypeError(`host function invocation ('func') required (got ${JSON.stringify(e)})`);e.func.switch().value===se.HostFunctionType.hostFunctionTypeInvokeContract().value&&e.func.invokeContract().args().forEach(e=>{let t;try{t=Xr.fromScVal(e)}catch{return}switch(t.type){case"claimableBalance":case"liquidityPool":throw new TypeError("claimable balances and liquidity pools cannot be arguments to invokeHostFunction")}});const t=new se.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),n={sourceAccount:null,body:se.OperationBody.invokeHostFunction(t)};return sr(n,e),new se.Operation(n)}function Wr(e){const t=new Xr(e.contract);if("contract"!==t.type)throw new TypeError(`expected contract strkey instance, got ${t.toString()}`);return Kr({func:se.HostFunction.hostFunctionTypeInvokeContract(new se.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args})),...void 0!==e.source&&{source:e.source},...void 0!==e.auth&&{auth:e.auth}})}function Zr(e){const t=fe.Buffer.from(e.salt||Tn.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError(`expected hash(contract WASM) in 'opts.wasmHash', got ${String(e.wasmHash)}`);if(32!==t.length)throw new TypeError(`expected 32-byte salt in 'opts.salt', got ${String(e.salt)}`);return Kr({func:se.HostFunction.hostFunctionTypeCreateContractV2(new se.CreateContractArgsV2({executable:se.ContractExecutable.contractExecutableWasm(fe.Buffer.from(e.wasmHash)),contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAddress(new se.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:t})),constructorArgs:e.constructorArgs??[]})),...void 0!==e.source&&{source:e.source},...void 0!==e.auth&&{auth:e.auth}})}function zr(e){let t=e.asset;if("string"==typeof t){const n=t.split(":"),r=n[0];if(void 0===r)throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);t=new In(r,n[1])}if(!(t instanceof In))throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);return Kr({func:se.HostFunction.hostFunctionTypeCreateContract(new se.CreateContractArgs({executable:se.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:se.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())})),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function jr(e){return Kr({func:se.HostFunction.hostFunctionTypeUploadContractWasm(fe.Buffer.from(e.wasm)),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Yr(e){if((e.extendTo??-1)<=0)throw new RangeError("extendTo has to be positive");const t=new se.ExtendFootprintTtlOp({ext:new se.ExtensionPoint(0),extendTo:e.extendTo}),n={sourceAccount:null,body:se.OperationBody.extendFootprintTtl(t)};return sr(n,e),new se.Operation(n)}function Jr(e={}){const t=new se.RestoreFootprintOp({ext:new se.ExtensionPoint(0)}),n={sourceAccount:null,body:se.OperationBody.restoreFootprint(t)};return sr(n,e),new se.Operation(n)}class Qr{static fromXDRObject(e){const t={},n=e.sourceAccount();n&&(t.source=On(n));const r=e.body().value(),o=e.body().switch().name;switch(o){case"createAccount":t.type="createAccount",t.destination=eo(r.destination()),t.startingBalance=cr(r.startingBalance());break;case"payment":t.type="payment",t.destination=On(r.destination()),t.asset=In.fromOperation(r.asset()),t.amount=cr(r.amount());break;case"pathPaymentStrictReceive":{t.type="pathPaymentStrictReceive",t.sendAsset=In.fromOperation(r.sendAsset()),t.sendMax=cr(r.sendMax()),t.destination=On(r.destination()),t.destAsset=In.fromOperation(r.destAsset()),t.destAmount=cr(r.destAmount()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(In.fromOperation(e[n]))});break}case"pathPaymentStrictSend":{t.type="pathPaymentStrictSend",t.sendAsset=In.fromOperation(r.sendAsset()),t.sendAmount=cr(r.sendAmount()),t.destination=On(r.destination()),t.destAsset=In.fromOperation(r.destAsset()),t.destMin=cr(r.destMin()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(In.fromOperation(e[n]))});break}case"changeTrust":if(t.type="changeTrust",r.line().switch()===se.AssetType.assetTypePoolShare())t.line=xn.fromOperation(r.line());else t.line=In.fromOperation(r.line());t.limit=cr(r.limit());break;case"allowTrust":t.type="allowTrust",t.trustor=eo(r.trustor()),t.assetCode=r.asset().value().toString(),t.assetCode=ln(t.assetCode,"\0"),t.authorize=r.authorize();break;case"setOptions":if(t.type="setOptions",r.inflationDest()&&(t.inflationDest=eo(r.inflationDest())),t.clearFlags=r.clearFlags(),t.setFlags=r.setFlags(),t.masterWeight=r.masterWeight(),t.lowThreshold=r.lowThreshold(),t.medThreshold=r.medThreshold(),t.highThreshold=r.highThreshold(),t.homeDomain=void 0!==r.homeDomain()?r.homeDomain().toString("ascii"):void 0,r.signer()){const e={},n=r.signer().key().arm();if("ed25519"===n)e.ed25519PublicKey=eo(r.signer().key());else if("preAuthTx"===n)e.preAuthTx=r.signer().key().preAuthTx();else if("hashX"===n)e.sha256Hash=r.signer().key().hashX();else if("ed25519SignedPayload"===n){const t=r.signer().key().ed25519SignedPayload();e.ed25519SignedPayload=wn.encodeSignedPayload(t.toXDR())}e.weight=r.signer().weight(),t.signer=e}break;case"manageOffer":case"manageSellOffer":t.type="manageSellOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.amount=cr(r.amount()),t.price=ur(r.price()),t.offerId=r.offerId().toString();break;case"manageBuyOffer":t.type="manageBuyOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.buyAmount=cr(r.buyAmount()),t.price=ur(r.price()),t.offerId=r.offerId().toString();break;case"createPassiveOffer":case"createPassiveSellOffer":t.type="createPassiveSellOffer",t.selling=In.fromOperation(r.selling()),t.buying=In.fromOperation(r.buying()),t.amount=cr(r.amount()),t.price=ur(r.price());break;case"accountMerge":t.type="accountMerge",t.destination=On(r);break;case"manageData":t.type="manageData",t.name=r.dataName().toString("ascii"),t.value=r.dataValue();break;case"inflation":t.type="inflation";break;case"bumpSequence":t.type="bumpSequence",t.bumpTo=r.bumpTo().toString();break;case"createClaimableBalance":t.type="createClaimableBalance",t.asset=In.fromOperation(r.asset()),t.amount=cr(r.amount()),t.claimants=[],r.claimants().forEach(e=>{t.claimants.push(Rn.fromXDR(e))});break;case"claimClaimableBalance":t.type="claimClaimableBalance",t.balanceId=r.toXDR("hex");break;case"beginSponsoringFutureReserves":t.type="beginSponsoringFutureReserves",t.sponsoredId=eo(r.sponsoredId());break;case"endSponsoringFutureReserves":t.type="endSponsoringFutureReserves";break;case"revokeSponsorship":!function(e,t){switch(e.switch().name){case"revokeSponsorshipLedgerEntry":{const n=e.ledgerKey();switch(n.switch().name){case se.LedgerEntryType.account().name:t.type="revokeAccountSponsorship",t.account=eo(n.account().accountId());break;case se.LedgerEntryType.trustline().name:{t.type="revokeTrustlineSponsorship",t.account=eo(n.trustLine().accountId());const e=n.trustLine().asset();if(e.switch()===se.AssetType.assetTypePoolShare())t.asset=_n.fromOperation(e);else t.asset=In.fromOperation(e);break}case se.LedgerEntryType.offer().name:t.type="revokeOfferSponsorship",t.seller=eo(n.offer().sellerId()),t.offerId=n.offer().offerId().toString();break;case se.LedgerEntryType.data().name:t.type="revokeDataSponsorship",t.account=eo(n.data().accountId()),t.name=n.data().dataName().toString("ascii");break;case se.LedgerEntryType.claimableBalance().name:t.type="revokeClaimableBalanceSponsorship",t.balanceId=n.claimableBalance().balanceId().toXDR("hex");break;case se.LedgerEntryType.liquidityPool().name:t.type="revokeLiquidityPoolSponsorship",t.liquidityPoolId=n.liquidityPool().liquidityPoolId().toString("hex");break;default:throw new Error(`Unknown ledgerKey: ${e.switch().name}`)}break}case"revokeSponsorshipSigner":t.type="revokeSignerSponsorship",t.account=eo(e.signer().accountId()),t.signer=function(e){const t={};switch(e.switch().name){case se.SignerKeyType.signerKeyTypeEd25519().name:t.ed25519PublicKey=wn.encodeEd25519PublicKey(e.ed25519());break;case se.SignerKeyType.signerKeyTypePreAuthTx().name:t.preAuthTx=e.preAuthTx().toString("hex");break;case se.SignerKeyType.signerKeyTypeHashX().name:t.sha256Hash=e.hashX().toString("hex");break;case se.SignerKeyType.signerKeyTypeEd25519SignedPayload().name:{const n=e.ed25519SignedPayload();t.ed25519SignedPayload=wn.encodeSignedPayload(n.toXDR());break}default:throw new Error(`Unknown signerKey: ${e.switch().name}`)}return t}(e.signer().signerKey());break;default:throw new Error(`Unknown revokeSponsorship: ${e.switch().name}`)}}(r,t);break;case"clawback":t.type="clawback",t.amount=cr(r.amount()),t.from=On(r.from()),t.asset=In.fromOperation(r.asset());break;case"clawbackClaimableBalance":t.type="clawbackClaimableBalance",t.balanceId=r.toXDR("hex");break;case"setTrustLineFlags":{t.type="setTrustLineFlags",t.asset=In.fromOperation(r.asset()),t.trustor=eo(r.trustor());const e=r.clearFlags(),n=r.setFlags(),o={authorized:se.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:se.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:se.TrustLineFlags.trustlineClawbackEnabledFlag()},s=t=>{const r=o[t]?.value??0;return!!(n&r)||!(e&r)&&void 0},i={};Object.keys(o).forEach(e=>{i[e]=s(e)}),t.flags=i;break}case"liquidityPoolDeposit":t.type="liquidityPoolDeposit",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.maxAmountA=cr(r.maxAmountA()),t.maxAmountB=cr(r.maxAmountB()),t.minPrice=ur(r.minPrice()),t.maxPrice=ur(r.maxPrice());break;case"liquidityPoolWithdraw":t.type="liquidityPoolWithdraw",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.amount=cr(r.amount()),t.minAmountA=cr(r.minAmountA()),t.minAmountB=cr(r.minAmountB());break;case"invokeHostFunction":t.type="invokeHostFunction",t.func=r.hostFunction(),t.auth=r.auth()??[];break;case"extendFootprintTtl":t.type="extendFootprintTtl",t.extendTo=r.extendTo();break;case"restoreFootprint":t.type="restoreFootprint";break;default:throw new Error(`Unknown operation: ${o}`)}return t}static accountMerge=mr;static allowTrust=gr;static bumpSequence=yr;static changeTrust=wr;static createAccount=Ar;static createClaimableBalance=Sr;static claimClaimableBalance=br;static clawbackClaimableBalance=Tr;static createPassiveSellOffer=fr;static inflation=Er;static manageData=kr;static manageSellOffer=hr;static manageBuyOffer=Ir;static pathPaymentStrictReceive=Cr;static pathPaymentStrictSend=Br;static payment=xr;static setOptions=_r;static beginSponsoringFutureReserves=Pr;static endSponsoringFutureReserves=Or;static revokeAccountSponsorship=Ur;static revokeTrustlineSponsorship=Lr;static revokeOfferSponsorship=Nr;static revokeDataSponsorship=Vr;static revokeClaimableBalanceSponsorship=Fr;static revokeLiquidityPoolSponsorship=Dr;static revokeSignerSponsorship=Mr;static clawback=qr;static setTrustLineFlags=Hr;static liquidityPoolDeposit=Gr;static liquidityPoolWithdraw=$r;static invokeHostFunction=Kr;static extendFootprintTtl=Yr;static restoreFootprint=Jr;static createStellarAssetContract=zr;static invokeContractFunction=Wr;static createCustomContract=Zr;static uploadContractWasm=jr}function eo(e){return wn.encodeEd25519PublicKey(e.ed25519())}const to="none",no="id",ro="text",oo="hash",so="return";class io{_type;_value;constructor(e,t=null){switch(this._type=e,this._value=t,this._type){case to:break;case no:io._validateIdValue(t);break;case ro:io._validateTextValue(t);break;case oo:case so:io._validateHashValue(t),"string"==typeof t&&(this._value=fe.Buffer.from(t,"hex"));break;default:throw new Error("Invalid memo type")}}get type(){return this._type}set type(e){throw new Error("Memo is immutable")}get value(){switch(this._type){case to:return null;case no:case ro:return this._value;case oo:case so:return fe.Buffer.from(this._value);default:throw new Error("Invalid memo type")}}set value(e){throw new Error("Memo is immutable")}static _validateIdValue(e){const t=new Error(`Expects a uint64 as a string. Got ${e}`);if("string"!=typeof e)throw t;if(!/^[0-9]+$/.test(e))throw t;let n;try{n=new tr(e)}catch{throw t}if(!n.isFinite())throw t;if(n.isNaN())throw t;if(n.isNegative())throw t;if(!n.isInteger())throw t;if(n.isGreaterThan("18446744073709551615"))throw t}static _validateTextValue(e){if("string"==typeof e){if(fe.Buffer.byteLength(e,"utf8")>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(fe.Buffer.isBuffer(e)){if(e.length>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(!se.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}static _validateHashValue(e){const t=new Error(`Expects a 32 byte hash value or hex encoded string. Got ${String(e)}`);if(null==e)throw t;let n;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw t;n=fe.Buffer.from(e,"hex")}else{if(!fe.Buffer.isBuffer(e))throw t;n=fe.Buffer.from(e)}if(!n.length||32!==n.length)throw t}static none(){return new io(to)}static text(e){return new io(ro,e)}static id(e){return new io(no,e)}static hash(e){return new io(oo,e)}static return(e){return new io(so,e)}toXDRObject(){switch(this._type){case to:return se.Memo.memoNone();case no:return se.Memo.memoId(se.Uint64.fromString(oe.UnsignedHyper.fromString(this._value).toString()));case ro:return se.Memo.memoText(this._value);case oo:return se.Memo.memoHash(this._value);case so:return se.Memo.memoReturn(this._value);default:throw new Error("Invalid memo type")}}static fromXDRObject(e){switch(e.switch()){case se.MemoType.memoId():return io.id(e.id().toString());case se.MemoType.memoText():return io.text(e.value());case se.MemoType.memoHash():return io.hash(e.hash());case se.MemoType.memoReturn():return io.return(e.retHash())}if(void 0===e.value())return io.none();throw new Error("Unknown type")}}class ao extends Bn{_envelopeType;_source="";_memo;_sequence;_operations;_timeBounds;_ledgerBounds;_minAccountSequence;_minAccountSequenceAge;_minAccountSequenceLedgerGap;_extraSigners;constructor(e,t){if("string"==typeof e){const t=fe.Buffer.from(e,"base64");e=se.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==se.EnvelopeType.envelopeTypeTxV0()&&n!==se.EnvelopeType.envelopeTypeTx())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${n.name}.`);const r=e.value(),o=r.tx(),s=o.fee().toString();if(super(o,(r.signatures()||[]).slice(),s,t),this._envelopeType=n,this._memo=o.memo(),this._sequence=o.seqNum().toString(),this._envelopeType===se.EnvelopeType.envelopeTypeTxV0())this._source=wn.encodeEd25519PublicKey(o.sourceAccountEd25519());else this._source=On(o.sourceAccount());let i=null,a=null;switch(this._envelopeType){case se.EnvelopeType.envelopeTypeTxV0():a=o.timeBounds();break;case se.EnvelopeType.envelopeTypeTx():switch(o.cond().switch()){case se.PreconditionType.precondTime():a=o.cond().timeBounds();break;case se.PreconditionType.precondV2():i=o.cond().v2(),a=i.timeBounds()}}if(a&&(this._timeBounds={minTime:a.minTime().toString(),maxTime:a.maxTime().toString()}),i){const e=i.ledgerBounds();e&&(this._ledgerBounds={minLedger:e.minLedger(),maxLedger:e.maxLedger()});const t=i.minSeqNum();t&&(this._minAccountSequence=t.toString()),this._minAccountSequenceAge=i.minSeqAge().toBigInt(),this._minAccountSequenceLedgerGap=i.minSeqLedgerGap(),this._extraSigners=i.extraSigners()}const c=o.operations()||[];this._operations=c.map(e=>Qr.fromXDRObject(e))}get timeBounds(){return this._timeBounds}set timeBounds(e){throw new Error("Transaction is immutable")}get ledgerBounds(){return this._ledgerBounds}set ledgerBounds(e){throw new Error("Transaction is immutable")}get minAccountSequence(){return this._minAccountSequence}set minAccountSequence(e){throw new Error("Transaction is immutable")}get minAccountSequenceAge(){return this._minAccountSequenceAge}set minAccountSequenceAge(e){throw new Error("Transaction is immutable")}get minAccountSequenceLedgerGap(){return this._minAccountSequenceLedgerGap}set minAccountSequenceLedgerGap(e){throw new Error("Transaction is immutable")}get extraSigners(){return this._extraSigners}set extraSigners(e){throw new Error("Transaction is immutable")}get sequence(){return this._sequence}set sequence(e){throw new Error("Transaction is immutable")}get source(){return this._source}set source(e){throw new Error("Transaction is immutable")}get operations(){return this._operations}set operations(e){throw new Error("Transaction is immutable")}get memo(){return io.fromXDRObject(this._memo)}set memo(e){throw new Error("Transaction is immutable")}signatureBase(){let e=this.tx;this._envelopeType===se.EnvelopeType.envelopeTypeTxV0()&&(e=se.Transaction.fromXDR(fe.Buffer.concat([fe.Buffer.alloc(4),e.toXDR()])));const t=se.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(e);return new se.TransactionSignaturePayload({networkId:se.Hash.fromXDR(nt(this.networkPassphrase)),taggedTransaction:t}).toXDR()}toEnvelope(){const e=this.tx.toXDR(),t=this.signatures.slice();let n;switch(this._envelopeType){case se.EnvelopeType.envelopeTypeTxV0():n=se.TransactionEnvelope.envelopeTypeTxV0(new se.TransactionV0Envelope({tx:se.TransactionV0.fromXDR(e),signatures:t}));break;case se.EnvelopeType.envelopeTypeTx():n=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:se.Transaction.fromXDR(e),signatures:t}));break;default:throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${this._envelopeType.name}.`)}return n}getClaimableBalanceId(e){if(!Number.isInteger(e)||e<0||e>=this.operations.length)throw new RangeError("invalid operation index");const t=this.operations[e];if(void 0===t)throw new RangeError("invalid operation index");try{Qr.createClaimableBalance(t)}catch(e){throw new TypeError(`expected createClaimableBalance, got ${t.type}: ${String(e)}`)}const n=wn.decodeEd25519PublicKey(Ln(this.source)),r=nt(se.HashIdPreimage.envelopeTypeOpId(new se.HashIdPreimageOperationId({sourceAccount:se.PublicKey.publicKeyTypeEd25519(n),seqNum:se.Int64.fromString(this.sequence),opNum:e})).toXDR("raw"));return se.ClaimableBalanceId.claimableBalanceIdTypeV0(r).toXDR("hex")}}class co extends Bn{_feeSource;_innerTransaction;constructor(e,t){if("string"==typeof e){const t=fe.Buffer.from(e,"base64");e=se.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==se.EnvelopeType.envelopeTypeTxFeeBump())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ${n.name}.`);const r=e.value(),o=r.tx(),s=o.fee().toString();super(o,(r.signatures()||[]).slice(),s,t);const i=se.TransactionEnvelope.envelopeTypeTx(o.innerTx().v1());this._feeSource=On(this.tx.feeSource()),this._innerTransaction=new ao(i,t)}get innerTransaction(){return this._innerTransaction}get operations(){return this._innerTransaction.operations}get feeSource(){return this._feeSource}signatureBase(){const e=se.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx);return new se.TransactionSignaturePayload({networkId:se.Hash.fromXDR(nt(this.networkPassphrase)),taggedTransaction:e}).toXDR()}toEnvelope(){const e=new se.FeeBumpTransactionEnvelope({tx:se.FeeBumpTransaction.fromXDR(this.tx.toXDR()),signatures:this.signatures.slice()});return se.TransactionEnvelope.envelopeTypeTxFeeBump(e)}}class uo{_accountId;sequence;constructor(e,t){if(wn.isValidMed25519PublicKey(e))throw new Error("accountId is an M-address; use MuxedAccount instead");if(!wn.isValidEd25519PublicKey(e))throw new Error("accountId is invalid");if("string"!=typeof t)throw new Error("sequence must be of type string");let n;try{n=new tr(t)}catch{throw new Error("sequence is not a valid number")}if(n.isNaN())throw new Error("sequence is not a valid number");this._accountId=e,this.sequence=n}accountId(){return this._accountId}sequenceNumber(){return this.sequence.toString()}incrementSequenceNumber(){this.sequence=this.sequence.plus(1)}}const lo=BigInt("18446744073709551615");function po(e){let t;try{t=BigInt(e)}catch{throw new Error(`id is not a valid uint64 string: ${e}`)}if(t<BigInt(0)||t>lo)throw new Error(`id value out of range for uint64 [0, ${lo}]: ${e}`)}class ho{account;_muxedXdr;_mAddress;_id;constructor(e,t){const n=e.accountId();if(!wn.isValidEd25519PublicKey(n))throw new Error("accountId is invalid");po(t),this.account=e,this._muxedXdr=Un(n,t),this._mAddress=On(this._muxedXdr),this._id=t}static fromAddress(e,t){const n=Pn(e),r=Ln(e),o=n.med25519().id().toString();return new ho(new uo(r,t),o)}baseAccount(){return this.account}accountId(){return this._mAddress}id(){return this._id}setId(e){if("string"!=typeof e)throw new Error("id should be a string representing a number (uint64)");return po(e),this._muxedXdr.med25519().id(se.Uint64.fromString(e)),this._mAddress=On(this._muxedXdr),this._id=e,this}sequenceNumber(){return this.account.sequenceNumber()}incrementSequenceNumber(){this.account.incrementSequenceNumber()}toXDRObject(){return this._muxedXdr}equals(e){return this.accountId()===e.accountId()}}class fo{_data;constructor(e){let t;t=e?"string"==typeof e||ArrayBuffer.isView(e)?fo.fromXDR(e):fo.fromXDR(e.toXDR()):new se.SorobanTransactionData({resources:new se.SorobanResources({footprint:new se.LedgerFootprint({readOnly:[],readWrite:[]}),instructions:0,diskReadBytes:0,writeBytes:0}),ext:new se.SorobanTransactionDataExt(0),resourceFee:new se.Int64(0)}),this._data=t}static fromXDR(e){return"string"==typeof e?se.SorobanTransactionData.fromXDR(e,"base64"):se.SorobanTransactionData.fromXDR(fe.Buffer.from(e),"raw")}setResourceFee(e){return this._data.resourceFee(new se.Int64(e)),this}setResources(e,t,n){return this._data.resources().instructions(e),this._data.resources().diskReadBytes(t),this._data.resources().writeBytes(n),this}appendFootprint(e,t){return this.setFootprint(this.getReadOnly().concat(e),this.getReadWrite().concat(t))}setFootprint(e,t){return null!==e&&this.setReadOnly(e),null!==t&&this.setReadWrite(t),this}setReadOnly(e){return this._data.resources().footprint().readOnly(e??[]),this}setReadWrite(e){return this._data.resources().footprint().readWrite(e??[]),this}build(){return se.SorobanTransactionData.fromXDR(this._data.toXDR())}getReadOnly(){return this.getFootprint().readOnly()}getReadWrite(){return this.getFootprint().readWrite()}getFootprint(){return this._data.resources().footprint()}}class mo{static decodeAddress(e){const t=wn.getVersionByteForPrefix(e);if(void 0===t)throw new Error(`invalid signer key type (${t})`);const n=Sn(t,e);switch(t){case"signedPayload":return se.SignerKey.signerKeyTypeEd25519SignedPayload(new se.SignerKeyEd25519SignedPayload({ed25519:n.subarray(0,32),payload:n.subarray(36,36+n.readUInt32BE(32))}));case"ed25519PublicKey":return se.SignerKey.signerKeyTypeEd25519(n);case"preAuthTx":return se.SignerKey.signerKeyTypePreAuthTx(n);case"sha256Hash":return se.SignerKey.signerKeyTypeHashX(n);default:throw new Error(`invalid signer key type (${t})`)}}static encodeSignerKey(e){let t,n;switch(e.switch()){case se.SignerKeyType.signerKeyTypeEd25519():t="ed25519PublicKey",n=e.value();break;case se.SignerKeyType.signerKeyTypePreAuthTx():t="preAuthTx",n=e.value();break;case se.SignerKeyType.signerKeyTypeHashX():t="sha256Hash",n=e.value();break;case se.SignerKeyType.signerKeyTypeEd25519SignedPayload():t="signedPayload",n=e.ed25519SignedPayload().toXDR("raw");break;default:throw new Error(`invalid SignerKey (type: ${e.switch().name})`)}return bn(t,n)}}class go{_id;constructor(e){try{this._id=wn.decodeContract(e)}catch{throw new Error(`Invalid contract ID: ${e}`)}}contractId(){return wn.encodeContract(this._id)}toString(){return this.contractId()}address(){return Xr.contract(this._id)}call(e,...t){return Qr.invokeContractFunction({contract:this.address().toString(),function:e,args:t})}getFootprint(){return se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:this.address().toScAddress(),key:se.ScVal.scvLedgerKeyContractInstance(),durability:se.ContractDataDurability.persistent()}))}}class yo extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 128}}yo.defineIntBoundaries();class wo extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 256}}wo.defineIntBoundaries();class Ao extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 128}}Ao.defineIntBoundaries();class So extends oe.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 256}}So.defineIntBoundaries();class bo{int;type;constructor(e,t){t instanceof Array||(t=[t]);const n=t.map(e=>"bigint"==typeof e?e:"object"==typeof e&&null!==e&&"toBigInt"in e&&"function"==typeof e.toBigInt?e.toBigInt():BigInt(e));switch(e){case"i64":this.int=new oe.Hyper(n);break;case"i128":this.int=new Ao(...n);break;case"i256":this.int=new So(...n);break;case"u64":case"timepoint":case"duration":this.int=new oe.UnsignedHyper(n);break;case"u128":this.int=new yo(...n);break;case"u256":this.int=new wo(...n);break;default:throw TypeError(`invalid type: ${e}`)}this.type=e}toNumber(){const e=this.int.toBigInt();if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw RangeError(`value ${e} not in range for Number [${Number.MAX_SAFE_INTEGER}, ${Number.MIN_SAFE_INTEGER}]`);return Number(e)}toBigInt(){return this.int.toBigInt()}toI64(){this._sizeCheck(64);const e=this.toBigInt();if(BigInt.asIntN(64,e)!==e)throw RangeError(`value too large for i64: ${e}`);return se.ScVal.scvI64(new se.Int64(e))}toU64(){return this._sizeCheck(64),se.ScVal.scvU64(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toTimepoint(){return this._sizeCheck(64),se.ScVal.scvTimepoint(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toDuration(){return this._sizeCheck(64),se.ScVal.scvDuration(new se.Uint64(BigInt.asUintN(64,this.toBigInt())))}toI128(){this._sizeCheck(128);const e=this.int.toBigInt();if(BigInt.asIntN(128,e)!==e)throw RangeError(`value too large for i128: ${e}`);const t=BigInt.asIntN(64,e>>64n),n=BigInt.asUintN(64,e);return se.ScVal.scvI128(new se.Int128Parts({hi:new se.Int64(t),lo:new se.Uint64(n)}))}toU128(){this._sizeCheck(128);const e=this.int.toBigInt();return se.ScVal.scvU128(new se.UInt128Parts({hi:new se.Uint64(BigInt.asUintN(64,e>>64n)),lo:new se.Uint64(BigInt.asUintN(64,e))}))}toI256(){const e=this.int.toBigInt();if(BigInt.asIntN(256,e)!==e)throw RangeError(`value too large for i256: ${e}`);const t=BigInt.asIntN(64,e>>192n),n=BigInt.asUintN(64,e>>128n),r=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return se.ScVal.scvI256(new se.Int256Parts({hiHi:new se.Int64(t),hiLo:new se.Uint64(n),loHi:new se.Uint64(r),loLo:new se.Uint64(o)}))}toU256(){const e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),n=BigInt.asUintN(64,e>>128n),r=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return se.ScVal.scvU256(new se.UInt256Parts({hiHi:new se.Uint64(t),hiLo:new se.Uint64(n),loHi:new se.Uint64(r),loLo:new se.Uint64(o)}))}toScVal(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();case"timepoint":return this.toTimepoint();case"duration":return this.toDuration();default:throw TypeError(`invalid type: ${this.type}`)}}valueOf(){return this.int.valueOf()}toString(){return this.int.toString()}toJSON(){return{value:this.toBigInt().toString(),type:this.type}}_sizeCheck(e){if(this.int.size>e)throw RangeError(`value too large for ${e} bits (${this.type})`)}static isType(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":case"timepoint":case"duration":return!0;default:return!1}}static getType(e){const t=e.slice(3).toLowerCase();if(this.isType(t))return t}}class vo extends bo{constructor(e,t){const n=BigInt(e),r=n<0n;let o=t?.type??"";if(o.startsWith("u")&&r)throw TypeError(`specified type ${t?.type} yet negative (${e})`);if(""===o){o=r?"i":"u";const t=function(e){if(e<0n){const t=(-e-1n).toString(2).length+1;return[64,128,256].find(e=>t<=e)??t}const t=e.toString(2).length;return[64,128,256].find(e=>t<=e)??t}(n);switch(t){case 64:case 128:case 256:o+=t.toString();break;default:throw RangeError(`expected 64/128/256 bits for input (${e}), got ${t}`)}}super(o,n)}}function To(e){const t=e.switch().name,n=bo.getType(t),r=e.value();if(null===r)throw TypeError(`unexpected null value for ${t}`);switch(t){case"scvU32":case"scvI32":return BigInt(r);case"scvU64":case"scvI64":case"scvTimepoint":case"scvDuration":if(void 0===n)throw TypeError(`invalid integer type for ${t}`);return new bo(n,r).toBigInt();case"scvU128":case"scvI128":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new bo(n,[e.lo(),e.hi()]).toBigInt()}case"scvU256":case"scvI256":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new bo(n,[e.loLo(),e.loHi(),e.hiLo(),e.hiHi()]).toBigInt()}default:throw TypeError(`expected integer type, got ${t}`)}}function Eo(e,t={}){switch(typeof e){case"object":{if(null===e)return se.ScVal.scvVoid();if(e instanceof se.ScVal)return e;if(e instanceof Xr)return e.toScVal();if(e instanceof Tn)return Eo(e.publicKey(),{type:"address"});if(e instanceof go)return e.address().toScVal();if(e instanceof Uint8Array||fe.Buffer.isBuffer(e)){const n=fe.Buffer.from(e);switch(t?.type??"bytes"){case"bytes":return se.ScVal.scvBytes(n);case"symbol":return se.ScVal.scvSymbol(n);case"string":return se.ScVal.scvString(n);default:throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for bytes-like value`)}}if(Array.isArray(e))return se.ScVal.scvVec(e.map((e,n)=>Array.isArray(t.type)?Eo(e,{...t.type.length>n&&{type:t.type[n]}}):Eo(e,t)));if(Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`cannot interpret ${e.constructor?.name} value as ScVal (${JSON.stringify(e)})`);const n=t?.type??{};return se.ScVal.scvMap(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>{const[r,o]=Object.hasOwn(n,e)?n[e]??[null,null]:[null,null],s=r?{type:r}:{},i=o?{type:o}:{};return new se.ScMapEntry({key:Eo(e,s),val:Eo(t,i)})}))}case"number":case"bigint":{const n=BigInt(e);switch(t?.type){case"u32":if(n<BigInt(se.Uint32.MIN_VALUE)||n>BigInt(se.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return se.ScVal.scvU32(Number(e));case"i32":if(n<-BigInt(se.Int32.MIN_VALUE)||n>BigInt(se.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return se.ScVal.scvI32(Number(e))}return new vo(e,{type:t?.type}).toScVal()}case"string":{const n=t?.type??"string";switch(n){case"string":return se.ScVal.scvString(e);case"symbol":return se.ScVal.scvSymbol(e);case"address":return new Xr(e).toScVal();case"u32":{const t=BigInt(e);if(t<BigInt(se.Uint32.MIN_VALUE)||t>BigInt(se.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return se.ScVal.scvU32(Number(t))}case"i32":{const t=BigInt(e);if(t<-BigInt(se.Int32.MIN_VALUE)||t>BigInt(se.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return se.ScVal.scvI32(Number(t))}default:if(bo.isType(n))return new bo(n,e).toScVal();throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for string value`)}}case"boolean":return se.ScVal.scvBool(e);case"undefined":return se.ScVal.scvVoid();case"function":return Eo(e());default:throw new TypeError(`failed to convert typeof ${typeof e} (${JSON.stringify(e)})`)}}function ko(e){switch(e.switch().value){case se.ScValType.scvVoid().value:return null;case se.ScValType.scvU64().value:case se.ScValType.scvI64().value:return e.value().toBigInt();case se.ScValType.scvU128().value:case se.ScValType.scvI128().value:case se.ScValType.scvU256().value:case se.ScValType.scvI256().value:return To(e);case se.ScValType.scvVec().value:return(e.vec()??[]).map(ko);case se.ScValType.scvAddress().value:return Xr.fromScVal(e).toString();case se.ScValType.scvMap().value:return Object.fromEntries((e.map()??[]).map(e=>[ko(e.key()),ko(e.val())]));case se.ScValType.scvBool().value:case se.ScValType.scvU32().value:case se.ScValType.scvI32().value:case se.ScValType.scvBytes().value:return e.value();case se.ScValType.scvSymbol().value:{const t=e.sym();if(fe.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case se.ScValType.scvString().value:{const t=e.str();if(fe.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case se.ScValType.scvTimepoint().value:case se.ScValType.scvDuration().value:return e.value().toBigInt();case se.ScValType.scvError().value:if(e.error().switch().value===se.ScErrorType.sceContract().value)return{type:"contract",code:e.error().contractCode()};{const t=e.error();return{type:"system",code:t.code().value,value:t.code().name}}default:return e.value()}}function Io(e){const t=Array.from(e).sort((e,t)=>{const n=ko(e.key()),r=ko(t.key());switch(typeof n){case"number":case"bigint":return n===r?0:n<r?-1:1;default:{const e=n.toString(),t=r.toString();return e<t?-1:e>t?1:0}}});return se.ScVal.scvMap(t)}se.scvSortedMap=Io;const Co=oe.Hyper.MAX_VALUE,Bo=4294967295,xo="100";class Ro{source;operations;baseFee;timebounds;ledgerbounds;minAccountSequence;minAccountSequenceAge;minAccountSequenceLedgerGap;extraSigners;memo;networkPassphrase;sorobanData;constructor(e,t={}){if(!e)throw new Error("must specify source account for the transaction");if(void 0===t.fee)throw new Error("must specify fee for the transaction (in stroops)");if(this.source=e,this.operations=[],this.baseFee=t.fee,t.timebounds){const e=Po(t.timebounds.minTime),n=Po(t.timebounds.maxTime);if(void 0!==e&&e<0)throw new Error("min_time cannot be negative");if(void 0!==n&&n<0)throw new Error("max_time cannot be negative");if(void 0!==e&&void 0!==n&&n>0&&e>n)throw new Error("min_time cannot be greater than max_time");this.timebounds={...t.timebounds}}else this.timebounds=null;if(t.ledgerbounds){const e=t.ledgerbounds.minLedger,n=t.ledgerbounds.maxLedger;if(void 0!==e&&e<0)throw new Error("min_ledger cannot be negative");if(void 0!==n&&n<0)throw new Error("max_ledger cannot be negative");if(void 0!==e&&void 0!==n&&n>0&&e>n)throw new Error("min_ledger cannot be greater than max_ledger");this.ledgerbounds={...t.ledgerbounds}}else this.ledgerbounds=null;this.minAccountSequence=t.minAccountSequence||null,this.minAccountSequenceAge=void 0!==t.minAccountSequenceAge?t.minAccountSequenceAge:null,this.minAccountSequenceLedgerGap=void 0!==t.minAccountSequenceLedgerGap?t.minAccountSequenceLedgerGap:null,this.extraSigners=t.extraSigners?[...t.extraSigners]:null,this.memo=t.memo||io.none(),this.networkPassphrase=t.networkPassphrase||null,this.sorobanData=t.sorobanData?new fo(t.sorobanData).build():null}static cloneFrom(e,t={}){if(!(e instanceof ao))throw new TypeError(`expected a 'Transaction', got: ${String(e)}`);const n=(BigInt(e.sequence)-1n).toString();let r,o;if(wn.isValidMed25519PublicKey(e.source))r=ho.fromAddress(e.source,n);else{if(!wn.isValidEd25519PublicKey(e.source))throw new TypeError(`unsupported tx source account: ${e.source}`);r=new uo(e.source,n)}if(0===e.operations.length)throw new Error("cannot clone a transaction with no operations: per-operation base fee cannot be determined");const s=e.toEnvelope();s.switch()===se.EnvelopeType.envelopeTypeTx()&&(o=s.v1().tx().ext().value()??void 0);let i=parseInt(e.fee,10);if(o){const e=Number(o.resourceFee().toBigInt());i-e>0&&(i-=e)}const a={fee:(Math.floor(i/e.operations.length)||xo).toString(),memo:e.memo,networkPassphrase:e.networkPassphrase};e.timeBounds&&(a.timebounds=e.timeBounds),e.ledgerBounds&&(a.ledgerbounds=e.ledgerBounds),e.minAccountSequence&&(a.minAccountSequence=e.minAccountSequence),void 0!==e.minAccountSequenceAge&&(a.minAccountSequenceAge=e.minAccountSequenceAge),void 0!==e.minAccountSequenceLedgerGap&&(a.minAccountSequenceLedgerGap=e.minAccountSequenceLedgerGap),e.extraSigners&&(a.extraSigners=e.extraSigners.map(e=>mo.encodeSignerKey(e))),Object.assign(a,t);const c=new Ro(r,a);return e.tx.operations().forEach(e=>c.addOperation(e)),c}addOperation(e){return this.operations.push(e),this}addOperationAt(e,t){return this.operations.splice(t,0,e),this}clearOperations(){return this.operations=[],this}clearOperationAt(e){return this.operations.splice(e,1),this}addMemo(e){return this.memo=e,this}setTimeout(e){if(null!==this.timebounds&&Number(this.timebounds.maxTime)>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){const t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime??0,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}setTimebounds(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");const n=Math.floor(e.valueOf()/1e3),r=Math.floor(t.valueOf()/1e3);if(n<0)throw new Error("min_time cannot be negative");if(r<0)throw new Error("max_time cannot be negative");if(r>0&&n>r)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:n,maxTime:r},this}setLedgerbounds(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}setMinAccountSequence(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}setMinAccountSequenceAge(e){if("bigint"!=typeof e)throw new Error("min_account_sequence_age must be a bigint");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}setMinAccountSequenceLedgerGap(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}setExtraSigners(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=[...e],this}setNetworkPassphrase(e){return this.networkPassphrase=e,this}setSorobanData(e){return this.sorobanData=new fo(e).build(),this}addSacTransferOperation(e,t,n,r){if(BigInt(n)<=0n)throw new Error("Amount must be a positive integer");if(BigInt(n)>Co)throw new Error("Amount exceeds maximum value for i64");if(r){const{instructions:e,readBytes:t,writeBytes:n,resourceFee:o}=r,s=4294967295;if(e<=0||e>s)throw new Error(`instructions must be greater than 0 and at most ${s}`);if(t<=0||t>s)throw new Error(`readBytes must be greater than 0 and at most ${s}`);if(n<=0||n>s)throw new Error(`writeBytes must be greater than 0 and at most ${s}`);if(o<=0n||o>Co)throw new Error("resourceFee must be greater than 0 and at most i64 max")}const o=wn.isValidContract(e);if(!o&&!wn.isValidEd25519PublicKey(e)&&!wn.isValidMed25519PublicKey(e))throw new Error("Invalid destination address. Must be a valid Stellar address or contract ID.");const s=o?e:Ln(e);if(s===Ln(this.source.accountId()))throw new Error("Destination cannot be the same as the source account.");if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to add a SAC transfer operation");const i=t.contractId(this.networkPassphrase),a="transfer",c=this.source.accountId(),u=Ln(c),l=[Eo(c,{type:"address"}),Eo(e,{type:"address"}),Eo(n,{type:"i128"})],d=t.isNative(),p=new se.SorobanAuthorizationEntry({credentials:se.SorobanCredentials.sorobanCredentialsSourceAccount(),rootInvocation:new se.SorobanAuthorizedInvocation({function:se.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(new se.InvokeContractArgs({contractAddress:Xr.fromString(i).toScAddress(),functionName:a,args:l})),subInvocations:[]})}),h=new se.LedgerFootprint({readOnly:[se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:Xr.fromString(i).toScAddress(),key:se.ScVal.scvLedgerKeyContractInstance(),durability:se.ContractDataDurability.persistent()}))],readWrite:[]});if(o){if(h.readWrite().push(se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:Xr.fromString(i).toScAddress(),key:se.ScVal.scvVec([Eo("Balance",{type:"symbol"}),Eo(e,{type:"address"})]),durability:se.ContractDataDurability.persistent()}))),!d){const e=t.getIssuer();if(!e)throw new Error("Asset issuer must be set for non-native assets.");h.readOnly().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e).xdrPublicKey()})))}}else d?h.readWrite().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(s).xdrPublicKey()}))):t.getIssuer()!==s&&h.readWrite().push(se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(s).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));t.isNative()?h.readWrite().push(se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(u).xdrPublicKey()}))):t.getIssuer()!==u&&h.readWrite().push(se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(u).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));const f={instructions:4e5,readBytes:1e3,writeBytes:1e3,resourceFee:BigInt(5e6)},m=new se.SorobanTransactionData({resources:new se.SorobanResources({footprint:h,instructions:r?r.instructions:f.instructions,diskReadBytes:r?r.readBytes:f.readBytes,writeBytes:r?r.writeBytes:f.writeBytes}),ext:new se.SorobanTransactionDataExt(0),resourceFee:new se.Int64(r?r.resourceFee:f.resourceFee)}),g=Qr.invokeContractFunction({contract:i,function:a,args:l,auth:[p]});return this.setSorobanData(m),this.addOperation(g)}build(){const e=new tr(this.source.sequenceNumber()).plus(1),t=new tr(this.baseFee).times(this.operations.length).toNumber();if(t>Bo)throw new Error(`Total fee (baseFee * operations) exceeds the maximum uint32 value (4294967295). Got ${t} from baseFee=${this.baseFee} and ${this.operations.length} operation(s).`);const n={fee:t,seqNum:se.Int64.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");_o(this.timebounds.minTime)&&(this.timebounds.minTime=Math.floor(this.timebounds.minTime.getTime()/1e3)),_o(this.timebounds.maxTime)&&(this.timebounds.maxTime=Math.floor(this.timebounds.maxTime.getTime()/1e3));const r=se.Uint64.fromString(this.timebounds.minTime.toString()),o=se.Uint64.fromString(this.timebounds.maxTime.toString()),s=new se.TimeBounds({minTime:r,maxTime:o});if(this.hasV2Preconditions()){let e=null;null!==this.ledgerbounds&&(e=new se.LedgerBounds({minLedger:this.ledgerbounds.minLedger??0,maxLedger:this.ledgerbounds.maxLedger??0}));const t=this.minAccountSequence?se.Int64.fromString(this.minAccountSequence):null,r=se.Uint64.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),o=this.minAccountSequenceLedgerGap||0,i=null!==this.extraSigners?this.extraSigners.map(e=>mo.decodeAddress(e)):[];n.cond=se.Preconditions.precondV2(new se.PreconditionsV2({timeBounds:s,ledgerBounds:e,minSeqNum:t,minSeqAge:r,minSeqLedgerGap:o,extraSigners:i}))}else n.cond=se.Preconditions.precondTime(s);if(n.sourceAccount=Pn(this.source.accountId()),this.sorobanData){if(n.ext=new se.TransactionExt(1,this.sorobanData),n.fee=new tr(n.fee).plus(this.sorobanData.resourceFee().toString()).toNumber(),n.fee>Bo)throw new Error(`Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (4294967295). Got ${n.fee}.`)}else n.ext=new se.TransactionExt(0);const i=new se.Transaction(n);i.operations(this.operations);const a=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:i,signatures:[]}));if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to build a transaction");const c=new ao(a,this.networkPassphrase);return this.source.incrementSequenceNumber(),c}hasV2Preconditions(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}static buildFeeBumpTransaction(e,t,n,r){const o=n.operations.length,s=new tr(xo);let i=new tr(0);const a=n.toEnvelope();switch(a.switch().value){case se.EnvelopeType.envelopeTypeTx().value:{const e=a.v1().tx().ext().value();i=new tr(e?.resourceFee().toString()??0);break}}const c=new tr(n.fee).minus(i).div(o),u=new tr(t);if(u.lt(c))throw new Error(`Invalid baseFee, it should be at least ${c.toString()} stroops.`);if(u.lt(s))throw new Error(`Invalid baseFee, it should be at least ${s.toString()} stroops.`);let l,d=n.toEnvelope();if(d.switch()===se.EnvelopeType.envelopeTypeTxV0()){const e=d.v0().tx(),t=e.timeBounds();if(null===t)throw new Error("Inner transaction must have time bounds");const n=new se.Transaction({sourceAccount:se.MuxedAccount.keyTypeEd25519(e.sourceAccountEd25519()),fee:e.fee(),seqNum:e.seqNum(),cond:se.Preconditions.precondTime(t),memo:e.memo(),operations:e.operations(),ext:new se.TransactionExt(0)});d=se.TransactionEnvelope.envelopeTypeTx(new se.TransactionV1Envelope({tx:n,signatures:d.v0().signatures()}))}l="string"==typeof e?Pn(e):e.xdrMuxedAccount();const p=new se.FeeBumpTransaction({feeSource:l,fee:se.Int64.fromString(u.times(o+1).plus(i).toString()),innerTx:se.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new se.FeeBumpTransactionExt(0)}),h=new se.FeeBumpTransactionEnvelope({tx:p,signatures:[]}),f=se.TransactionEnvelope.envelopeTypeTxFeeBump(h);return new co(f,r)}static fromXDR(e,t){return"string"==typeof e&&(e=se.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===se.EnvelopeType.envelopeTypeTxFeeBump()?new co(e,t):new ao(e,t)}}function _o(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function Po(e){if(void 0===e)return;const t=e instanceof Date?Math.floor(e.getTime()/1e3):Number(e);if(!Number.isFinite(t)||t%1!=0)throw new Error("timebounds value must be a finite integer or Date");return t}var Oo=(e=>(e.PUBLIC="Public Global Stellar Network ; September 2015",e.TESTNET="Test SDF Network ; September 2015",e.FUTURENET="Test SDF Future Network ; October 2022",e.SANDBOX="Local Sandbox Stellar Network ; September 2022",e.STANDALONE="Standalone Network ; February 2017",e))(Oo||{});class Uo{static formatTokenAmount(e,t){if(e.includes("."))throw new TypeError("No decimals are allowed");const n=e.startsWith("-");let r=n?e.slice(1):e;return t>0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.includes(".")&&(r=r.replace(/0+$/,""),r.endsWith(".")&&(r+="0")),r.startsWith(".")&&(r=`0${r}`),n?`-${r}`:r}static parseTokenAmount(e,t){const[n,r,...o]=e.split(".").slice();if(o.length)throw new Error(`Invalid decimal value: ${e}`);if(r?.length&&r.length>t)throw new Error(`Too many decimal places in "${e}": expected at most ${t}, got ${r.length}`);return BigInt(n+(r?.padEnd(t,"0")??"0".repeat(t))).toString()}}function Lo(e){const t="function"==typeof e.contractId?e.contractId():null;return{...null!=t&&{contractId:wn.encodeContract(t)},type:e.type().name,topics:e.body().value().topics().map(e=>ko(e)),data:ko(e.body().value().data())}}function No(e){return e.map(e=>Lo("inSuccessfulContractCall"in e?e.event():e))}function Vo(e){return e instanceof ArrayBuffer?fe.Buffer.from(new Uint8Array(e)):fe.Buffer.from(e)}async function Fo(e,t,n,r,o){if(e.credentials().switch().value===se.SorobanCredentialsType.sorobanCredentialsSourceAccount().value)return e;const s=se.SorobanAuthorizationEntry.fromXDR(e.toXDR()),i=s.credentials(),a=Go(i);if(null===a)throw new Error(`unsupported credential type ${i.switch().name}`);a.signatureExpirationLedger(n);const c=Mo(s,n,r),u=nt(c.toXDR());let l,d;if("function"==typeof t){const e=await t(c);null!==e&&"object"==typeof e&&"signature"in e?(l=Vo(e.signature),d=e.publicKey):(l=Vo(e),d=Xr.fromScAddress(a.address()).toString())}else l=Vo(t.sign(u)),d=t.publicKey();if(!Tn.fromPublicKey(d).verify(u,l))throw new Error("signature doesn't match payload");const p=Eo({public_key:wn.decodeEd25519PublicKey(d),signature:l},{type:{public_key:["symbol",null],signature:["symbol",null]}}),h=se.ScVal.scvVec([p]),f=void 0===o?[a]:function(e){switch(e.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return[e.address()];case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return[e.addressV2()];case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:{const t=e.addressWithDelegates(),n=[t.addressCredentials()],r=e=>{e.forEach(e=>{n.push(e),r(e.nestedDelegates())})};return r(t.delegates()),n}default:return[]}}(i).filter(e=>Xr.fromScAddress(e.address()).toString()===o);if(0===f.length)throw new Error(`the authorization entry has no credential node for address ${o}`);return f.forEach(e=>e.signature(h)),s}function Do(e){const{signer:t,validUntilLedgerSeq:n,invocation:r,networkPassphrase:o,publicKey:s="",authV2:i=!1}=e,a=Tn.random().rawPublicKey(),c=new se.Int64(function(e){const t=e.subarray(0,8);if(t.length<8)throw new Error(`need at least 8 bytes to convert to Int64, got ${e.length}`);const n=new DataView(t.buffer,t.byteOffset,8);return n.getBigInt64(0,!1)}(a)),u=s||(t instanceof Tn?t.publicKey():null);if(!u)throw new Error("authorizeInvocation requires publicKey parameter");const l=new se.SorobanAddressCredentials({address:new Xr(u).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:se.ScVal.scvVec([])});return Fo(new se.SorobanAuthorizationEntry({rootInvocation:r,credentials:i?se.SorobanCredentials.sorobanCredentialsAddressV2(l):se.SorobanCredentials.sorobanCredentialsAddress(l)}),t,n,o)}function Mo(e,t,n){const r=e.credentials(),o=Go(r);if(null===o)throw new Error(`cannot build a signature payload for credential type ${r.switch().name}`);const s=nt(fe.Buffer.from(n));switch(r.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return se.HashIdPreimage.envelopeTypeSorobanAuthorization(new se.HashIdPreimageSorobanAuthorization({networkId:s,nonce:o.nonce(),invocation:e.rootInvocation(),signatureExpirationLedger:t}));case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return se.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(new se.HashIdPreimageSorobanAuthorizationWithAddress({networkId:s,nonce:o.nonce(),invocation:e.rootInvocation(),address:o.address(),signatureExpirationLedger:t}));default:throw new Error(`unsupported credential type ${r.switch().name}`)}}function qo(e){const{entry:t,validUntilLedgerSeq:n,delegates:r,signature:o}=e,s=t.credentials(),i=Go(s);if(null===i||s.switch().value===se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value)throw new Error(`buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${s.switch().name}`);return new se.SorobanAuthorizationEntry({rootInvocation:t.rootInvocation(),credentials:se.SorobanCredentials.sorobanCredentialsAddressWithDelegates(new se.SorobanAddressCredentialsWithDelegates({addressCredentials:new se.SorobanAddressCredentials({address:i.address(),nonce:i.nonce(),signatureExpirationLedger:n,signature:o??se.ScVal.scvVoid()}),delegates:Ho(r)}))})}function Ho(e){const t=e.map(e=>new se.SorobanDelegateSignature({address:new Xr(e.address).toScAddress(),signature:e.signature??se.ScVal.scvVoid(),nestedDelegates:Ho(e.nestedDelegates??[])}));t.sort((e,t)=>fe.Buffer.compare(e.address().toXDR(),t.address().toXDR()));for(let e=1;e<t.length;e++)if(0===fe.Buffer.compare(t[e-1].address().toXDR(),t[e].address().toXDR()))throw new Error(`duplicate delegate address ${Xr.fromScAddress(t[e].address()).toString()}`);return t}function Go(e){switch(e.switch().value){case se.SorobanCredentialsType.sorobanCredentialsAddress().value:return e.address();case se.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return e.addressV2();case se.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return e.addressWithDelegates().addressCredentials();default:return null}}function $o(e){const t=e.function(),n={},r=t.value();switch(t.switch().value){case 0:{const e=t.contractFn();n.type="execute",n.args={source:Xr.fromScAddress(e.contractAddress()).toString(),function:e.functionName().toString(),args:e.args().map(e=>ko(e))};break}case 1:case 2:{const e=r,o=2===t.switch().value;n.type="create";const s={},[i,a]=[e.executable(),e.contractIdPreimage()];if(!!i.switch().value!=!!a.switch().value)throw new Error(`creation function appears invalid: ${JSON.stringify(r)} (should be wasm+address or token+asset)`);switch(i.switch().value){case 0:{const e=a.fromAddress();s.type="wasm",s.wasm={salt:fe.Buffer.from(e.salt()).toString("hex"),hash:i.wasmHash().toString("hex"),address:Xr.fromScAddress(e.address()).toString(),...o&&{constructorArgs:r.constructorArgs().map(e=>ko(e))}};break}case 1:s.type="sac",s.asset=In.fromOperation(a.fromAsset()).toString();break;default:throw new Error(`unknown creation type: ${JSON.stringify(i)}`)}n.args=s;break}default:throw new Error(`unknown invocation type (${t.switch().value}): ${JSON.stringify(t)}`)}return n.invocations=e.subInvocations().map(e=>$o(e)),n}function Xo(e,t){Ko(e,1,t)}function Ko(e,t,n,r){!1!==n(e,t,r)&&e.subInvocations().forEach(r=>Ko(r,t+1,n,e))}var Wo=Object.freeze({__proto__:null,Account:uo,Address:Xr,Asset:In,AssetType:En,AuthClawbackEnabledFlag:8,AuthImmutableFlag:4,AuthRequiredFlag:1,AuthRevocableFlag:2,BASE_FEE:xo,Claimant:Rn,Contract:go,FeeBumpTransaction:co,Hyper:oe.Hyper,Int128:Ao,Int256:So,Keypair:Tn,LiquidityPoolAsset:xn,LiquidityPoolFeeV18:30,LiquidityPoolId:_n,Memo:io,MemoHash:oo,MemoID:no,MemoNone:to,MemoReturn:so,MemoText:ro,MuxedAccount:ho,Networks:Oo,Operation:Qr,ScInt:vo,SignerKey:mo,Soroban:Uo,SorobanDataBuilder:fo,StrKey:wn,TimeoutInfinite:0,Transaction:ao,TransactionBase:Bn,TransactionBuilder:Ro,Uint128:yo,Uint256:wo,UnsignedHyper:oe.UnsignedHyper,XdrLargeInt:bo,authorizeEntry:Fo,authorizeInvocation:Do,buildAuthorizationEntryPreimage:Mo,buildInvocationTree:$o,buildWithDelegatesEntry:qo,cereal:ie,decodeAddressToMuxedAccount:Pn,encodeMuxedAccount:Un,encodeMuxedAccountToAddress:On,extractBaseAddress:Ln,getLiquidityPoolId:Cn,hash:nt,humanizeEvents:No,nativeToScVal:Eo,scValToBigInt:To,scValToNative:ko,scvSortedMap:Io,sign:cn,verify:un,walkInvocationTree:Xo,xdr:se});function Zo(e){if(!/^(?:[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)*[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?::\d+)?$/.test(e))throw new Error("The provided domain is invalid. Ensure that the domain adheres to RFC 1035")}const zo=102400;class jo{serverURL;domain;timeout;static async resolve(e,t={}){if(e.indexOf("*")<0)return wn.isValidEd25519PublicKey(e)?Promise.resolve({account_id:e}):Promise.reject(new Error("Invalid Account ID"));const n=e.split("*"),[,r]=n;if(2!==n.length||!r)return Promise.reject(new Error("Invalid Stellar address"));return(await jo.createForDomain(r,t)).resolveAddress(e)}static async createForDomain(e,t={}){Zo(e);const n=await Q.resolve(e,t);return n.FEDERATION_SERVER?new jo(n.FEDERATION_SERVER,e,t):Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))}constructor(e,t,n={}){this.serverURL=new URL(e),this.domain=t,Zo(t);const r=void 0===n.allowHttp?_.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?_.getTimeout():n.timeout,"https:"!==this.serverURL.protocol&&!r)throw new Error("Cannot connect to insecure federation server")}async resolveAddress(e){let t=e;if(e.indexOf("*")<0){if(!this.domain)return Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."));t=`${e}*${this.domain}`}const n=new URL(this.serverURL);return n.search="",n.searchParams.set("type","name"),n.searchParams.set("q",t),this._sendRequest(n)}async resolveAccountId(e){const t=new URL(this.serverURL);return t.search="",t.searchParams.set("type","id"),t.searchParams.set("q",e),this._sendRequest(t)}async resolveTransactionId(e){const t=new URL(this.serverURL);return t.search="",t.searchParams.set("type","txid"),t.searchParams.set("q",e),this._sendRequest(t)}async _sendRequest(e){const t=this.timeout;return T.get(e.toString(),{maxContentLength:zo,timeout:t}).then(e=>{if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data}).catch(e=>{if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of 102400");return Promise.reject(e)}return Promise.reject(new C(`Server query failed. Server responded: ${e.status} ${e.statusText}`,e.data))})}}var Yo=Object.freeze({__proto__:null,FEDERATION_RESPONSE_MAX_SIZE:zo,Server:jo});class Jo extends Error{}function Qo(e,t){const n=e.hash(),r=[...e.signatures],o=new Set;for(const e of t){if(0===r.length)break;let t;try{t=Tn.fromPublicKey(e)}catch(e){throw new Jo(`Signer is not a valid address: ${e.message}`)}for(let s=0;s<r.length;s++){const i=r[s];if(i.hint().equals(t.signatureHint())&&t.verify(n,i.signature())){o.add(e),r.splice(s,1);break}}}return Array.from(o)}function es(e,t){return 0!==Qo(e,[t]).length}const ts=Object.prototype.toString;function ns(e){return function(e,t,n){return!!e&&(e.constructor===t||ts.call(e)===n)}(e,Uint8Array,"[object Uint8Array]")}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder;function rs(e,{urlSafe:t=!1}={}){!function(e){if(!ns(e))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}(e);let n="";for(let t=0;t<e.length;t+=65535){const r=e.subarray(t,t+65535);n+=globalThis.btoa(String.fromCodePoint.apply(void 0,r))}return t?function(e){return e.replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}(n):n}function os(e,t,n,r,o){if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");let s;try{s=new ao(e,n)}catch{try{s=new co(e,n)}catch{throw new Jo("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new Jo("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(s.sequence,10))throw new Jo("The transaction sequence number should be zero");if(s.source!==t)throw new Jo("The transaction source account is not equal to the server's account");if(s.operations.length<1)throw new Jo("The transaction should contain at least one operation");const[i,...a]=s.operations;if(!i.source)throw new Jo("The transaction's operation should contain a source account");const c=i.source;let u,l=null;if(s.memo.type!==to){if(c.startsWith("M"))throw new Jo("The transaction has a memo but the client account ID is a muxed account");if(s.memo.type!==no)throw new Jo("The transaction's memo must be of type `id`");l=s.memo.value}if("manageData"!==i.type)throw new Jo("The transaction's operation type should be 'manageData'");if(s.timeBounds&&0===Number.parseInt(s.timeBounds?.maxTime,10))throw new Jo("The transaction requires non-infinite timebounds");if(!P.validateTimebounds(s,300))throw new Jo("The transaction has expired");if(void 0===i.value)throw new Jo("The transaction's operation values should not be null");if(!i.value)throw new Jo("The transaction's operation value should not be null");if(48!==fe.Buffer.from(i.value.toString(),"base64").length)throw new Jo("The transaction's operation value should be a 64 bytes base64 random string");if(!r)throw new Jo("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof r)`${r} auth`===i.name&&(u=r);else{if(!Array.isArray(r))throw new Jo(`Invalid homeDomains: homeDomains type is ${typeof r} but should be a string or an array`);u=r.find(e=>`${e} auth`===i.name)}if(!u)throw new Jo("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");for(const e of a){if("manageData"!==e.type)throw new Jo("The transaction has operations that are not of type 'manageData'");if(e.source!==t&&"client_domain"!==e.name)throw new Jo("The transaction has operations that are unrecognized");if("web_auth_domain"===e.name){if(void 0===e.value)throw new Jo("'web_auth_domain' operation value should not be null");if(e.value.compare(fe.Buffer.from(o)))throw new Jo(`'web_auth_domain' operation value does not match ${o}`)}}if(!es(s,t))throw new Jo(`Transaction not signed by server: '${t}'`);return{tx:s,clientAccountID:c,matchedHomeDomain:u,memo:l}}function ss(e,t,n,r,o,s){const{tx:i}=os(e,t,n,o,s);let a;try{a=Tn.fromPublicKey(t)}catch(e){throw new Error(`Couldn't infer keypair from the provided 'serverAccountID': ${e.message}`)}const c=new Set;for(const e of r)e!==a.publicKey()&&"G"===e.charAt(0)&&c.add(e);if(0===c.size)throw new Jo("No verifiable client signers provided, at least one G... address must be provided");let u;for(const e of i.operations)if("manageData"===e.type&&"client_domain"===e.name){if(u)throw new Jo("Found more than one client_domain operation");u=e.source}const l=[a.publicKey(),...Array.from(c)];u&&l.push(u);const d=Qo(i,l);let p=!1,h=!1;for(const e of d)e===a.publicKey()&&(p=!0),e===u&&(h=!0);if(!p)throw new Jo(`Transaction not signed by server: '${a.publicKey()}'`);if(u&&!h)throw new Jo("Transaction not signed by the source account of the 'client_domain' ManageData operation");if(1===d.length)throw new Jo("None of the given signers match the transaction signatures");if(d.length!==i.signatures.length)throw new Jo("Transaction has unrecognized signatures");if(d.splice(d.indexOf(a.publicKey()),1),u&&d.splice(d.indexOf(u),1),0===d.length)throw new Jo("None of the given signers match the transaction signatures");return d}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var is,as,cs,us,ls,ds=Object.freeze({__proto__:null,InvalidChallengeError:Jo,buildChallengeTx:function(e,t,n,r=300,o,s,i=null,a=null,c=null){if(t.startsWith("M")&&i)throw Error("memo cannot be used if clientAccountID is a muxed account");const u=new uo(e.publicKey(),"-1"),l=Math.floor(Date.now()/1e3),d=rs(crypto.getRandomValues(new Uint8Array(48))),p=new Ro(u,{fee:xo,networkPassphrase:o,timebounds:{minTime:l,maxTime:l+r}}).addOperation(Qr.manageData({name:`${n} auth`,value:d,source:t})).addOperation(Qr.manageData({name:"web_auth_domain",value:s,source:u.accountId()}));if(a){if(!c)throw Error("clientSigningKey is required if clientDomain is provided");p.addOperation(Qr.manageData({name:"client_domain",value:a,source:c}))}i&&p.addMemo(io.id(i));const h=p.build();return h.sign(e),h.toEnvelope().toXDR("base64").toString()},gatherTxSigners:Qo,readChallengeTx:os,verifyChallengeTxSigners:ss,verifyChallengeTxThreshold:function(e,t,n,r,o,s,i){const a=ss(e,t,n,o.map(e=>e.key),s,i);let c=0;for(const e of a){c+=o.find(t=>t.key===e)?.weight||0}if(c<r)throw new Jo(`signers with weight ${c} do not meet threshold ${r}"`);return a},verifyTxSignedBy:es}),ps=Object.freeze({__proto__:null});((as=is||(is={})).LiquidityPoolType||(as.LiquidityPoolType={})).constantProduct="constant_product",(cs=as.OperationResponseType||(as.OperationResponseType={})).createAccount="create_account",cs.payment="payment",cs.pathPayment="path_payment_strict_receive",cs.createPassiveOffer="create_passive_sell_offer",cs.manageOffer="manage_sell_offer",cs.setOptions="set_options",cs.changeTrust="change_trust",cs.allowTrust="allow_trust",cs.accountMerge="account_merge",cs.inflation="inflation",cs.manageData="manage_data",cs.bumpSequence="bump_sequence",cs.manageBuyOffer="manage_buy_offer",cs.pathPaymentStrictSend="path_payment_strict_send",cs.createClaimableBalance="create_claimable_balance",cs.claimClaimableBalance="claim_claimable_balance",cs.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",cs.endSponsoringFutureReserves="end_sponsoring_future_reserves",cs.revokeSponsorship="revoke_sponsorship",cs.clawback="clawback",cs.clawbackClaimableBalance="clawback_claimable_balance",cs.setTrustLineFlags="set_trust_line_flags",cs.liquidityPoolDeposit="liquidity_pool_deposit",cs.liquidityPoolWithdraw="liquidity_pool_withdraw",cs.invokeHostFunction="invoke_host_function",cs.bumpFootprintExpiration="bump_footprint_expiration",cs.restoreFootprint="restore_footprint",(us=as.OperationResponseTypeI||(as.OperationResponseTypeI={}))[us.createAccount=0]="createAccount",us[us.payment=1]="payment",us[us.pathPayment=2]="pathPayment",us[us.createPassiveOffer=3]="createPassiveOffer",us[us.manageOffer=4]="manageOffer",us[us.setOptions=5]="setOptions",us[us.changeTrust=6]="changeTrust",us[us.allowTrust=7]="allowTrust",us[us.accountMerge=8]="accountMerge",us[us.inflation=9]="inflation",us[us.manageData=10]="manageData",us[us.bumpSequence=11]="bumpSequence",us[us.manageBuyOffer=12]="manageBuyOffer",us[us.pathPaymentStrictSend=13]="pathPaymentStrictSend",us[us.createClaimableBalance=14]="createClaimableBalance",us[us.claimClaimableBalance=15]="claimClaimableBalance",us[us.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",us[us.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",us[us.revokeSponsorship=18]="revokeSponsorship",us[us.clawback=19]="clawback",us[us.clawbackClaimableBalance=20]="clawbackClaimableBalance",us[us.setTrustLineFlags=21]="setTrustLineFlags",us[us.liquidityPoolDeposit=22]="liquidityPoolDeposit",us[us.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",us[us.invokeHostFunction=24]="invokeHostFunction",us[us.bumpFootprintExpiration=25]="bumpFootprintExpiration",us[us.restoreFootprint=26]="restoreFootprint",(ls=as.TransactionFailedResultCodes||(as.TransactionFailedResultCodes={})).TX_FAILED="tx_failed",ls.TX_BAD_SEQ="tx_bad_seq",ls.TX_BAD_AUTH="tx_bad_auth",ls.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",ls.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",ls.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",ls.TX_NOT_SUPPORTED="tx_not_supported",ls.TX_SUCCESS="tx_success",ls.TX_TOO_EARLY="tx_too_early",ls.TX_TOO_LATE="tx_too_late",ls.TX_MISSING_OPERATION="tx_missing_operation",ls.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",ls.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",ls.TX_INSUFFICIENT_FEE="tx_insufficient_fee",ls.TX_INTERNAL_ERROR="tx_internal_error";var hs,fs,ms,gs=(e=>(e[e.account_created=0]="account_created",e[e.account_removed=1]="account_removed",e[e.account_credited=2]="account_credited",e[e.account_debited=3]="account_debited",e[e.account_thresholds_updated=4]="account_thresholds_updated",e[e.account_home_domain_updated=5]="account_home_domain_updated",e[e.account_flags_updated=6]="account_flags_updated",e[e.account_inflation_destination_updated=7]="account_inflation_destination_updated",e[e.signer_created=10]="signer_created",e[e.signer_removed=11]="signer_removed",e[e.signer_updated=12]="signer_updated",e[e.trustline_created=20]="trustline_created",e[e.trustline_removed=21]="trustline_removed",e[e.trustline_updated=22]="trustline_updated",e[e.trustline_authorized=23]="trustline_authorized",e[e.trustline_deauthorized=24]="trustline_deauthorized",e[e.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",e[e.trustline_flags_updated=26]="trustline_flags_updated",e[e.offer_created=30]="offer_created",e[e.offer_removed=31]="offer_removed",e[e.offer_updated=32]="offer_updated",e[e.trade=33]="trade",e[e.data_created=40]="data_created",e[e.data_removed=41]="data_removed",e[e.data_updated=42]="data_updated",e[e.sequence_bumped=43]="sequence_bumped",e[e.claimable_balance_created=50]="claimable_balance_created",e[e.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",e[e.claimable_balance_claimed=52]="claimable_balance_claimed",e[e.account_sponsorship_created=60]="account_sponsorship_created",e[e.account_sponsorship_updated=61]="account_sponsorship_updated",e[e.account_sponsorship_removed=62]="account_sponsorship_removed",e[e.trustline_sponsorship_created=63]="trustline_sponsorship_created",e[e.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",e[e.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",e[e.data_sponsorship_created=66]="data_sponsorship_created",e[e.data_sponsorship_updated=67]="data_sponsorship_updated",e[e.data_sponsorship_removed=68]="data_sponsorship_removed",e[e.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",e[e.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",e[e.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",e[e.signer_sponsorship_created=72]="signer_sponsorship_created",e[e.signer_sponsorship_updated=73]="signer_sponsorship_updated",e[e.signer_sponsorship_removed=74]="signer_sponsorship_removed",e[e.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",e[e.liquidity_pool_deposited=90]="liquidity_pool_deposited",e[e.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",e[e.liquidity_pool_trade=92]="liquidity_pool_trade",e[e.liquidity_pool_created=93]="liquidity_pool_created",e[e.liquidity_pool_removed=94]="liquidity_pool_removed",e[e.liquidity_pool_revoked=95]="liquidity_pool_revoked",e[e.contract_credited=96]="contract_credited",e[e.contract_debited=97]="contract_debited",e))(gs||{});(fs=hs||(hs={})).EffectType=gs,(ms=fs.TradeType||(fs.TradeType={})).all="all",ms.liquidityPools="liquidity_pool",ms.orderbook="orderbook",is.OperationResponseType,is.OperationResponseTypeI;class ys{id;paging_token;account_id;sequence;sequence_ledger;sequence_time;subentry_count;home_domain;inflation_destination;last_modified_ledger;last_modified_time;thresholds;flags;balances;signers;num_sponsoring;num_sponsored;sponsor;data;data_attr;effects;offers;operations;payments;trades;transactions;_baseAccount;constructor(e){this._baseAccount=new uo(e.account_id,e.sequence),this.effects=e.effects,this.offers=e.offers,this.operations=e.operations,this.payments=e.payments,this.trades=e.trades,this.data=e.data,this.transactions=e.transactions,this.id=e.id,this.paging_token=e.paging_token,this.account_id=e.account_id,this.sequence=e.sequence,this.sequence_ledger=e.sequence_ledger,this.sequence_time=e.sequence_time,this.subentry_count=e.subentry_count,this.home_domain=e.home_domain,this.inflation_destination=e.inflation_destination,this.last_modified_ledger=e.last_modified_ledger,this.last_modified_time=e.last_modified_time,this.thresholds=e.thresholds,this.flags=e.flags,this.balances=e.balances,this.signers=e.signers,this.data_attr=e.data_attr,this.sponsor=e.sponsor,this.num_sponsoring=e.num_sponsoring,this.num_sponsored=e.num_sponsored}accountId(){return this._baseAccount.accountId()}sequenceNumber(){return this._baseAccount.sequenceNumber()}incrementSequenceNumber(){this._baseAccount.incrementSequenceNumber(),this.sequence=this._baseAccount.sequenceNumber()}}class ws 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}}const As=32;function Ss(e){}function bs(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=Ss,onError:n=Ss,onRetry:r=Ss,onComment:o}=e,s=[];let i,a,c=!0,u="",l=0;function d(e){let n=0;if(-1===e.indexOf("\r")){let r=e.indexOf("\n",n);for(;-1!==r;){if(n===r){l>0&&t({id:i,event:a,data:u}),i=void 0,u="",l=0,a=void 0,n=r+1,r=e.indexOf("\n",n);continue}const o=e.charCodeAt(n);if(vs(e,n,o)){const o=e.charCodeAt(n+5)===As?n+6:n+5,s=e.slice(o,r);if(0===l&&10===e.charCodeAt(r+1)){t({id:i,event:a,data:s}),i=void 0,u="",a=void 0,n=r+2,r=e.indexOf("\n",n);continue}u=0===l?s:`${u}\n${s}`,l++}else Ts(e,n,o)?a=e.slice(e.charCodeAt(n+6)===As?n+7:n+6,r)||void 0:p(e,n,r);n=r+1,r=e.indexOf("\n",n)}return e.slice(n)}for(;n<e.length;){const t=e.indexOf("\r",n),r=e.indexOf("\n",n);let o=-1;if(-1!==t&&-1!==r?o=t<r?t:r:-1!==t?o=t===e.length-1?-1:t:-1!==r&&(o=r),-1===o)break;p(e,n,o),n=o+1,13===e.charCodeAt(n-1)&&10===e.charCodeAt(n)&&n++}return e.slice(n)}function p(e,n,r){if(n===r)return l>0&&t({id:i,event:a,data:u}),i=void 0,u="",l=0,void(a=void 0);const s=e.charCodeAt(n);if(vs(e,n,s)){const t=e.charCodeAt(n+5)===As?n+6:n+5,o=e.slice(t,r);return u=0===l?o:`${u}\n${o}`,void l++}if(Ts(e,n,s))return void(a=e.slice(e.charCodeAt(n+6)===As?n+7:n+6,r)||void 0);if(105===s&&100===e.charCodeAt(n+1)&&58===e.charCodeAt(n+2)){const t=e.slice(e.charCodeAt(n+3)===As?n+4:n+3,r);return void(i=t.includes("\0")?void 0:t)}if(58===s){if(o){const t=e.slice(n,r);o(t.slice(e.charCodeAt(n+1)===As?2:1))}return}const c=e.slice(n,r),d=c.indexOf(":");if(-1===d)return void h(c,"",c);const p=c.slice(0,d),f=c.charCodeAt(d+1)===As?2:1;h(p,c.slice(d+f),c)}function h(e,t,o){switch(e){case"event":a=t||void 0;break;case"data":u=0===l?t:`${u}\n${t}`,l++;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new ws(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new ws(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){if(c&&(c=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){const t=d(e);return void(""!==t&&s.push(t))}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return void s.push(e);s.push(e);const t=s.join("");s.length=0;const n=d(t);""!==n&&s.push(n)},reset:function(e={}){if(e.consume&&s.length>0){const e=s.join("");p(e,0,e.length)}c=!0,i=void 0,u="",l=0,a=void 0,s.length=0}}}function vs(e,t,n){return 100===n&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function Ts(e,t,n){return 101===n&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class Es 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(Is(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Is(this),t)}}function ks(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(ks).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${ks(e.cause)}`:e.message:`${e}`}function Is(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Cs,Bs,xs,Rs,_s,Ps,Os,Us,Ls,Ns,Vs,Fs,Ds,Ms,qs,Hs,Gs,$s,Xs,Ks,Ws,Zs,zs,js=e=>{throw TypeError(e)},Ys=(e,t,n)=>t.has(e)||js("Cannot "+n),Js=(e,t,n)=>(Ys(e,t,"read from private field"),n?n.call(e):t.get(e)),Qs=(e,t,n)=>t.has(e)?js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ei=(e,t,n,r)=>(Ys(e,t,"write to private field"),t.set(e,n),n),ti=(e,t,n)=>(Ys(e,t,"access private method"),n);class ni extends EventTarget{constructor(e,t){var n,r;super(),Qs(this,Ms),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Qs(this,Cs),Qs(this,Bs),Qs(this,xs),Qs(this,Rs),Qs(this,_s),Qs(this,Ps),Qs(this,Os),Qs(this,Us,null),Qs(this,Ls),Qs(this,Ns),Qs(this,Vs,null),Qs(this,Fs,null),Qs(this,Ds,null),Qs(this,Hs,async e=>{var t;Js(this,Ns).reset();const{body:n,redirected:r,status:o,headers:s}=e;if(204===o)return ti(this,Ms,Ws).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(ei(this,xs,r?new URL(e.url):void 0),200!==o)return void ti(this,Ms,Ws).call(this,`Non-200 status code (${o})`,o);if(!(s.get("content-type")||"").startsWith("text/event-stream"))return void ti(this,Ms,Ws).call(this,'Invalid content type, expected "text/event-stream"',o);if(Js(this,Cs)===this.CLOSED)return;ei(this,Cs,this.OPEN);const i=new Event("open");if(null==(t=Js(this,Ds))||t.call(this,i),this.dispatchEvent(i),"object"!=typeof n||!n||!("getReader"in n))return ti(this,Ms,Ws).call(this,"Invalid response body, expected a web ReadableStream",o),void this.close();const a=new TextDecoder,c=n.getReader();let u=!0;do{const{done:e,value:t}=await c.read();t&&Js(this,Ns).feed(a.decode(t,{stream:!e})),e&&(u=!1,Js(this,Ns).reset(),ti(this,Ms,Zs).call(this))}while(u)}),Qs(this,Gs,e=>{ei(this,Ls,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&ti(this,Ms,Zs).call(this,ks(e))}),Qs(this,Xs,e=>{"string"==typeof e.id&&ei(this,Us,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Js(this,xs)?Js(this,xs).origin:Js(this,Bs).origin,lastEventId:e.id||""});Js(this,Fs)&&(!e.event||"message"===e.event)&&Js(this,Fs).call(this,t),this.dispatchEvent(t)}),Qs(this,Ks,e=>{ei(this,Ps,e)}),Qs(this,zs,()=>{ei(this,Os,void 0),Js(this,Cs)===this.CONNECTING&&ti(this,Ms,qs).call(this)});try{if(e instanceof URL)ei(this,Bs,e);else{if("string"!=typeof e)throw new Error("Invalid URL");ei(this,Bs,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")}ei(this,Ns,bs({onEvent:Js(this,Xs),onRetry:Js(this,Ks)})),ei(this,Cs,this.CONNECTING),ei(this,Ps,3e3),ei(this,_s,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),ei(this,Rs,null!=(r=null==t?void 0:t.withCredentials)&&r),ti(this,Ms,qs).call(this)}get readyState(){return Js(this,Cs)}get url(){return Js(this,Bs).href}get withCredentials(){return Js(this,Rs)}get onerror(){return Js(this,Vs)}set onerror(e){ei(this,Vs,e)}get onmessage(){return Js(this,Fs)}set onmessage(e){ei(this,Fs,e)}get onopen(){return Js(this,Ds)}set onopen(e){ei(this,Ds,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(){Js(this,Os)&&clearTimeout(Js(this,Os)),Js(this,Cs)!==this.CLOSED&&(Js(this,Ls)&&Js(this,Ls).abort(),ei(this,Cs,this.CLOSED),ei(this,Ls,void 0))}}Cs=new WeakMap,Bs=new WeakMap,xs=new WeakMap,Rs=new WeakMap,_s=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Us=new WeakMap,Ls=new WeakMap,Ns=new WeakMap,Vs=new WeakMap,Fs=new WeakMap,Ds=new WeakMap,Ms=new WeakSet,qs=function(){ei(this,Cs,this.CONNECTING),ei(this,Ls,new AbortController),Js(this,_s)(Js(this,Bs),ti(this,Ms,$s).call(this)).then(Js(this,Hs)).catch(Js(this,Gs))},Hs=new WeakMap,Gs=new WeakMap,$s=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Js(this,Us)?{"Last-Event-ID":Js(this,Us)}:void 0},cache:"no-store",signal:null==(e=Js(this,Ls))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Xs=new WeakMap,Ks=new WeakMap,Ws=function(e,t){var n;Js(this,Cs)!==this.CLOSED&&ei(this,Cs,this.CLOSED);const r=new Es("error",{code:t,message:e});null==(n=Js(this,Vs))||n.call(this,r),this.dispatchEvent(r)},Zs=function(e,t){var n;if(Js(this,Cs)===this.CLOSED)return;ei(this,Cs,this.CONNECTING);const r=new Es("error",{code:t,message:e});null==(n=Js(this,Vs))||n.call(this,r),this.dispatchEvent(r),ei(this,Os,setTimeout(Js(this,zs),Js(this,Ps)))},zs=new WeakMap,ni.CONNECTING=0,ni.OPEN=1,ni.CLOSED=2,Object.defineProperty(ni,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});const ri="16.0.1",oi={};function si(e){return Math.floor(e/1e3)}function ii(e){const t=oi[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;const{serverTime:n,localTimeRecorded:r}=t,o=si((new Date).getTime());return o-r>300?null:o-r+n}function ai(e){return Array.isArray(e)?e.join(","):e.toString()}const ci=["transaction"];class ui{url;filter;originalSegments;neighborRoot;httpClient;constructor(e,t,n=""){this.url=new URL(e),this.filter=[],this.originalSegments=this.url.pathname.split("/").filter(e=>e.length>0),this.neighborRoot=n,this.httpClient=t}setPath(...e){const t=e.flatMap(e=>e.split("/").filter(e=>e.length>0));this.url.pathname=this.originalSegments.concat(t).join("/")}call(){return this.checkFilter(),this._sendNormalRequest(this.url).then(e=>this._parseResponse(e))}stream(e={}){this.checkFilter();const t=new URL(this.url);t.searchParams.set("X-Client-Name","js-stellar-sdk"),t.searchParams.set("X-Client-Version",ri);const{headers:n}=this.httpClient.defaults;if(n){["X-App-Name","X-App-Version"].forEach(e=>{let r;if(n instanceof Headers)r=n.get(e)??void 0;else if(Array.isArray(n)){const t=n.find(([t])=>t===e);r=t?.[1]}else r=n[e];r&&t.searchParams.set(e,r)})}let r,o;const s=()=>{o=setTimeout(()=>{r?.close(),r=i()},e.reconnectTimeout||15e3)},i=()=>{try{r=new ni(t.toString())}catch(t){e.onerror&&e.onerror(t)}if(s(),!r)return r;let n=!1;const a=()=>{n||(clearTimeout(o),r.close(),i(),n=!0)},c=n=>{if("close"===n.type)return void a();const r=n.data?this._parseRecord(JSON.parse(n.data)):n;r.paging_token&&t.searchParams.set("cursor",r.paging_token),clearTimeout(o),s(),void 0!==e.onmessage&&e.onmessage(r)},u=t=>{e.onerror&&e.onerror(t)};return r.addEventListener?(r.addEventListener("message",c.bind(this)),r.addEventListener("error",u.bind(this)),r.addEventListener("close",a.bind(this))):(r.onmessage=c.bind(this),r.onerror=u.bind(this)),r};return i(),()=>{clearTimeout(o),r?.close()}}cursor(e){return this.url.searchParams.set("cursor",e),this}limit(e){return this.url.searchParams.set("limit",e.toString()),this}order(e){return this.url.searchParams.set("order",e),this}join(e){return this.url.searchParams.set("join",e),this}forEndpoint(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}checkFilter(){if(this.filter.length>=2)throw new I("Too many filters specified",this.filter);if(1===this.filter.length){const e=this.originalSegments.concat(this.filter[0]);this.url.pathname=e.join("/")}}_requestFnForLink(e){return async(t={})=>{let n;n=e.templated?new URL(function(e,t,n){const r=[],o=e.replace(/\{\?([^}]+)\}/g,(e,t)=>(r.push(...t.split(",")),"")).replace(/\{([^?][^}]*)\}/g,(e,n)=>{const r=t[n];return void 0===r?"":encodeURIComponent(ai(r))}),s=new URL(o,n);return r.forEach(e=>{const n=t[e];void 0!==n&&s.searchParams.set(e,ai(n))}),s.toString()}(e.href,t),this.url):new URL(e.href,this.url);const r=await this._sendNormalRequest(n);return this._parseResponse(r)}}_parseRecord(e){return e._links?(Object.keys(e._links).forEach(t=>{const n=e._links[t];let r=!1;if(void 0!==e[t]&&(e[`${t}_attr`]=e[t],r=!0),r&&ci.indexOf(t)>=0){const n=this._parseRecord(e[t]);e[t]=async()=>n}else e[t]=this._requestFnForLink(n)}),e):e}async _sendNormalRequest(e){const t=new URL(e);return t.protocol=this.url.protocol,t.host=this.url.host,this.httpClient.get(t.toString()).then(e=>e.data).catch(this._handleNetworkError)}_parseResponse(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}_toCollectionPage(e){for(let t=0;t<e._embedded.records.length;t+=1)e._embedded.records[t]=this._parseRecord(e._embedded.records[t]);return{records:e._embedded.records,next:async()=>{const t=await this._sendNormalRequest(new URL(e._links.next.href,this.url));return this._toCollectionPage(t)},prev:async()=>{const t=await this._sendNormalRequest(new URL(e._links.prev.href,this.url));return this._toCollectionPage(t)}}}async _handleNetworkError(e){return e.response&&e.response.status?404===e.response.status?Promise.reject(new k(e.response.statusText??"Not Found",e.response.data)):Promise.reject(new E(e.response.statusText??"Unknown",e.response.data)):Promise.reject(new Error(e.message))}}class li extends ui{constructor(e,t){super(e,t),this.setPath("accounts")}accountId(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forSigner(e){return this.url.searchParams.set("signer",e),this}forAsset(e){return this.url.searchParams.set("asset",`${e}`),this}sponsor(e){return this.url.searchParams.set("sponsor",e),this}forLiquidityPool(e){return this.url.searchParams.set("liquidity_pool",e),this}}class di extends ui{constructor(e,t){super(e,t),this.setPath("assets")}forCode(e){return this.url.searchParams.set("asset_code",e),this}forIssuer(e){return this.url.searchParams.set("asset_issuer",e),this}}class pi extends ui{constructor(e,t){super(e,t),this.setPath("claimable_balances")}claimableBalance(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}sponsor(e){return this.url.searchParams.set("sponsor",e),this}claimant(e){return this.url.searchParams.set("claimant",e),this}asset(e){return this.url.searchParams.set("asset",e.toString()),this}}class hi extends ui{constructor(e,t){super(e,t,"effects"),this.setPath("effects")}forAccount(e){return this.forEndpoint("accounts",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}forOperation(e){return this.forEndpoint("operations",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}}class fi extends ui{constructor(e,t,n){super(e,t),this.setPath("friendbot"),this.url.searchParams.set("addr",n)}}class mi extends ui{constructor(e,t){super(e,t),this.setPath("ledgers")}ledger(e){return this.filter.push(["ledgers",e.toString()]),this}}class gi extends ui{constructor(e,t){super(e,t),this.setPath("liquidity_pools")}forAssets(...e){const t=e.map(e=>e.toString()).join(",");return this.url.searchParams.set("reserves",t),this}forAccount(e){return this.url.searchParams.set("account",e),this}liquidityPoolId(e){if(!e.match(/[a-fA-F0-9]{64}/))throw new TypeError(`${e} does not look like a liquidity pool ID`);const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e.toLowerCase()]),t}}class yi extends ui{constructor(e,t){super(e,t,"offers"),this.setPath("offers")}offer(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}buying(e){const t=e.getIssuer();return e.isNative()||void 0===t?this.url.searchParams.set("buying_asset_type","native"):(this.url.searchParams.set("buying_asset_type",e.getAssetType()),this.url.searchParams.set("buying_asset_code",e.getCode()),this.url.searchParams.set("buying_asset_issuer",t)),this}selling(e){const t=e.getIssuer();return e.isNative()||void 0===t?this.url.searchParams.set("selling_asset_type","native"):(this.url.searchParams.set("selling_asset_type",e.getAssetType()),this.url.searchParams.set("selling_asset_code",e.getCode()),this.url.searchParams.set("selling_asset_issuer",t)),this}sponsor(e){return this.url.searchParams.set("sponsor",e),this}seller(e){return this.url.searchParams.set("seller",e),this}}class wi extends ui{constructor(e,t){super(e,t,"operations"),this.setPath("operations")}operation(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}forClaimableBalance(e){return this.forEndpoint("claimable_balances",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}class Ai extends ui{constructor(e,t,n,r){super(e,t),this.setPath("order_book");const o=n.getIssuer();n.isNative()||void 0===o?this.url.searchParams.set("selling_asset_type","native"):(this.url.searchParams.set("selling_asset_type",n.getAssetType()),this.url.searchParams.set("selling_asset_code",n.getCode()),this.url.searchParams.set("selling_asset_issuer",o));const s=r.getIssuer();r.isNative()||void 0===s?this.url.searchParams.set("buying_asset_type","native"):(this.url.searchParams.set("buying_asset_type",r.getAssetType()),this.url.searchParams.set("buying_asset_code",r.getCode()),this.url.searchParams.set("buying_asset_issuer",s))}}class Si extends ui{constructor(e,t){super(e,t,"payments"),this.setPath("payments")}forAccount(e){return this.forEndpoint("accounts",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forTransaction(e){return this.forEndpoint("transactions",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}class bi extends ui{constructor(e,t,n,r,o){if(super(e,t),this.setPath("paths/strict-receive"),"string"==typeof n)this.url.searchParams.set("source_account",n);else{const e=n.map(e=>e.isNative()?"native":`${e.getCode()}:${e.getIssuer()}`).join(",");this.url.searchParams.set("source_assets",e)}this.url.searchParams.set("destination_amount",o);const s=r.getIssuer();r.isNative()||void 0===s?this.url.searchParams.set("destination_asset_type","native"):(this.url.searchParams.set("destination_asset_type",r.getAssetType()),this.url.searchParams.set("destination_asset_code",r.getCode()),this.url.searchParams.set("destination_asset_issuer",s))}}class vi extends ui{constructor(e,t,n,r,o){super(e,t),this.setPath("paths/strict-send");const s=n.getIssuer();if(n.isNative()?this.url.searchParams.set("source_asset_type","native"):void 0!==s&&(this.url.searchParams.set("source_asset_type",n.getAssetType()),this.url.searchParams.set("source_asset_code",n.getCode()),this.url.searchParams.set("source_asset_issuer",s)),this.url.searchParams.set("source_amount",r),"string"==typeof o)this.url.searchParams.set("destination_account",o);else{const e=o.map(e=>e.isNative()?"native":`${e.getCode()}:${e.getIssuer()}`).join(",");this.url.searchParams.set("destination_assets",e)}}}const Ti=[6e4,3e5,9e5,36e5,864e5,6048e5];class Ei extends ui{constructor(e,t,n,r,o,s,i,a){super(e,t),this.setPath("trade_aggregations");const c=n.getIssuer();n.isNative()||void 0===c?this.url.searchParams.set("base_asset_type","native"):(this.url.searchParams.set("base_asset_type",n.getAssetType()),this.url.searchParams.set("base_asset_code",n.getCode()),this.url.searchParams.set("base_asset_issuer",c));const u=r.getIssuer();if(r.isNative()||void 0===u?this.url.searchParams.set("counter_asset_type","native"):(this.url.searchParams.set("counter_asset_type",r.getAssetType()),this.url.searchParams.set("counter_asset_code",r.getCode()),this.url.searchParams.set("counter_asset_issuer",u)),"number"!=typeof o||"number"!=typeof s)throw new I("Invalid time bounds",[o,s]);if(this.url.searchParams.set("start_time",o.toString()),this.url.searchParams.set("end_time",s.toString()),!this.isValidResolution(i))throw new I("Invalid resolution",i);if(this.url.searchParams.set("resolution",i.toString()),!this.isValidOffset(a,i))throw new I("Invalid offset",a);this.url.searchParams.set("offset",a.toString())}isValidResolution(e){return Ti.some(t=>t===e)}isValidOffset(e,t){const n=36e5;return!(e>t||e>=24*n||e%n!==0)}}class ki extends ui{constructor(e,t){super(e,t,"trades"),this.setPath("trades")}forAssetPair(e,t){const n=e.getIssuer();e.isNative()||void 0===n?this.url.searchParams.set("base_asset_type","native"):(this.url.searchParams.set("base_asset_type",e.getAssetType()),this.url.searchParams.set("base_asset_code",e.getCode()),this.url.searchParams.set("base_asset_issuer",n));const r=t.getIssuer();return t.isNative()||void 0===r?this.url.searchParams.set("counter_asset_type","native"):(this.url.searchParams.set("counter_asset_type",t.getAssetType()),this.url.searchParams.set("counter_asset_code",t.getCode()),this.url.searchParams.set("counter_asset_issuer",r)),this}forOffer(e){return this.url.searchParams.set("offer_id",e),this}forType(e){return this.url.searchParams.set("trade_type",e),this}forAccount(e){return this.forEndpoint("accounts",e)}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}}class Ii extends ui{constructor(e,t){super(e,t,"transactions"),this.setPath("transactions")}transaction(e){const t=new ui(new URL(this.url),this.httpClient);return t.filter.push([e]),t}forAccount(e){return this.forEndpoint("accounts",e)}forClaimableBalance(e){return this.forEndpoint("claimable_balances",e)}forLedger(e){return this.forEndpoint("ledgers",e.toString())}forLiquidityPool(e){return this.forEndpoint("liquidity_pools",e)}includeFailed(e){return this.url.searchParams.set("include_failed",e.toString()),this}}function Ci(e){return new tr(e).div(1e7).toString()}var Bi,xi=Object.freeze({__proto__:null,AccountResponse:ys,get HorizonApi(){return is},SERVER_TIME_MAP:oi,Server:class{serverURL;httpClient;constructor(e,t={}){this.serverURL=new URL(e);const n=void 0===t.allowHttp?_.isAllowHttp():t.allowHttp,r={};if(t.appName&&(r["X-App-Name"]=t.appName),t.appVersion&&(r["X-App-Version"]=t.appVersion),t.authToken&&(r["X-Auth-Token"]=t.authToken),t.headers&&Object.assign(r,t.headers),this.httpClient=function(e){const t=v({headers:{...e,"X-Client-Name":"js-stellar-sdk","X-Client-Version":ri}});return t.interceptors.response.use(e=>{const t=e.config.url;if(!t)return e;const n=new URL(t),r=n.port,o=r?`${n.hostname}:${r}`:n.hostname;let s=0;if(e.headers instanceof Headers){const t=e.headers.get("date");t&&(s=si(Date.parse(t)))}else if("object"==typeof e.headers&&"date"in e.headers){const t=e.headers;"string"==typeof t.date&&(s=si(Date.parse(t.date)))}const i=si((new Date).getTime());return Number.isNaN(s)||(oi[o]={serverTime:s,localTimeRecorded:i}),e}),t}(r),"https:"!==this.serverURL.protocol&&!n)throw new Error("Cannot connect to insecure horizon server")}async fetchTimebounds(e,t=!1){const n=this.serverURL.port,r=ii(n?`${this.serverURL.hostname}:${n}`:this.serverURL.hostname);return r?{minTime:0,maxTime:r+e}:t?{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+e}:(await this.httpClient.get(this.serverURL.toString()),this.fetchTimebounds(e,!0))}async fetchBaseFee(){const e=await this.feeStats();return parseInt(e.last_ledger_base_fee,10)||100}async feeStats(){const e=new ui(this.serverURL,this.httpClient);return e.filter.push(["fee_stats"]),e.call()}async root(){return new ui(this.serverURL,this.httpClient).call()}async submitTransaction(e,t={skipMemoRequiredCheck:!1}){t.skipMemoRequiredCheck||await this.checkMemoRequired(e);const n=encodeURIComponent(e.toEnvelope().toXDR().toString("base64")),r=new URL(this.serverURL);return r.pathname=r.pathname.split("/").concat(["transactions"]).filter(e=>e.length>0).join("/"),this.httpClient.post(r.toString(),`tx=${n}`,{timeout:6e4,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{if(!e.data.result_xdr)return e.data;const t=se.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();let n,r;return t.length&&(n=t.map((e,t)=>{if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;let n=new tr(0),o=new tr(0);const s=e.value().value().success(),i=s.offersClaimed().map(e=>{const t=e.value();let r="";switch(e.switch()){case se.ClaimAtomType.claimAtomTypeV0():r=wn.encodeEd25519PublicKey(t.sellerEd25519());break;case se.ClaimAtomType.claimAtomTypeOrderBook():r=wn.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error(`Invalid offer result type: ${e.switch()}`)}const s=new tr(t.amountBought().toString()),i=new tr(t.amountSold().toString());n=n.plus(i),o=o.plus(s);const a=In.fromOperation(t.assetSold()),c=In.fromOperation(t.assetBought()),u={type:a.getAssetType(),assetCode:a.getCode(),issuer:a.getIssuer()},l={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:u,amountSold:Ci(i),assetBought:l,amountBought:Ci(s)}}),a=s.offer().switch().name;let c;if("function"==typeof s.offer().value&&s.offer().value()){const e=s.offer().value();c={offerId:e.offerId().toString(),selling:{},buying:{},amount:Ci(e.amount().toString()),price:{n:e.price().n(),d:e.price().d()}};const t=In.fromOperation(e.selling());c.selling={type:t.getAssetType(),assetCode:t.getCode(),issuer:t.getIssuer()};const n=In.fromOperation(e.buying());c.buying={type:n.getAssetType(),assetCode:n.getCode(),issuer:n.getIssuer()}}return{offersClaimed:i,effect:a,operationIndex:t,currentOffer:c,amountBought:Ci(n),amountSold:Ci(o),isFullyOpen:!i.length&&"manageOfferDeleted"!==a,wasPartiallyFilled:!!i.length&&"manageOfferDeleted"!==a,wasImmediatelyFilled:!!i.length&&"manageOfferDeleted"===a,wasImmediatelyDeleted:!i.length&&"manageOfferDeleted"===a}}).filter(e=>!!e)),{...e.data,offerResults:r?n:void 0}}).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new C(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}async submitAsyncTransaction(e,t={skipMemoRequiredCheck:!1}){t.skipMemoRequiredCheck||await this.checkMemoRequired(e);const n=encodeURIComponent(e.toEnvelope().toXDR().toString("base64")),r=new URL(this.serverURL);return r.pathname=r.pathname.split("/").concat(["transactions_async"]).filter(e=>e.length>0).join("/"),this.httpClient.post(r.toString(),`tx=${n}`,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>e.data).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new C(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}accounts(){return new li(this.serverURL,this.httpClient)}claimableBalances(){return new pi(this.serverURL,this.httpClient)}ledgers(){return new mi(this.serverURL,this.httpClient)}transactions(){return new Ii(this.serverURL,this.httpClient)}offers(){return new yi(this.serverURL,this.httpClient)}orderbook(e,t){return new Ai(this.serverURL,this.httpClient,e,t)}trades(){return new ki(this.serverURL,this.httpClient)}operations(){return new wi(this.serverURL,this.httpClient)}liquidityPools(){return new gi(this.serverURL,this.httpClient)}strictReceivePaths(e,t,n){return new bi(this.serverURL,this.httpClient,e,t,n)}strictSendPaths(e,t,n){return new vi(this.serverURL,this.httpClient,e,t,n)}payments(){return new Si(this.serverURL,this.httpClient)}effects(){return new hi(this.serverURL,this.httpClient)}friendbot(e){return new fi(this.serverURL,this.httpClient,e)}assets(){return new di(this.serverURL,this.httpClient)}async loadAccount(e){const t=await this.accounts().accountId(e).call();return new ys(t)}tradeAggregation(e,t,n,r,o,s){return new Ei(this.serverURL,this.httpClient,e,t,n,r,o,s)}async checkMemoRequired(e){if(e instanceof co&&(e=e.innerTransaction),"none"!==e.memo.type)return;const t=new Set;for(let n=0;n<e.operations.length;n+=1){const r=e.operations[n];switch(r.type){case"payment":case"pathPaymentStrictReceive":case"pathPaymentStrictSend":case"accountMerge":break;default:continue}const o=r.destination;if(!t.has(o)&&(t.add(o),!o.startsWith("M")))try{if("MQ=="===(await this.loadAccount(o)).data_attr["config.memo_required"])throw new B("account requires memo",o,n)}catch(e){if(e instanceof B)throw e;if(!(e instanceof k))throw e;continue}}}},get ServerApi(){return hs},getCurrentServerTime:ii});(e=>{var t;function n(e){return"transactionData"in e}(t=e.GetTransactionStatus||(e.GetTransactionStatus={})).SUCCESS="SUCCESS",t.NOT_FOUND="NOT_FOUND",t.FAILED="FAILED",e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=n,e.isSimulationRestore=function(e){return n(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}})(Bi||(Bi={}));async function Ri(e,t,n,r=null){const o=await e.post(t,{jsonrpc:"2.0",id:1,method:n,params:r});if(s=o.data,i="error",Object.prototype.hasOwnProperty.call(s,i))throw o.data.error;return o.data?.result;var s,i}function _i(e){const{errorResultXdr:t,diagnosticEventsXdr:n}=e;return delete e.errorResultXdr,delete e.diagnosticEventsXdr,t?{...e,...void 0!==n&&n.length>0&&{diagnosticEvents:n.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))},errorResult:se.TransactionResult.fromXDR(t,"base64")}:{...e}}function Pi(e){const t=se.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),n={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:se.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:se.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:t,events:{contractEventsXdr:(e.events?.contractEventsXdr??[]).map(e=>e.map(e=>se.ContractEvent.fromXDR(e,"base64"))),transactionEventsXdr:(e.events?.transactionEventsXdr??[]).map(e=>se.TransactionEvent.fromXDR(e,"base64"))}};switch(t.switch()){case 3:case 4:{const e=t.value();null!==e.sorobanMeta()&&(n.returnValue=e.sorobanMeta()?.returnValue()??void 0)}}return e.diagnosticEventsXdr&&(n.diagnosticEventsXdr=e.diagnosticEventsXdr.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))),n}function Oi(e){return{status:e.status,txHash:e.txHash,...Pi(e)}}function Ui(e){return{latestLedger:e.latestLedger,oldestLedger:e.oldestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor,events:(e.events??[]).map(e=>{const t={...e};return delete t.contractId,{...t,...""!==e.contractId&&{contractId:new go(e.contractId)},topic:(e.topic??[]).map(e=>se.ScVal.fromXDR(e,"base64")),value:se.ScVal.fromXDR(e.value,"base64")}})}}function Li(e){return{latestLedger:e.latestLedger,entries:(e.entries??[]).map(e=>{if(!e.key||!e.xdr)throw new TypeError(`invalid ledger entry: ${JSON.stringify(e)}`);return{lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:se.LedgerKey.fromXDR(e.key,"base64"),val:se.LedgerEntryData.fromXDR(e.xdr,"base64"),...void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq}}})}}function Ni(e){if(!Bi.isSimulationRaw(e))return e;const t={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:e.events?.map(e=>se.DiagnosticEvent.fromXDR(e,"base64"))??[]};return"string"==typeof e.error?{...t,error:e.error}:function(e,t){const n={...t,transactionData:new fo(e.transactionData),minResourceFee:e.minResourceFee,...(e.results?.length??0)>0&&{result:e.results.map(e=>({auth:(e.auth??[]).map(e=>se.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:e.xdr?se.ScVal.fromXDR(e.xdr,"base64"):se.ScVal.scvVoid()}))[0]},...(e.stateChanges?.length??0)>0&&{stateChanges:e.stateChanges?.map(e=>({type:e.type,key:se.LedgerKey.fromXDR(e.key,"base64"),before:e.before?se.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?se.LedgerEntry.fromXDR(e.after,"base64"):null}))}};return e.restorePreamble&&""!==e.restorePreamble.transactionData?{...n,restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new fo(e.restorePreamble.transactionData)}}:n}(e,t)}function Vi(e){if(!e.metadataXdr||!e.headerXdr){let t;throw t=e.metadataXdr||e.headerXdr?e.metadataXdr?"headerXdr":"metadataXdr":"metadataXdr and headerXdr",new TypeError(`invalid ledger missing fields: ${t}`)}const t=se.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64"),n=se.LedgerHeaderHistoryEntry.fromXDR(e.headerXdr,"base64");return{hash:e.hash,sequence:e.sequence,ledgerCloseTime:e.ledgerCloseTime,metadataXdr:t,headerXdr:n}}function Fi(e){const t=se.LedgerHeader.fromXDR(e.headerXdr,"base64"),n=se.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64");let r;if(e.metadataXdr||e.headerXdr?e.metadataXdr?e.headerXdr||(r="headerXdr"):r="metadataXdr":r="metadataXdr and headerXdr",r)throw new TypeError(`invalid getLatestLedger response missing fields: ${r}`);return{id:e.id,sequence:e.sequence,protocolVersion:e.protocolVersion,closeTime:e.closeTime,headerXdr:t,metadataXdr:n}}function Di(e,t){if("innerTransaction"in e)return Di(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");const n=Ni(t);if(!Bi.isSimulationSuccess(n))throw new Error(`simulation incorrect: ${JSON.stringify(n)}`);let r;try{r=BigInt(e.fee)}catch{r=BigInt(0)}const o=e.toEnvelope().v1().tx().ext().value();o&&r-o.resourceFee().toBigInt()>BigInt(0)&&(r-=o.resourceFee().toBigInt());const s=Ro.cloneFrom(e,{fee:r.toString(),sorobanData:n.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){s.clearOperations();const t=e.operations[0],r=t.auth??[];s.addOperation(Qr.invokeHostFunction({source:t.source,func:t.func,auth:r.length>0?r:n.result.auth}))}return s}var Mi=(e=>(e.Temporary="temporary",e.Persistent="persistent",e))(Mi||{});const qi=e=>1e3;class Hi{serverURL;httpClient;constructor(e,t={}){var n;if(this.serverURL=new URL(e),this.httpClient=(n=t.headers,v({headers:{...n,"X-Client-Name":"js-stellar-sdk","X-Client-Version":"16.0.1"}})),"https:"!==this.serverURL.protocol&&!t.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")}async getAccount(e){const t=await this.getAccountEntry(e);return new uo(e,t.seqNum().toString())}async getAccountEntry(e){const t=se.LedgerKey.account(new se.LedgerKeyAccount({accountId:Tn.fromPublicKey(e).xdrPublicKey()}));try{return(await this.getLedgerEntry(t)).val.account()}catch{throw new Error(`Account not found: ${e}`)}}async getTrustline(e,t){const n=se.LedgerKey.trustline(new se.LedgerKeyTrustLine({accountId:Tn.fromPublicKey(e).xdrAccountId(),asset:t.toTrustLineXDRObject()}));try{return(await this.getLedgerEntry(n)).val.trustLine()}catch{throw new Error(`Trustline for ${t.getCode()}:${t.getIssuer()} not found for ${e}`)}}async getClaimableBalance(e){let t;if(wn.isValidClaimableBalance(e)){const n=wn.decodeClaimableBalance(e),r=fe.Buffer.concat([fe.Buffer.from("\0\0\0"),n.subarray(0,1)]);t=se.ClaimableBalanceId.fromXDR(fe.Buffer.concat([r,n.subarray(1)]))}else if(e.match(/[a-f0-9]{72}/i))t=se.ClaimableBalanceId.fromXDR(e,"hex");else{if(!e.match(/[a-f0-9]{64}/i))throw new TypeError(`expected 72-char hex ID or strkey, not ${e}`);t=se.ClaimableBalanceId.fromXDR(e.padStart(72,"0"),"hex")}const n=se.LedgerKey.claimableBalance(new se.LedgerKeyClaimableBalance({balanceId:t}));try{return(await this.getLedgerEntry(n)).val.claimableBalance()}catch{throw new Error(`Claimable balance ${e} not found`)}}async getAssetBalance(e,t,n){let r=e;if("string"==typeof e)r=e;else if(e instanceof Xr)r=e.toString();else{if(!(e instanceof go))throw new TypeError(`invalid address: ${e}`);r=e.toString()}if(wn.isValidEd25519PublicKey(r)){const[e,n]=await Promise.all([this.getTrustline(r,t),this.getLatestLedger()]);return{latestLedger:n.sequence,balanceEntry:{amount:e.balance().toString(),authorized:Boolean(1&e.flags()),clawback:Boolean(4&e.flags()),authorizedToMaintainLiabilities:Boolean(2&e.flags()),revocable:Boolean(2&e.flags())}}}if(wn.isValidContract(r))return this.getSACBalance(r,t,n);throw new Error(`invalid address: ${e}`)}async getHealth(){return Ri(this.httpClient,this.serverURL.toString(),"getHealth")}async getContractData(e,t,n="persistent"){let r,o;if("string"==typeof e)r=new go(e).address().toScAddress();else if(e instanceof Xr)r=e.toScAddress();else{if(!(e instanceof go))throw new TypeError(`unknown contract type: ${e}`);r=e.address().toScAddress()}switch(n){case"temporary":o=se.ContractDataDurability.temporary();break;case"persistent":o=se.ContractDataDurability.persistent();break;default:throw new TypeError(`invalid durability: ${n}`)}const s=se.LedgerKey.contractData(new se.LedgerKeyContractData({key:t,contract:r,durability:o}));try{return await this.getLedgerEntry(s)}catch{throw{code:404,message:`Contract data not found for ${Xr.fromScAddress(r).toString()} with key ${t.toXDR("base64")} and durability: ${n}`}}}async getContractWasmByContractId(e){const t=new go(e).getFootprint(),n=await this.getLedgerEntries(t);if(!n.entries.length||!n.entries[0]?.val)return Promise.reject({code:404,message:"Could not obtain contract hash from server"});const r=n.entries[0].val.contractData().val().instance().executable().wasmHash();return this.getContractWasmByHash(r)}async getContractWasmByHash(e,t=void 0){const n="string"==typeof e?fe.Buffer.from(e,t):e,r=se.LedgerKey.contractCode(new se.LedgerKeyContractCode({hash:n})),o=await this.getLedgerEntries(r);if(!o.entries.length||!o.entries[0]?.val)return Promise.reject({code:404,message:"Could not obtain contract wasm from server"});return o.entries[0].val.contractCode().code()}getLedgerEntries(...e){return this._getLedgerEntries(...e).then(Li)}_getLedgerEntries(...e){return Ri(this.httpClient,this.serverURL.toString(),"getLedgerEntries",{keys:e.map(e=>e.toXDR("base64"))})}async getLedgerEntry(e){const t=await this._getLedgerEntries(e).then(Li);if(1!==t.entries.length)throw new Error(`failed to find an entry for key ${e.toXDR("base64")}`);return t.entries[0]}async pollTransaction(e,t){const n=(t?.attempts??0)<1?30:t?.attempts??30;let r;for(let o=1;o<=n;o++){if(r=await this.getTransaction(e),r.status!==Bi.GetTransactionStatus.NOT_FOUND)return r;await P.sleep((t?.sleepStrategy??qi)(o))}return r}async getTransaction(e){return this._getTransaction(e).then(t=>{const n={};t.status!==Bi.GetTransactionStatus.NOT_FOUND&&Object.assign(n,Pi(t));return{status:t.status,txHash:e,latestLedger:t.latestLedger,latestLedgerCloseTime:t.latestLedgerCloseTime,oldestLedger:t.oldestLedger,oldestLedgerCloseTime:t.oldestLedgerCloseTime,...n}})}async _getTransaction(e){return Ri(this.httpClient,this.serverURL.toString(),"getTransaction",{hash:e})}async getTransactions(e){return this._getTransactions(e).then(e=>({transactions:(e.transactions||[]).map(Oi),latestLedger:e.latestLedger,latestLedgerCloseTimestamp:e.latestLedgerCloseTimestamp,oldestLedger:e.oldestLedger,oldestLedgerCloseTimestamp:e.oldestLedgerCloseTimestamp,cursor:e.cursor}))}async _getTransactions(e){return Ri(this.httpClient,this.serverURL.toString(),"getTransactions",e)}async getEvents(e){return this._getEvents(e).then(Ui)}async _getEvents(e){return Ri(this.httpClient,this.serverURL.toString(),"getEvents",{filters:e.filters??[],pagination:{...e.cursor&&{cursor:e.cursor},...e.limit&&{limit:e.limit}},...e.startLedger&&{startLedger:e.startLedger},...e.endLedger&&{endLedger:e.endLedger}})}async getNetwork(){return Ri(this.httpClient,this.serverURL.toString(),"getNetwork")}async getLatestLedger(){return this._getLatestLedger().then(Fi)}async _getLatestLedger(){return Ri(this.httpClient,this.serverURL.toString(),"getLatestLedger")}async simulateTransaction(e,t,n){return this._simulateTransaction(e,t,n).then(Ni)}async _simulateTransaction(e,t,n){return Ri(this.httpClient,this.serverURL.toString(),"simulateTransaction",{transaction:e.toXDR(),authMode:n,...void 0!==t&&{resourceConfig:{instructionLeeway:t.cpuInstructions}}})}async prepareTransaction(e){const t=await this.simulateTransaction(e);if(Bi.isSimulationError(t))throw new Error(t.error);return Di(e,t).build()}async sendTransaction(e){return this._sendTransaction(e).then(_i)}async _sendTransaction(e){return Ri(this.httpClient,this.serverURL.toString(),"sendTransaction",{transaction:e.toXDR()})}async requestAirdrop(e,t){const n="string"==typeof e?e:e.accountId();if(!(t=t||(await this.getNetwork()).friendbotUrl))throw new Error("No friendbot URL configured for current network");try{const r=await this.httpClient.post(`${t}?addr=${encodeURIComponent(n)}`);let o;if(r.data.result_meta_xdr)o=se.TransactionMeta.fromXDR(r.data.result_meta_xdr,"base64");else{const t=await this.getTransaction(r.data.hash);if(t.status!==Bi.GetTransactionStatus.SUCCESS)throw new Error(`Funding account ${e} failed`);o=t.resultMetaXdr}const s=function(e){let t=[];switch(e.switch()){case 0:t=e.operations();break;case 1:case 2:case 3:case 4:t=e.value().operations();break;default:throw new Error("Unexpected transaction meta switch value")}const n=t.flatMap(e=>e.changes()).find(e=>e.switch()===se.LedgerEntryChangeType.ledgerEntryCreated()&&e.created().data().switch()===se.LedgerEntryType.account())?.created()?.data()?.account()?.seqNum()?.toString();if(n)return n;throw new Error("No account created in transaction")}(o);return new uo(n,s)}catch(e){if(400===e.response?.status&&e.response.data?.detail?.includes("createAccountAlreadyExist"))return this.getAccount(n);throw e}}async fundAddress(e,t){if(!wn.isValidEd25519PublicKey(e)&&!wn.isValidContract(e))throw new Error(`Invalid address: ${e}. Expected a Stellar account (G...) or contract (C...) address.`);if(!(t=t||(await this.getNetwork()).friendbotUrl))throw new Error("No friendbot URL configured for current network");try{const n=await this.httpClient.post(`${t}?addr=${encodeURIComponent(e)}`),r=await this.getTransaction(n.data.hash);if(r.status!==Bi.GetTransactionStatus.SUCCESS)throw new Error(`Funding address ${e} failed: transaction status ${r.status}`);return r}catch(e){if(400===e.response?.status)throw new Error(e.response.data?.detail??"Bad Request");throw e}}async getFeeStats(){return Ri(this.httpClient,this.serverURL.toString(),"getFeeStats")}async getVersionInfo(){return Ri(this.httpClient,this.serverURL.toString(),"getVersionInfo")}async getSACBalance(e,t,n){const r=e instanceof Xr?e.toString():e;if(!wn.isValidContract(r))throw new TypeError(`expected contract ID, got ${r}`);const o=n??await this.getNetwork().then(e=>e.passphrase),s=t.contractId(o),i=Eo(["Balance",r],{type:["symbol","address"]}),a=se.LedgerKey.contractData(new se.LedgerKeyContractData({contract:new Xr(s).toScAddress(),durability:se.ContractDataDurability.persistent(),key:i})),c=await this.getLedgerEntries(a);if(0===c.entries.length)return{latestLedger:c.latestLedger};const{lastModifiedLedgerSeq:u,liveUntilLedgerSeq:l,val:d}=c.entries[0];if(d.switch().value!==se.LedgerEntryType.contractData().value)return{latestLedger:c.latestLedger};const p=ko(d.contractData().val());return{latestLedger:c.latestLedger,balanceEntry:{liveUntilLedgerSeq:l,lastModifiedLedgerSeq:u,amount:p.amount.toString(),authorized:p.authorized,clawback:p.clawback}}}async getLedgers(e){return this._getLedgers(e).then(e=>({ledgers:(e.ledgers||[]).map(Vi),latestLedger:e.latestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedger:e.oldestLedger,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor}))}async _getLedgers(e){return Ri(this.httpClient,this.serverURL.toString(),"getLedgers",e)}}var Gi=Object.freeze({__proto__:null,get Api(){return Bi},BasicSleepStrategy:qi,Durability:Mi,LinearSleepStrategy:e=>1e3*e,Server:Hi,assembleTransaction:Di,parseRawEvents:Ui,parseRawSimulation:Ni});class $i{constructor(e){this.value=e}value;unwrapErr(){throw new Error("No error")}unwrap(){return this.value}isOk(){return!0}isErr(){return!1}}class Xi{constructor(e){this.error=e}error;unwrapErr(){return this.error}unwrap(){throw new Error(this.error.message)}isOk(){return!1}isErr(){return!0}}const Ki=300,Wi="GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";const Zi=/Error\(Contract, #(\d+)\)/;function zi(e){const t=new ie.XdrReader(e),n=[];for(;!t.eof;)n.push(se.ScSpecEntry.read(t));return n}async function ji(e,t){return e.publicKey?t.getAccount(e.publicKey):new uo(Wi,"0")}class Yi{constructor(e){this.assembled=e;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.assembled.options;this.server=t??new Hi(o,{allowHttp:n,headers:r})}assembled;server;sendTransactionResponse;getTransactionResponseAll;getTransactionResponse;static Errors={SendFailed:class extends Error{},SendResultOnly:class extends Error{},TransactionStillPending:class extends Error{}};static init=async(e,t)=>{const n=new Yi(e);return await n.send(t)};send=async e=>{if(this.sendTransactionResponse=await this.server.sendTransaction(this.assembled.signed),"PENDING"!==this.sendTransactionResponse.status)throw new Yi.Errors.SendFailed(`Sending the transaction to the network failed!\n${JSON.stringify(this.sendTransactionResponse,null,2)}`);e?.onSubmitted&&e.onSubmitted(this.sendTransactionResponse);const{hash:t}=this.sendTransactionResponse,n=this.assembled.options.timeoutInSeconds??Ki;if(this.getTransactionResponseAll=await async function(e,t,n,r=1.5,o=!1){const s=[];let i=0;if(s.push(await e()),!t(s[s.length-1]))return s;const a=new Date(Date.now()+1e3*n).valueOf();let c=1e3,u=c;for(;Date.now()<a&&t(s[s.length-1]);)i+=1,o&&console.info(`Waiting ${c}ms before trying again (bringing the total wait time to ${u}ms so far, of total ${1e3*n}ms)`),await new Promise(e=>setTimeout(e,c)),c*=r,new Date(Date.now()+c).valueOf()>a&&(c=a-Date.now(),o&&console.info(`was gonna wait too long; new waitTime: ${c}ms`)),u=c+u,s.push(await e(s[s.length-1])),o&&t(s[s.length-1])&&console.info(`${i}. Called ${e}; ${s.length} prev attempts. Most recent: ${JSON.stringify(s[s.length-1],null,2)}`);return s}(async()=>{const n=await this.server.getTransaction(t);return e?.onProgress&&e.onProgress(n),n},e=>e.status===Bi.GetTransactionStatus.NOT_FOUND,n),this.getTransactionResponse=this.getTransactionResponseAll[this.getTransactionResponseAll.length-1],this.getTransactionResponse.status===Bi.GetTransactionStatus.NOT_FOUND)throw new Yi.Errors.TransactionStillPending(`Waited ${n} seconds for transaction to complete, but it did not. Returning anyway. Check the transaction status manually. Sent transaction: ${JSON.stringify(this.sendTransactionResponse,null,2)}\nAll attempts to get the result: ${JSON.stringify(this.getTransactionResponseAll,null,2)}`);return this};get result(){if("getTransactionResponse"in this&&this.getTransactionResponse){if("returnValue"in this.getTransactionResponse)return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue);throw new Error("Transaction failed! Cannot parse result.")}if(this.sendTransactionResponse){const e=this.sendTransactionResponse.errorResult?.result();if(e)throw new Yi.Errors.SendFailed(`Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${e}`);throw new Yi.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`")}throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled.signed)}`)}}class Ji extends Error{}class Qi extends Error{}class ea extends Error{}class ta extends Error{}class na extends Error{}class ra extends Error{}class oa extends Error{}class sa extends Error{}class ia extends Error{}class aa extends Error{}class ca extends Error{}class ua extends Error{}class la extends Error{}class da{constructor(e){this.options=e,this.options.simulate=this.options.simulate??!0;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.options;this.server=t??new Hi(o,{allowHttp:n,headers:r})}options;raw;originalOp;built;simulation;simulationResult;simulationTransactionData;server;signed;static Errors={ExpiredState:Ji,RestorationFailure:Qi,NeedsMoreSignatures:ea,NoSignatureNeeded:ta,NoUnsignedNonInvokerAuthEntries:na,NoSigner:ra,NotYetSimulated:oa,FakeAccount:sa,SimulationFailed:ia,InternalWalletError:aa,ExternalServiceError:ca,InvalidClientRequest:ua,UserRejected:la};toJSON(){return JSON.stringify({method:this.options.method,tx:this.built?.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map(e=>e.toXDR("base64")),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}static validateInvokeContractOp(e,t){if(1!==e.operations.length)throw new Error("Transaction envelope must contain exactly one operation.");const n=e.operations[0];if("invokeHostFunction"!==n.type)throw new Error("Transaction envelope does not contain an invokeHostFunction operation.");const r=n;if("hostFunctionTypeInvokeContract"!==r.func.switch().name)throw new Error("Transaction envelope does not contain an invokeContract host function.");const o=r.func.value();let s,i;try{s=o.contractAddress(),i=o.functionName().toString("utf-8")}catch{throw new Error("Could not extract contract address or method name from the transaction envelope.")}if(!s||!i)throw new Error("Could not extract contract address or method name from the transaction envelope.");const a=Xr.fromScAddress(s).toString();if(a!==t)throw new Error(`Transaction envelope targets contract ${a}, but this Client is configured for ${t}.`);return o}static fromJSON(e,{tx:t,simulationResult:n,simulationTransactionData:r}){const o=new da(e);o.built=Ro.fromXDR(t,e.networkPassphrase);const s=da.validateInvokeContractOp(o.built,e.contractId).functionName().toString("utf-8");if(s!==e.method)throw new Error(`Transaction envelope calls method '${s}', but the provided method is '${e.method}'.`);return o.simulationResult={auth:n.auth.map(e=>se.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:se.ScVal.fromXDR(n.retval,"base64")},o.simulationTransactionData=se.SorobanTransactionData.fromXDR(r,"base64"),o}toXDR(){if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return this.built?.toEnvelope().toXDR("base64")}static fromXDR(e,t,n){const r=se.TransactionEnvelope.fromXDR(t,"base64"),o=Ro.fromXDR(r,e.networkPassphrase),s=da.validateInvokeContractOp(o,e.contractId).functionName().toString("utf-8"),i=new da({...e,method:s,parseResultXdr:e=>n.funcResToNative(s,e)});return i.built=o,i}handleWalletError(e){if(!e)return;const{message:t,code:n}=e,r=`${t}${e.ext?` (${e.ext.join(", ")})`:""}`;switch(n){case-1:throw new da.Errors.InternalWalletError(r);case-2:throw new da.Errors.ExternalServiceError(r);case-3:throw new da.Errors.InvalidClientRequest(r);case-4:throw new da.Errors.UserRejected(r);default:throw new Error(`Unhandled error: ${r}`)}}static build(e){const t=new go(e.contractId);return da.buildWithOp(t.call(e.method,...e.args??[]),e)}static async buildWithOp(e,t){const n=new da(t);n.originalOp=e;const r=await ji(t,n.server);return n.raw=new Ro(r,{fee:t.fee??xo,networkPassphrase:t.networkPassphrase}).setTimeout(t.timeoutInSeconds??Ki).addOperation(e),t.simulate&&await n.simulate(),n}static async buildFootprintRestoreTransaction(e,t,n,r){const o=new da(e);return o.raw=new Ro(n,{fee:r,networkPassphrase:e.networkPassphrase}).setSorobanData(t instanceof fo?t.build():t).addOperation(Qr.restoreFootprint({})).setTimeout(e.timeoutInSeconds??Ki),await o.simulate({restore:!1}),o}simulate=async({restore:e}={})=>{if(!this.built){if(!this.raw)throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");this.built=this.raw.build()}if(e=e??this.options.restore,delete this.simulationResult,delete this.simulationTransactionData,this.simulation=await this.server.simulateTransaction(this.built),e&&Bi.isSimulationRestore(this.simulation)){const e=await ji(this.options,this.server),t=await this.restoreFootprint(this.simulation.restorePreamble,e);if(t.status===Bi.GetTransactionStatus.SUCCESS){const t=this.originalOp?this.originalOp:new go(this.options.contractId).call(this.options.method,...this.options.args??[]);return this.raw=new Ro(e,{fee:this.options.fee??xo,networkPassphrase:this.options.networkPassphrase}).addOperation(t).setTimeout(this.options.timeoutInSeconds??Ki),delete this.built,await this.simulate(),this}throw new da.Errors.RestorationFailure(`Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n${JSON.stringify(t)}`)}return Bi.isSimulationSuccess(this.simulation)&&(this.built=Di(this.built,this.simulation).build()),this};get simulationData(){if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};const e=this.simulation;if(!e)throw new da.Errors.NotYetSimulated("Transaction has not yet been simulated");if(Bi.isSimulationError(e))throw new da.Errors.SimulationFailed(`Transaction simulation failed: "${e.error}"`);if(Bi.isSimulationRestore(e))throw new da.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=e.result??{auth:[],retval:se.ScVal.scvVoid()},this.simulationTransactionData=e.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}get result(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(t){if("object"!=typeof(e=t)||null===e||!("toString"in e))throw t;const n=this.parseError(t.toString());if(n)return n;throw t}var e}parseError(e){if(!this.options.errorTypes)return;const t=e.match(Zi);if(!t)return;const n=parseInt(t[1],10),r=this.options.errorTypes[n];return r?new Xi(r):void 0}sign=async({force:e=!1,signTransaction:t=this.options.signTransaction}={})=>{if(!this.built)throw new Error("Transaction has not yet been simulated");if(!e&&this.isReadCall)throw new da.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");if(!t)throw new da.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");if(!this.options.publicKey)throw new da.Errors.FakeAccount("This transaction was constructed using a default account. Provide a valid publicKey in the AssembledTransactionOptions.");const n=this.needsNonInvokerSigningBy().filter(e=>!e.startsWith("C"));if(n.length)throw new da.Errors.NeedsMoreSignatures(`Transaction requires signatures from ${n}. See \`needsNonInvokerSigningBy\` for details.`);const r=this.options.timeoutInSeconds??Ki;this.built=Ro.cloneFrom(this.built,{fee:this.built.fee,timebounds:void 0,sorobanData:this.simulationData.transactionData}).setTimeout(r).build();const o={networkPassphrase:this.options.networkPassphrase};this.options.address&&(o.address=this.options.address),void 0!==this.options.submit&&(o.submit=this.options.submit),this.options.submitUrl&&(o.submitUrl=this.options.submitUrl);const{signedTxXdr:s,error:i}=await t(this.built.toXDR(),o);this.handleWalletError(i),this.signed=Ro.fromXDR(s,this.options.networkPassphrase)};async send(e){if(!this.signed)throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");return await Yi.init(this,e)}signAndSend=async({force:e=!1,signTransaction:t=this.options.signTransaction,watcher:n}={})=>{if(!this.signed){const n=t||this.options.signTransaction,r=this.options.submit&&n?(e,t)=>n(e,{...t,submit:!1}):t;await this.sign({force:e,signTransaction:r})}return this.send(n)};needsNonInvokerSigningBy=({includeAlreadySigned:e=!1}={})=>{if(!this.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in this.built))throw new Error(`Unexpected Transaction type; no operations: ${JSON.stringify(this.built)}`);const t=this.built.operations[0];return[...new Set((t.auth??[]).map(e=>Go(e.credentials())).filter(t=>null!==t&&(e||"scvVoid"===t.signature().switch().name)).map(e=>Xr.fromScAddress(e.address()).toString()))]};signAuthEntries=async({expiration:e=(async()=>(await this.server.getLatestLedger()).sequence+100)(),signAuthEntry:t=this.options.signAuthEntry,address:n=this.options.publicKey,authorizeEntry:r=Fo}={})=>{if(!this.built)throw new Error("Transaction has not yet been assembled or simulated");if(r===Fo){const e=this.needsNonInvokerSigningBy();if(0===e.length)throw new da.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");if(-1===e.indexOf(n??""))throw new da.Errors.NoSignatureNeeded(`No auth entries for public key "${n}"`);if(!t)throw new da.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`")}const o=this.built.operations[0].auth??[];for(const[s,i]of o.entries()){const a=Go(se.SorobanCredentials.fromXDR(i.credentials().toXDR()));if(null===a)continue;if(Xr.fromScAddress(a.address()).toString()!==n)continue;const c=t??Promise.resolve;o[s]=await r(i,async e=>{const{signedAuthEntry:t,error:r}=await c(e.toXDR("base64"),{address:n});return this.handleWalletError(r),fe.Buffer.from(t,"base64")},await e,this.options.networkPassphrase)}};get isReadCall(){const e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}async restoreFootprint(e,t){if(!this.options.signTransaction)throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");t=t??await ji(this.options,this.server);const n=await da.buildFootprintRestoreTransaction({...this.options},e.transactionData,t,e.minResourceFee),r=await n.signAndSend();if(!r.getTransactionResponse)throw new da.Errors.RestorationFailure(`The attempt at automatic restore failed. \n${JSON.stringify(r)}`);return r.getTransactionResponse}}function pa(e){const t=function(e){const t=new Map,n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let r=0;const o=t=>{if(r+t>e.byteLength)throw new Error("Buffer overflow");const o=new Uint8Array(n,r,t);return r+=t,o};function s(){let e=0,t=0;for(;;){const n=o(1)[0];if(e|=(127&n)<<t,!(128&n))break;if((t+=7)>=32)throw new Error("Invalid WASM value")}return e>>>0}if("0,97,115,109"!==[...o(4)].join())throw new Error("Invalid WASM magic");if("1,0,0,0"!==[...o(4)].join())throw new Error("Invalid WASM version");for(;r<e.byteLength;){const e=o(1)[0],n=s(),i=r;if(0===e){const e=s();if(e>0&&r+e<=i+n){const s=o(e),a=o(n-(r-i));try{const e=new TextDecoder("utf-8",{fatal:!0}).decode(s);a.length>0&&t.set(e,(t.get(e)||[]).concat(a))}catch{}}}r=i+n}return t}(e),n=t.get("contractspecv0");if(!n||0===n.length)throw new Error("Could not obtain contract spec from wasm");return fe.Buffer.from(n[0])}function ha(e){return/^\d+$/.test(e.name().toString())}const fa={U32:{type:"integer",minimum:0,maximum:4294967295},I32:{type:"integer",minimum:-2147483648,maximum:2147483647},U64:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},Timepoint:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},Duration:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:20},I64:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:21},U128:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:39},I128:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:40},U256:{type:"string",pattern:"^([1-9][0-9]*|0)$",minLength:1,maxLength:78},I256:{type:"string",pattern:"^(-?[1-9][0-9]*|0)$",minLength:1,maxLength:79},Address:{type:"string",format:"address",description:"Address can be a public key or contract id"},MuxedAddress:{type:"string",format:"address",description:"Stellar public key with M prefix combining a G address and unique ID"},ScString:{type:"string",description:"ScString is a string"},ScSymbol:{type:"string",description:"ScSymbol is a string"},DataUrl:{type:"string",pattern:"^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$"}};function ma(e){let t;switch(e.switch().value){case se.ScSpecType.scSpecTypeVal().value:t="Val";break;case se.ScSpecType.scSpecTypeBool().value:return{type:"boolean"};case se.ScSpecType.scSpecTypeVoid().value:return{type:"null"};case se.ScSpecType.scSpecTypeError().value:t="Error";break;case se.ScSpecType.scSpecTypeU32().value:t="U32";break;case se.ScSpecType.scSpecTypeI32().value:t="I32";break;case se.ScSpecType.scSpecTypeU64().value:t="U64";break;case se.ScSpecType.scSpecTypeI64().value:t="I64";break;case se.ScSpecType.scSpecTypeTimepoint().value:t="Timepoint";break;case se.ScSpecType.scSpecTypeDuration().value:t="Duration";break;case se.ScSpecType.scSpecTypeU128().value:t="U128";break;case se.ScSpecType.scSpecTypeI128().value:t="I128";break;case se.ScSpecType.scSpecTypeU256().value:t="U256";break;case se.ScSpecType.scSpecTypeI256().value:t="I256";break;case se.ScSpecType.scSpecTypeBytes().value:t="DataUrl";break;case se.ScSpecType.scSpecTypeString().value:t="ScString";break;case se.ScSpecType.scSpecTypeSymbol().value:t="ScSymbol";break;case se.ScSpecType.scSpecTypeAddress().value:t="Address";break;case se.ScSpecType.scSpecTypeMuxedAddress().value:t="MuxedAddress";break;case se.ScSpecType.scSpecTypeOption().value:return ma(e.option().valueType());case se.ScSpecType.scSpecTypeResult().value:return ma(e.result().okType());case se.ScSpecType.scSpecTypeVec().value:return{type:"array",items:ma(e.vec().elementType())};case se.ScSpecType.scSpecTypeMap().value:{const t=e.map();return{type:"array",items:{type:"array",items:[ma(t.keyType()),ma(t.valueType())],minItems:2,maxItems:2}}}case se.ScSpecType.scSpecTypeTuple().value:{const t=e.tuple(),n=t.valueTypes().length,r=n;return{type:"array",items:t.valueTypes().map(ma),minItems:n,maxItems:r}}case se.ScSpecType.scSpecTypeBytesN().value:return{$ref:"#/definitions/DataUrl",maxLength:e.bytesN().n()};case se.ScSpecType.scSpecTypeUdt().value:t=e.udt().name().toString();break}return{$ref:`#/definitions/${t}`}}function ga(e){const t={},n=[];e.forEach(e=>{const r=e.type(),o=e.name().toString();t[o]=ma(r),r.switch().value!==se.ScSpecType.scSpecTypeOption().value&&n.push(o)});const r={properties:t};return n.length>0&&(r.required=n),r}class ya{entries=[];static fromWasm(e){const t=pa(e);return new ya(t)}constructor(e){if(fe.Buffer.isBuffer(e))this.entries=zi(e);else if("string"==typeof e)this.entries=zi(fe.Buffer.from(e,"base64"));else{if(0===e.length)throw new Error("Contract spec must have at least one entry");const t=e[0];this.entries="string"==typeof t?e.map(e=>se.ScSpecEntry.fromXDR(e,"base64")):e}}funcs(){return this.entries.filter(e=>e.switch().value===se.ScSpecEntryKind.scSpecEntryFunctionV0().value).map(e=>e.functionV0())}getFunc(e){const t=this.findEntry(e);if(t.switch().value!==se.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error(`${e} is not a function`);return t.functionV0()}funcArgsToScVals(e,t){return this.getFunc(e).inputs().map(e=>this.nativeToScVal(function(e,t){const n=t.name().toString(),r=Object.entries(e).find(([e])=>e===n);if(!r)throw new Error(`Missing field ${n}`);return r[1]}(t,e),e.type()))}funcResToNative(e,t){const n="string"==typeof t?se.ScVal.fromXDR(t,"base64"):t,r=this.getFunc(e).outputs();if(0===r.length){const e=n.switch();if(e.value!==se.ScValType.scvVoid().value)throw new Error(`Expected void, got ${e.name}`);return null}if(r.length>1)throw new Error("Multiple outputs not supported");const o=r[0];return o.switch().value===se.ScSpecType.scSpecTypeResult().value?n.switch().value===se.ScValType.scvError().value?new Xi({message:n.error().toXDR("base64")}):new $i(this.scValToNative(n,o.result().okType())):this.scValToNative(n,o)}findEntry(e){const t=this.entries.find(t=>t.value().name().toString()===e);if(!t)throw new Error(`no such entry: ${e}`);return t}nativeToScVal(e,t){const n=t.switch(),r=n.value;if(n.value===se.ScSpecType.scSpecTypeUdt().value){const n=t.udt();return this.nativeToUdt(e,n.name().toString())}if(r===se.ScSpecType.scSpecTypeOption().value){const n=t.option();return null==e?se.ScVal.scvVoid():this.nativeToScVal(e,n.valueType())}switch(typeof e){case"object":if(null===e){if(r===se.ScSpecType.scSpecTypeVoid().value)return se.ScVal.scvVoid();throw new TypeError(`Type ${t} was not void, but value was null`)}if(e instanceof se.ScVal)return e;if(e instanceof Xr){if(t.switch().value!==se.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.toScVal()}if(e instanceof go){if(t.switch().value!==se.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.address().toScVal()}if(e instanceof Uint8Array||fe.Buffer.isBuffer(e)){const n=Uint8Array.from(e);switch(r){case se.ScSpecType.scSpecTypeBytesN().value:{const e=t.bytesN();if(n.length!==e.n())throw new TypeError(`expected ${e.n()} bytes, but got ${n.length}`);return se.ScVal.scvBytes(n)}case se.ScSpecType.scSpecTypeBytes().value:return se.ScVal.scvBytes(n);default:throw new TypeError(`invalid type (${t}) specified for Bytes and BytesN`)}}if(Array.isArray(e))switch(r){case se.ScSpecType.scSpecTypeVec().value:{const n=t.vec().elementType();return se.ScVal.scvVec(e.map(e=>this.nativeToScVal(e,n)))}case se.ScSpecType.scSpecTypeTuple().value:{const n=t.tuple().valueTypes();if(e.length!==n.length)throw new TypeError(`Tuple expects ${n.length} values, but ${e.length} were provided`);return se.ScVal.scvVec(e.map((e,t)=>this.nativeToScVal(e,n[t])))}case se.ScSpecType.scSpecTypeMap().value:{const n=t.map(),r=n.keyType(),o=n.valueType();return se.ScVal.scvMap(e.map(e=>{const t=this.nativeToScVal(e[0],r),n=this.nativeToScVal(e[1],o);return new se.ScMapEntry({key:t,val:n})}))}default:throw new TypeError(`Type ${t} was not vec, but value was Array`)}if(e.constructor===Map){if(r!==se.ScSpecType.scSpecTypeMap().value)throw new TypeError(`Type ${t} was not map, but value was Map`);const n=t.map(),o=[],s=e.entries();let i=s.next();for(;!i.done;){const[e,t]=i.value,r=this.nativeToScVal(e,n.keyType()),a=this.nativeToScVal(t,n.valueType());o.push(new se.ScMapEntry({key:r,val:a})),i=s.next()}return se.ScVal.scvMap(o)}if("Object"!==(e.constructor?.name??""))throw new TypeError(`cannot interpret ${e.constructor?.name} value as ScVal (${JSON.stringify(e)})`);throw new TypeError(`Received object ${e} did not match the provided type ${t}`);case"number":case"bigint":switch(r){case se.ScSpecType.scSpecTypeU32().value:if(BigInt(e)<BigInt(se.Uint32.MIN_VALUE)||BigInt(e)>BigInt(se.Uint32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for U32`);return se.ScVal.scvU32(Number(e));case se.ScSpecType.scSpecTypeI32().value:if(BigInt(e)<-BigInt(se.Int32.MIN_VALUE)||BigInt(e)>BigInt(se.Int32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for I32`);return se.ScVal.scvI32(Number(e));case se.ScSpecType.scSpecTypeU64().value:case se.ScSpecType.scSpecTypeI64().value:case se.ScSpecType.scSpecTypeU128().value:case se.ScSpecType.scSpecTypeI128().value:case se.ScSpecType.scSpecTypeU256().value:case se.ScSpecType.scSpecTypeI256().value:case se.ScSpecType.scSpecTypeTimepoint().value:case se.ScSpecType.scSpecTypeDuration().value:{const t=n.name.substring(10).toLowerCase();return new bo(t,e).toScVal()}default:throw new TypeError(`invalid type (${t}) specified for integer`)}case"string":return function(e,t){switch(t.value){case se.ScSpecType.scSpecTypeString().value:return se.ScVal.scvString(e);case se.ScSpecType.scSpecTypeSymbol().value:return se.ScVal.scvSymbol(e);case se.ScSpecType.scSpecTypeAddress().value:case se.ScSpecType.scSpecTypeMuxedAddress().value:return Xr.fromString(e).toScVal();case se.ScSpecType.scSpecTypeU64().value:return new bo("u64",e).toScVal();case se.ScSpecType.scSpecTypeI64().value:return new bo("i64",e).toScVal();case se.ScSpecType.scSpecTypeU128().value:return new bo("u128",e).toScVal();case se.ScSpecType.scSpecTypeI128().value:return new bo("i128",e).toScVal();case se.ScSpecType.scSpecTypeU256().value:return new bo("u256",e).toScVal();case se.ScSpecType.scSpecTypeI256().value:return new bo("i256",e).toScVal();case se.ScSpecType.scSpecTypeBytes().value:case se.ScSpecType.scSpecTypeBytesN().value:return se.ScVal.scvBytes(fe.Buffer.from(e,"base64"));case se.ScSpecType.scSpecTypeTimepoint().value:return se.ScVal.scvTimepoint(new se.Uint64(e));case se.ScSpecType.scSpecTypeDuration().value:return se.ScVal.scvDuration(new se.Uint64(e));default:throw new TypeError(`invalid type ${t.name} specified for string value`)}}(e,n);case"boolean":if(r!==se.ScSpecType.scSpecTypeBool().value)throw TypeError(`Type ${t} was not bool, but value was bool`);return se.ScVal.scvBool(e);case"undefined":if(!t)return se.ScVal.scvVoid();switch(r){case se.ScSpecType.scSpecTypeVoid().value:case se.ScSpecType.scSpecTypeOption().value:return se.ScVal.scvVoid();default:throw new TypeError(`Type ${t} was not void, but value was undefined`)}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError(`failed to convert typeof ${typeof e} (${e})`)}}nativeToUdt(e,t){const n=this.findEntry(t);switch(n.switch()){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError(`expected number for enum ${t}, but got ${typeof e}`);return this.nativeToEnum(e,n.udtEnumV0());case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,n.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,n.udtUnionV0());default:throw new Error(`failed to parse udt ${t}`)}}nativeToUnion(e,t){const n=e.tag,r=t.cases().find(e=>e.value().name().toString()===n);if(!r)throw new TypeError(`no such enum entry: ${n} in ${t}`);const o=se.ScVal.scvSymbol(n);switch(r.switch()){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return se.ScVal.scvVec([o]);case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const n=r.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==n.length)throw new TypeError(`union ${t} expects ${n.length} values, but got ${e.values.length}`);const r=e.values.map((e,t)=>this.nativeToScVal(e,n[t]));return r.unshift(o),se.ScVal.scvVec(r)}throw new Error(`failed to parse union case ${r} with ${e}`)}default:throw new Error(`failed to parse union ${t} with ${e}`)}}nativeToStruct(e,t){const n=t.fields();if(n.some(ha)){if(!n.every(ha))throw new Error("mixed numeric and non-numeric field names are not allowed");return se.ScVal.scvVec(n.map((t,r)=>this.nativeToScVal(e[r],n[r].type())))}return se.ScVal.scvMap(n.map(t=>{const n=t.name().toString();return new se.ScMapEntry({key:this.nativeToScVal(n,se.ScSpecTypeDef.scSpecTypeSymbol()),val:this.nativeToScVal(e[n],t.type())})}))}nativeToEnum(e,t){if(t.cases().some(t=>t.value()===e))return se.ScVal.scvU32(e);throw new TypeError(`no such enum entry: ${e} in ${t}`)}scValStrToNative(e,t){return this.scValToNative(se.ScVal.fromXDR(e,"base64"),t)}scValToNative(e,t){const n=t.switch(),r=n.value;if(r===se.ScSpecType.scSpecTypeOption().value)return e.switch().value===se.ScValType.scvVoid().value?null:this.scValToNative(e,t.option().valueType());if(r===se.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case se.ScValType.scvVoid().value:return null;case se.ScValType.scvU64().value:case se.ScValType.scvI64().value:case se.ScValType.scvTimepoint().value:case se.ScValType.scvDuration().value:case se.ScValType.scvU128().value:case se.ScValType.scvI128().value:case se.ScValType.scvU256().value:case se.ScValType.scvI256().value:return To(e);case se.ScValType.scvVec().value:if(r===se.ScSpecType.scSpecTypeVec().value){const n=t.vec();return(e.vec()??[]).map(e=>this.scValToNative(e,n.elementType()))}if(r===se.ScSpecType.scSpecTypeTuple().value){const n=t.tuple().valueTypes();return(e.vec()??[]).map((e,t)=>this.scValToNative(e,n[t]))}throw new TypeError(`Type ${t} was not vec, but ${e} is`);case se.ScValType.scvAddress().value:return Xr.fromScVal(e).toString();case se.ScValType.scvMap().value:{const o=e.map()??[];if(r===se.ScSpecType.scSpecTypeMap().value){const e=t.map(),n=e.keyType(),r=e.valueType();return o.map(e=>[this.scValToNative(e.key(),n),this.scValToNative(e.val(),r)])}throw new TypeError(`ScSpecType ${n.name} was not map, but ${JSON.stringify(e,null,2)} is`)}case se.ScValType.scvBool().value:case se.ScValType.scvU32().value:case se.ScValType.scvI32().value:case se.ScValType.scvBytes().value:return e.value();case se.ScValType.scvString().value:case se.ScValType.scvSymbol().value:if(r!==se.ScSpecType.scSpecTypeString().value&&r!==se.ScSpecType.scSpecTypeSymbol().value)throw new Error(`ScSpecType ${n.name} was not string or symbol, but ${JSON.stringify(e,null,2)} is`);return e.value()?.toString();default:throw new TypeError(`failed to convert ${JSON.stringify(e,null,2)} to native type from type ${n.name}`)}}scValUdtToNative(e,t){const n=this.findEntry(t.name().toString());switch(n.switch()){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,n.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,n.udtUnionV0());default:throw new Error(`failed to parse udt ${t.name().toString()}: ${n}`)}}unionToNative(e,t){const n=e.vec();if(!n)throw new Error(`${JSON.stringify(e,null,2)} is not a vec`);if(0===n.length&&0!==t.cases.length)throw new Error(`${e} has length 0, but the there are at least one case in the union`);const r=n[0].sym().toString();if(n[0].switch().value!==se.ScValType.scvSymbol().value)throw new Error(`${n[0]} is not a symbol`);const o=t.cases().find(function(e){return function(t){switch(t.switch().value){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(r));if(!o)throw new Error(`failed to find entry ${r} in union ${t.name().toString()}`);const s={tag:r};if(o.switch().value===se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){const e=o.tupleCase().type().map((e,t)=>this.scValToNative(n[t+1],e));s.values=e}return s}structToNative(e,t){const n={},r=t.fields();if(r.some(ha)){const t=e.vec()?.map((e,t)=>this.scValToNative(e,r[t].type()));return t}return e.map()?.forEach((e,t)=>{const o=r[t];n[o.name().toString()]=this.scValToNative(e.val(),o.type())}),n}enumToNative(e){if(e.switch().value!==se.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}errorCases(){return this.entries.filter(e=>e.switch().value===se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value).flatMap(e=>e.value().cases())}jsonSchema(e){const t={};this.entries.forEach(e=>{switch(e.switch().value){case se.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:{const n=e.udtEnumV0();t[n.name().toString()]=function(e){const t=e.doc().toString(),n=e.cases(),r=[];n.forEach(e=>{const t=e.name().toString(),n=e.doc().toString();r.push({description:n,title:t,enum:[e.value()],type:"number"})});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case se.ScSpecEntryKind.scSpecEntryUdtStructV0().value:{const n=e.udtStructV0();t[n.name().toString()]=function(e){const t=e.fields();if(t.some(ha)){if(!t.every(ha))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((e,n)=>ma(t[n].type())),minItems:t.length,maxItems:t.length}}const n=e.doc().toString(),{properties:r,required:o}=ga(t);return{description:n,properties:r,required:o,additionalProperties:!1,type:"object"}}(n);break}case se.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:{const n=e.udtUnionV0();t[n.name().toString()]=function(e){const t=e.doc().toString(),n=e.cases(),r=[];n.forEach(e=>{switch(e.switch().value){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:{const t=e.voidCase().name().toString();r.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break}case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:{const t=e.tupleCase(),n=t.name().toString();r.push({type:"object",title:n,properties:{tag:n,values:{type:"array",items:t.type().map(ma)}},required:["tag","values"],additionalProperties:!1})}}});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case se.ScSpecEntryKind.scSpecEntryFunctionV0().value:{const n=e.functionV0(),r=n.name().toString(),{input:o}=function(e){const{properties:t,required:n}=ga(e.inputs()),r={additionalProperties:!1,properties:t,type:"object"};n?.length>0&&(r.required=n);const o={properties:{args:r}},s=e.outputs(),i=s.length>0?ma(s[0]):ma(se.ScSpecTypeDef.scSpecTypeVoid()),a=e.doc().toString();return a.length>0&&(o.description=a),o.additionalProperties=!1,i.additionalProperties=!1,{input:o,output:i}}(n);t[r]=o;break}case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}});const n={$schema:"http://json-schema.org/draft-07/schema#",definitions:{...fa,...t}};return e&&(n.$ref=`#/definitions/${e}`),n}}function wa(e){const t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","enum","implements","interface","let","package","private","protected","public","static","async","await","constructor","null","true","false"].includes(t)?t+"_":/^\d/.test(t)?"_"+t:""===t||/^_+$/.test(t)?"_unnamed":t}function Aa(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Sa(e,t=!1){switch(e.switch()){case se.ScSpecType.scSpecTypeVal():return"any";case se.ScSpecType.scSpecTypeBool():return"boolean";case se.ScSpecType.scSpecTypeVoid():return"null";case se.ScSpecType.scSpecTypeError():return"Error";case se.ScSpecType.scSpecTypeU32():case se.ScSpecType.scSpecTypeI32():return"number";case se.ScSpecType.scSpecTypeU64():case se.ScSpecType.scSpecTypeI64():case se.ScSpecType.scSpecTypeTimepoint():case se.ScSpecType.scSpecTypeDuration():case se.ScSpecType.scSpecTypeU128():case se.ScSpecType.scSpecTypeI128():case se.ScSpecType.scSpecTypeU256():case se.ScSpecType.scSpecTypeI256():return"bigint";case se.ScSpecType.scSpecTypeBytes():case se.ScSpecType.scSpecTypeBytesN():return"Buffer";case se.ScSpecType.scSpecTypeString():case se.ScSpecType.scSpecTypeSymbol():return"string";case se.ScSpecType.scSpecTypeAddress():case se.ScSpecType.scSpecTypeMuxedAddress():return t?"string | Address":"string";case se.ScSpecType.scSpecTypeVec():return`Array<${Sa(e.vec().elementType(),t)}>`;case se.ScSpecType.scSpecTypeMap():return`Map<${Sa(e.map().keyType(),t)}, ${Sa(e.map().valueType(),t)}>`;case se.ScSpecType.scSpecTypeTuple():return`[${e.tuple().valueTypes().map(e=>Sa(e,t)).join(", ")}]`;case se.ScSpecType.scSpecTypeOption():for(;e.option().valueType().switch()===se.ScSpecType.scSpecTypeOption();)e=e.option().valueType();return`${Sa(e.option().valueType(),t)} | null`;case se.ScSpecType.scSpecTypeResult():return`Result<${Sa(e.result().okType(),t)}, ${Sa(e.result().errorType(),t)}>`;case se.ScSpecType.scSpecTypeUdt():return wa(e.udt().name().toString());default:return"unknown"}}function ba(e,t){switch(e.switch()){case se.ScSpecType.scSpecTypeUdt():return void t.typeFileImports.add(wa(e.udt().name().toString()));case se.ScSpecType.scSpecTypeAddress():case se.ScSpecType.scSpecTypeMuxedAddress():return void t.stellarImports.add("Address");case se.ScSpecType.scSpecTypeBytes():case se.ScSpecType.scSpecTypeBytesN():return void(t.needsBufferImport=!0);case se.ScSpecType.scSpecTypeVal():return void t.stellarImports.add("xdr");case se.ScSpecType.scSpecTypeResult():t.stellarContractImports.add("Result");break;case se.ScSpecType.scSpecTypeBool():case se.ScSpecType.scSpecTypeVoid():case se.ScSpecType.scSpecTypeError():case se.ScSpecType.scSpecTypeU32():case se.ScSpecType.scSpecTypeI32():case se.ScSpecType.scSpecTypeU64():case se.ScSpecType.scSpecTypeI64():case se.ScSpecType.scSpecTypeTimepoint():case se.ScSpecType.scSpecTypeDuration():case se.ScSpecType.scSpecTypeU128():case se.ScSpecType.scSpecTypeI128():case se.ScSpecType.scSpecTypeU256():case se.ScSpecType.scSpecTypeI256():case se.ScSpecType.scSpecTypeString():case se.ScSpecType.scSpecTypeSymbol():return}const n=function(e){switch(e.switch()){case se.ScSpecType.scSpecTypeVec():return[e.vec().elementType()];case se.ScSpecType.scSpecTypeMap():return[e.map().keyType(),e.map().valueType()];case se.ScSpecType.scSpecTypeTuple():return e.tuple().valueTypes();case se.ScSpecType.scSpecTypeOption():return[e.option().valueType()];case se.ScSpecType.scSpecTypeResult():return[e.result().okType(),e.result().errorType()];default:return[]}}(e);n.forEach(e=>ba(e,t))}function va(e){const t={typeFileImports:new Set,stellarContractImports:new Set,stellarImports:new Set,needsBufferImport:!1};return e.forEach(e=>ba(e,t)),t}function Ta(e,t){const n=[],r=e.typeFileImports,o=[...e.stellarContractImports,...t?.additionalStellarContractImports||[]],s=[...e.stellarImports,...t?.additionalStellarImports||[]];if(t?.includeTypeFileImports&&r.size>0&&n.push(`import {${Array.from(r).join(", ")}} from './types.js';`),o.length>0){const e=Array.from(new Set(o));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk/contract';`)}if(s.length>0){const e=Array.from(new Set(s));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk';`)}return e.needsBufferImport&&n.push("import { Buffer } from 'buffer';"),n.join("\n")}function Ea(e,t=0){if(""===e.trim())return"";const n=" ".repeat(t);const r=e.replace(/\*\//g,"* /").replace(/@(?!(param|returns?|type|throws?|example|deprecated|see|link|since|author|version|description|summary)\b)/g,"\\@").split("\n").map(e=>`${n} * ${e}`.trimEnd());return`${n}/**\n${r.join("\n")}\n${n} */\n`}const ka="__constructor";class Ia{constructor(e,t){if(this.spec=e,this.options=t,void 0===t.server){const{allowHttp:e,headers:n}=t;t.server=new Hi(t.rpcUrl,{allowHttp:e,headers:n})}this.spec.funcs().forEach(n=>{const r=n.name().toString();if(r===ka)return;const o=(n,o)=>da.build({method:r,args:n&&e.funcArgsToScVals(r,n),...t,...o,errorTypes:e.errorCases().reduce((e,t)=>({...e,[t.value()]:{message:t.doc().toString()}}),{}),parseResultXdr:t=>e.funcResToNative(r,t)});this[wa(r)]=0===e.getFunc(r).inputs().length?e=>o(void 0,e):o})}spec;options;static async deploy(e,t){const{wasmHash:n,salt:r,format:o,fee:s,timeoutInSeconds:i,simulate:a,...c}=t,u=await async function(e,t,n="hex"){if(!t||!t.rpcUrl)throw new TypeError("options must contain rpcUrl");const{rpcUrl:r,allowHttp:o,headers:s}=t,i=new Hi(r,{allowHttp:o,headers:s}),a=await i.getContractWasmByHash(e,n);return ya.fromWasm(a)}(n,c,o),l=Qr.createCustomContract({address:new Xr(t.address||t.publicKey),wasmHash:"string"==typeof n?fe.Buffer.from(n,o??"hex"):n,salt:r,constructorArgs:e?u.funcArgsToScVals(ka,e):[]});return da.buildWithOp(l,{fee:s,timeoutInSeconds:i,simulate:a,...c,contractId:"ignored",method:ka,parseResultXdr:e=>new Ia(u,{...c,contractId:Xr.fromScVal(e).toString()})})}static async fromWasmHash(e,t,n="hex"){if(!t||!t.rpcUrl)throw new TypeError("options must contain rpcUrl");const{rpcUrl:r,allowHttp:o,headers:s}=t,i=t.server??new Hi(r,{allowHttp:o,headers:s}),a=await i.getContractWasmByHash(e,n);return Ia.fromWasm(a,t)}static async fromWasm(e,t){const n=await ya.fromWasm(e);return new Ia(n,t)}static async from(e){if(!e||!e.rpcUrl||!e.contractId)throw new TypeError("options must contain rpcUrl and contractId");const{rpcUrl:t,contractId:n,allowHttp:r,headers:o}=e,s=new Hi(t,{allowHttp:r,headers:o}),i=await s.getContractWasmByContractId(n);return Ia.fromWasm(i,e)}txFromJSON=e=>{const{method:t,...n}=JSON.parse(e);return da.fromJSON({...this.options,method:t,parseResultXdr:e=>this.spec.funcResToNative(t,e)},n)};txFromXDR=e=>da.fromXDR(this.options,e,this.spec)}var Ca=Object.freeze({__proto__:null,AssembledTransaction:da,Client:Ia,DEFAULT_TIMEOUT:Ki,Err:Xi,NULL_ACCOUNT:Wi,Ok:$i,SentTransaction:Yi,Spec:ya,Watcher:class{},basicNodeSigner:(e,t)=>({signTransaction:async(n,r)=>{const o=Ro.fromXDR(n,r?.networkPassphrase||t);return o.sign(e),{signedTxXdr:o.toXDR(),signerAddress:e.publicKey()}},signAuthEntry:async t=>({signedAuthEntry:e.sign(nt(fe.Buffer.from(t,"base64"))).toString("base64"),signerAddress:e.publicKey()})})});class Ba{generate(e){const{contractName:t}=e;return{packageJson:this.generatePackageJson(t),tsConfig:this.generateTsConfig(),gitignore:this.generateGitignore(),readme:this.generateReadme(t)}}generatePackageJson(e){const t={name:e.toLowerCase().replace(/[^a-z0-9-]/g,"-"),version:"0.0.1",description:`Generated TypeScript bindings for ${e} Stellar contract`,type:"module",main:"dist/index.js",types:"dist/index.d.ts",scripts:{build:"tsc"},dependencies:{"@stellar/stellar-sdk":"^16.0.1",buffer:"6.0.3"},devDependencies:{typescript:"^5.6.3"}};return JSON.stringify(t,null,2)}generateTsConfig(){return JSON.stringify({compilerOptions:{target:"ESNext",module:"NodeNext",moduleResolution:"nodenext",declaration:!0,outDir:"./dist",strictNullChecks:!0,skipLibCheck:!0},include:["src/*"]},null,2)}generateGitignore(){return["# Dependencies","node_modules/","","# Build outputs","dist/","*.tgz","","# IDE",".vscode/",".idea/","","# OS",".DS_Store","Thumbs.db","","# Logs","*.log","npm-debug.log*","","# Runtime data","*.pid","*.seed"].join("\n")}generateReadme(e){return[`# ${e} Contract Bindings`,"",`TypeScript bindings for the ${e} Stellar smart contract.`,"","## Installation","","```bash","npm install","```","","## Build","","```bash","npm run build","```","","## Usage","","```typescript",'import { Client } from "./src";',"","const client = new Client({",' contractId: "YOUR_CONTRACT_ID",',' rpcUrl: "https://soroban-testnet.stellar.org:443",',' networkPassphrase: "Test SDF Network ; September 2015",',"});","","// Call contract methods","// const result = await client.methodName();","```","","## Generated Files","","- `src/index.ts` - Entry point exporting the Client","- `src/types.ts` - Type definitions for contract structs, enums, and unions","- `src/contract.ts` - Client implementation","- `tsconfig.json` - TypeScript configuration","- `package.json` - NPM package configuration","","This package was generated using the Js-Stellar-SDK contract binding generator."].join("\n")}}class xa{spec;constructor(e){this.spec=e}generate(){const e=this.spec.entries.map(e=>this.generateEntry(e)).filter(e=>e).join("\n\n");return`${this.generateImports()}\n\n ${e}\n `}generateEntry(e){switch(e.switch()){case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().every((e,t)=>e.name().toString().trim()===t.toString())?this.generateTupleStruct(e.udtStructV0()):this.generateStruct(e.udtStructV0());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.generateUnion(e.udtUnionV0());case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.generateEnum(e.udtEnumV0());case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():return this.generateErrorEnum(e.udtErrorEnumV0());default:return null}}generateImports(){return Ta(va(this.spec.entries.flatMap(e=>{switch(e.switch()){case se.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().map(e=>e.type());case se.ScSpecEntryKind.scSpecEntryUdtUnionV0():return e.udtUnionV0().cases().flatMap(e=>e.switch()===se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0()?e.tupleCase().type():[]);case se.ScSpecEntryKind.scSpecEntryUdtEnumV0():case se.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():default:return[]}})),{includeTypeFileImports:!1})}generateStruct(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Struct: ${t}`,0)}export interface ${t} {\n${e.fields().map(e=>{const t=wa(e.name().toString()),n=Sa(e.type());return`${Ea(e.doc().toString(),2)} ${t}: ${n};`}).join("\n")}\n}`}generateUnion(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Union: ${t}`,0)} export type ${t} =\n${e.cases().map(e=>this.generateUnionCase(e)).map(e=>e.types.length>0?`${Ea(e.doc,2)} { tag: "${Aa(e.name)}"; values: readonly [${e.types.join(", ")}] }`:`${Ea(e.doc,2)} { tag: "${Aa(e.name)}"; values: void }`).join(" |\n")};`}generateEnum(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Enum: ${t}`,0)}export enum ${t} {\n${e.cases().map(e=>{const t=wa(e.name().toString()),n=e.value();return`${Ea(e.doc().toString()||`Enum Case: ${t}`,2)} ${t} = ${n}`}).join(",\n")}\n}`}generateErrorEnum(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Error Enum: ${t}`,0)}export const ${t} = {\n${e.cases().map(e=>this.generateEnumCase(e)).map(e=>`${Ea(e.doc,2)} ${e.value} : { message: "${Aa(e.name)}" }`).join(",\n")}\n}`}generateUnionCase(e){switch(e.switch()){case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():{const t=e.voidCase();return{doc:t.doc().toString(),name:t.name().toString(),types:[]}}case se.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const t=e.tupleCase();return{doc:t.doc().toString(),name:t.name().toString(),types:t.type().map(e=>Sa(e))}}default:throw new Error(`Unknown union case kind: ${e.switch()}`)}}generateEnumCase(e){return{doc:e.doc().toString(),name:e.name().toString(),value:e.value()}}generateTupleStruct(e){const t=wa(e.name().toString());return`${Ea(e.doc().toString()||`Tuple Struct: ${t}`,0)}export type ${t} = readonly [${e.fields().map(e=>Sa(e.type())).join(", ")}];`}}class Ra{spec;constructor(e){this.spec=e}generate(){let e="";try{const t=this.spec.getFunc("__constructor");e=this.generateDeployMethod(t)}catch{e=this.generateDeployMethod(void 0)}const t=this.spec.funcs().filter(e=>"__constructor"!==e.name().toString()).map(e=>this.generateInterfaceMethod(e)).join("\n"),n=this.generateImports(),r=this.spec.entries.map(e=>`"${e.toXDR("base64")}"`),o=this.spec.funcs().filter(e=>"__constructor"!==e.name().toString()).map(e=>this.generateFromJSONMethod(e)).join(",");return`${n}\n\nexport interface Client {\n${t}\n}\n\nexport class Client extends ContractClient {\n constructor(public readonly options: ContractClientOptions) {\n super(\n new Spec([${r.join(", ")}]),\n options\n );\n }\n\n ${e}\n public readonly fromJSON = {\n ${o}\n };\n}`}generateImports(){return Ta(va(this.spec.funcs().flatMap(e=>{const t=e.inputs(),n=e.outputs();return t.map(e=>e.type()).concat(n)})),{includeTypeFileImports:!0,additionalStellarContractImports:["Spec","AssembledTransaction","Client as ContractClient","ClientOptions as ContractClientOptions","MethodOptions"]})}generateInterfaceMethod(e){const t=wa(e.name().toString()),n=e.inputs().map(e=>({name:wa(e.name().toString()),type:Sa(e.type(),!0)})),r=e.outputs().length>0?Sa(e.outputs()[0]):"void";return`${Ea(e.doc().toString(),2)} ${t}(${this.formatMethodParameters(n)}): Promise<AssembledTransaction<${r}>>;`}generateFromJSONMethod(e){return` ${wa(e.name().toString())} : this.txFromJSON<${e.outputs().length>0?Sa(e.outputs()[0]):"void"}>`}generateDeployMethod(e){if(!e){return` static deploy<T = Client>(${this.formatConstructorParameters([])}): Promise<AssembledTransaction<T>> {\n return ContractClient.deploy(null, options);\n }`}const t=e.inputs().map(e=>({name:wa(e.name().toString()),type:Sa(e.type(),!0)}));return` static deploy<T = Client>(${this.formatConstructorParameters(t)}): Promise<AssembledTransaction<T>> {\n return ContractClient.deploy(${t.length>0?`{ ${t.map(e=>e.name).join(", ")} }, `:""}options);\n }`}formatMethodParameters(e){const t=[];if(e.length>0){const n=`{ ${e.map(e=>`${e.name}: ${e.type}`).join("; ")} }`;t.push(`{ ${e.map(e=>e.name).join(", ")} }: ${n}`)}return t.push("options?: MethodOptions"),t.join(", ")}formatConstructorParameters(e){const t=[];if(e.length>0){const n=`{ ${e.map(e=>`${e.name}: ${e.type}`).join("; ")} }`;t.push(`{ ${e.map(e=>e.name).join(", ")} }: ${n}`)}return t.push('options: MethodOptions & Omit<ContractClientOptions, \'contractId\'> & { wasmHash: Buffer | string; salt?: Buffer | Uint8Array; format?: "hex" | "base64"; address?: string; }'),t.join(", ")}}class _a extends Error{constructor(e,t){super(e),this.cause=t,this.name="WasmFetchError"}cause}async function Pa(e,t){try{const n=se.LedgerKey.contractCode(new se.LedgerKeyContractCode({hash:se.Hash.fromXDR(t,"raw")})),r=await e.getLedgerEntries(n);if(!r.entries||0===r.entries.length)throw new _a("WASM not found for the given hash");const o=r.entries[0];if(o.key.switch()!==se.LedgerEntryType.contractCode())throw new _a("Invalid ledger entry type returned");const s=o.val.contractCode();return fe.Buffer.from(s.code())}catch(e){if(e instanceof _a)throw e;throw new _a("Failed to fetch WASM from hash",e)}}async function Oa(e,t){try{const n=new go(t.toString()),r=await e.getLedgerEntries(n.getFootprint());if(!r.entries||0===r.entries.length)throw new _a("Contract instance not found");const o=r.entries[0];if(o.key.switch()!==se.LedgerEntryType.contractData())throw new _a("Invalid ledger entry type returned");const s=o.val.contractData().val().instance();if(function(e){return e.executable().switch()===se.ContractExecutableType.contractExecutableStellarAsset()}(s))return{type:"stellar-asset-contract"};const i=s.executable().wasmHash();return{type:"wasm",wasmBytes:await Pa(e,i)}}catch(e){if(e instanceof _a)throw e;throw new _a("Failed to fetch WASM from contract",e)}}class Ua{spec;constructor(e){this.spec=e}static fromSpec(e){return new Ua(e)}static fromWasm(e){const t=new ya(pa(e));return new Ua(t)}static async fromWasmHash(e,t){const n=await async function(e,t){try{const n=fe.Buffer.from(e,"hex");if(32!==n.length)throw new _a(`Invalid WASM hash length: expected 32 bytes, got ${n.length}`);return{type:"wasm",wasmBytes:await Pa(t,n)}}catch(t){throw new _a(`Failed to fetch WASM from hash ${e}`,t)}}(e,t);if("wasm"!==n.type)throw new Error("Fetched contract is not of type 'wasm'");return Ua.fromWasm(n.wasmBytes)}static async fromContractId(e,t){const n=await async function(e,t){try{if(!wn.isValidContract(e))throw new _a(`Invalid contract ID: ${e}`);const n=Xr.fromString(e);return await Oa(t,n)}catch(t){throw new _a(`Failed to fetch WASM from contract ${e}`,t)}}(e,t);if("wasm"===n.type)return Ua.fromWasm(n.wasmBytes);const r=new ya("AAAAAAAAAYpSZXR1cm5zIHRoZSBhbGxvd2FuY2UgZm9yIGBzcGVuZGVyYCB0byB0cmFuc2ZlciBmcm9tIGBmcm9tYC4KClRoZSBhbW91bnQgcmV0dXJuZWQgaXMgdGhlIGFtb3VudCB0aGF0IHNwZW5kZXIgaXMgYWxsb3dlZCB0byB0cmFuc2ZlcgpvdXQgb2YgZnJvbSdzIGJhbGFuY2UuIFdoZW4gdGhlIHNwZW5kZXIgdHJhbnNmZXJzIGFtb3VudHMsIHRoZSBhbGxvd2FuY2UKd2lsbCBiZSByZWR1Y2VkIGJ5IHRoZSBhbW91bnQgdHJhbnNmZXJyZWQuCgojIEFyZ3VtZW50cwoKKiBgZnJvbWAgLSBUaGUgYWRkcmVzcyBob2xkaW5nIHRoZSBiYWxhbmNlIG9mIHRva2VucyB0byBiZSBkcmF3biBmcm9tLgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIHNwZW5kaW5nIHRoZSB0b2tlbnMgaGVsZCBieSBgZnJvbWAuAAAAAAAJYWxsb3dhbmNlAAAAAAAAAgAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAEAAAALAAAAAAAAAIlSZXR1cm5zIHRydWUgaWYgYGlkYCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBpZGAgLSBUaGUgYWRkcmVzcyBmb3Igd2hpY2ggdG9rZW4gYXV0aG9yaXphdGlvbiBpcyBiZWluZyBjaGVja2VkLgAAAAAAAAphdXRob3JpemVkAAAAAAABAAAAAAAAAAJpZAAAAAAAEwAAAAEAAAABAAAAAAAAA59TZXQgdGhlIGFsbG93YW5jZSBieSBgYW1vdW50YCBmb3IgYHNwZW5kZXJgIHRvIHRyYW5zZmVyL2J1cm4gZnJvbQpgZnJvbWAuCgpUaGUgYW1vdW50IHNldCBpcyB0aGUgYW1vdW50IHRoYXQgc3BlbmRlciBpcyBhcHByb3ZlZCB0byB0cmFuc2ZlciBvdXQgb2YKZnJvbSdzIGJhbGFuY2UuIFRoZSBzcGVuZGVyIHdpbGwgYmUgYWxsb3dlZCB0byB0cmFuc2ZlciBhbW91bnRzLCBhbmQKd2hlbiBhbiBhbW91bnQgaXMgdHJhbnNmZXJyZWQgdGhlIGFsbG93YW5jZSB3aWxsIGJlIHJlZHVjZWQgYnkgdGhlCmFtb3VudCB0cmFuc2ZlcnJlZC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHRvIGJlIGRyYXduIGZyb20uCiogYHNwZW5kZXJgIC0gVGhlIGFkZHJlc3MgYmVpbmcgYXV0aG9yaXplZCB0byBzcGVuZCB0aGUgdG9rZW5zIGhlbGQgYnkKYGZyb21gLgoqIGBhbW91bnRgIC0gVGhlIHRva2VucyB0byBiZSBtYWRlIGF2YWlsYWJsZSB0byBgc3BlbmRlcmAuCiogYGV4cGlyYXRpb25fbGVkZ2VyYCAtIFRoZSBsZWRnZXIgbnVtYmVyIHdoZXJlIHRoaXMgYWxsb3dhbmNlIGV4cGlyZXMuIENhbm5vdApiZSBsZXNzIHRoYW4gdGhlIGN1cnJlbnQgbGVkZ2VyIG51bWJlciB1bmxlc3MgdGhlIGFtb3VudCBpcyBiZWluZyBzZXQgdG8gMC4KQW4gZXhwaXJlZCBlbnRyeSAod2hlcmUgZXhwaXJhdGlvbl9sZWRnZXIgPCB0aGUgY3VycmVudCBsZWRnZXIgbnVtYmVyKQpzaG91bGQgYmUgdHJlYXRlZCBhcyBhIDAgYW1vdW50IGFsbG93YW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJhcHByb3ZlIiwgZnJvbTogQWRkcmVzcywKc3BlbmRlcjogQWRkcmVzc10sIGRhdGEgPSBbYW1vdW50OiBpMTI4LCBleHBpcmF0aW9uX2xlZGdlcjogdTMyXWAAAAAAB2FwcHJvdmUAAAAABAAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAABFleHBpcmF0aW9uX2xlZGdlcgAAAAAAAAQAAAAAAAAAAAAAAJhSZXR1cm5zIHRoZSBiYWxhbmNlIG9mIGBpZGAuCgojIEFyZ3VtZW50cwoKKiBgaWRgIC0gVGhlIGFkZHJlc3MgZm9yIHdoaWNoIGEgYmFsYW5jZSBpcyBiZWluZyBxdWVyaWVkLiBJZiB0aGUKYWRkcmVzcyBoYXMgbm8gZXhpc3RpbmcgYmFsYW5jZSwgcmV0dXJucyAwLgAAAAdiYWxhbmNlAAAAAAEAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAsAAAAAAAABYkJ1cm4gYGFtb3VudGAgZnJvbSBgZnJvbWAuCgpSZWR1Y2VzIGZyb20ncyBiYWxhbmNlIGJ5IHRoZSBhbW91bnQsIHdpdGhvdXQgdHJhbnNmZXJyaW5nIHRoZSBiYWxhbmNlCnRvIGFub3RoZXIgaG9sZGVyJ3MgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAABGJ1cm4AAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAALaQnVybiBgYW1vdW50YCBmcm9tIGBmcm9tYCwgY29uc3VtaW5nIHRoZSBhbGxvd2FuY2Ugb2YgYHNwZW5kZXJgLgoKUmVkdWNlcyBmcm9tJ3MgYmFsYW5jZSBieSB0aGUgYW1vdW50LCB3aXRob3V0IHRyYW5zZmVycmluZyB0aGUgYmFsYW5jZQp0byBhbm90aGVyIGhvbGRlcidzIGJhbGFuY2UuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gYnVybiB0aGUgYW1vdW50IGZyb20gZnJvbSdzIGJhbGFuY2UsIGlmCnRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlciBoYXMKb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZSB3aWxsIGJlCnJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSBidXJuLCBhbmQgaGF2aW5nIGl0cyBhbGxvd2FuY2UKY29uc3VtZWQgZHVyaW5nIHRoZSBidXJuLgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAACWJ1cm5fZnJvbQAAAAAAAAMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAABUUNsYXdiYWNrIGBhbW91bnRgIGZyb20gYGZyb21gIGFjY291bnQuIGBhbW91bnRgIGlzIGJ1cm5lZCBpbiB0aGUKY2xhd2JhY2sgcHJvY2Vzcy4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2UgZnJvbSB3aGljaCB0aGUgY2xhd2JhY2sgd2lsbAp0YWtlIHRva2Vucy4KKiBgYW1vdW50YCAtIFRoZSBhbW91bnQgb2YgdG9rZW5zIHRvIGJlIGNsYXdlZCBiYWNrLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbImNsYXdiYWNrIiwgYWRtaW46IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAACAUmV0dXJucyB0aGUgbnVtYmVyIG9mIGRlY2ltYWxzIHVzZWQgdG8gcmVwcmVzZW50IGFtb3VudHMgb2YgdGhpcyB0b2tlbi4KCiMgUGFuaWNzCgpJZiB0aGUgY29udHJhY3QgaGFzIG5vdCB5ZXQgYmVlbiBpbml0aWFsaXplZC4AAAAIZGVjaW1hbHMAAAAAAAAAAQAAAAQAAAAAAAAA801pbnRzIGBhbW91bnRgIHRvIGB0b2AuCgojIEFyZ3VtZW50cwoKKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSBtaW50ZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgbWludGVkLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbIm1pbnQiLCBhZG1pbjogQWRkcmVzcywgdG86IEFkZHJlc3NdLCBkYXRhCj0gYW1vdW50OiBpMTI4YAAAAAAEbWludAAAAAIAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAFlSZXR1cm5zIHRoZSBuYW1lIGZvciB0aGlzIHRva2VuLgoKIyBQYW5pY3MKCklmIHRoZSBjb250cmFjdCBoYXMgbm90IHlldCBiZWVuIGluaXRpYWxpemVkLgAAAAAAAARuYW1lAAAAAAAAAAEAAAAQAAAAAAAAAQxTZXRzIHRoZSBhZG1pbmlzdHJhdG9yIHRvIHRoZSBzcGVjaWZpZWQgYWRkcmVzcyBgbmV3X2FkbWluYC4KCiMgQXJndW1lbnRzCgoqIGBuZXdfYWRtaW5gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCBoZW5jZWZvcnRoIGJlIHRoZSBhZG1pbmlzdHJhdG9yCm9mIHRoaXMgdG9rZW4gY29udHJhY3QuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsic2V0X2FkbWluIiwgYWRtaW46IEFkZHJlc3NdLCBkYXRhID0KW25ld19hZG1pbjogQWRkcmVzc11gAAAACXNldF9hZG1pbgAAAAAAAAEAAAAAAAAACW5ld19hZG1pbgAAAAAAABMAAAAAAAAAAAAAAEZSZXR1cm5zIHRoZSBhZG1pbiBvZiB0aGUgY29udHJhY3QuCgojIFBhbmljcwoKSWYgdGhlIGFkbWluIGlzIG5vdCBzZXQuAAAAAAAFYWRtaW4AAAAAAAAAAAAAAQAAABMAAAAAAAABUFNldHMgd2hldGhlciB0aGUgYWNjb3VudCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4gSWYKYGF1dGhvcml6ZWRgIGlzIHRydWUsIGBpZGAgc2hvdWxkIGJlIGFibGUgdG8gdXNlIGl0cyBiYWxhbmNlLgoKIyBBcmd1bWVudHMKCiogYGlkYCAtIFRoZSBhZGRyZXNzIGJlaW5nIChkZS0pYXV0aG9yaXplZC4KKiBgYXV0aG9yaXplYCAtIFdoZXRoZXIgb3Igbm90IGBpZGAgY2FuIHVzZSBpdHMgYmFsYW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJzZXRfYXV0aG9yaXplZCIsIGlkOiBBZGRyZXNzXSwgZGF0YSA9ClthdXRob3JpemU6IGJvb2xdYAAAAA5zZXRfYXV0aG9yaXplZAAAAAAAAgAAAAAAAAACaWQAAAAAABMAAAAAAAAACWF1dGhvcml6ZQAAAAAAAAEAAAAAAAAAAAAAAFtSZXR1cm5zIHRoZSBzeW1ib2wgZm9yIHRoaXMgdG9rZW4uCgojIFBhbmljcwoKSWYgdGhlIGNvbnRyYWN0IGhhcyBub3QgeWV0IGJlZW4gaW5pdGlhbGl6ZWQuAAAAAAZzeW1ib2wAAAAAAAAAAAABAAAAEAAAAAAAAAFiVHJhbnNmZXIgYGFtb3VudGAgZnJvbSBgZnJvbWAgdG8gYHRvYC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKd2l0aGRyYXduIGZyb20uCiogYHRvYCAtIFRoZSBhZGRyZXNzIHdoaWNoIHdpbGwgcmVjZWl2ZSB0aGUgdHJhbnNmZXJyZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgdHJhbnNmZXJyZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsidHJhbnNmZXIiLCBmcm9tOiBBZGRyZXNzLCB0bzogQWRkcmVzc10sCmRhdGEgPSBhbW91bnQ6IGkxMjhgAAAAAAAIdHJhbnNmZXIAAAADAAAAAAAAAARmcm9tAAAAEwAAAAAAAAACdG8AAAAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAADMVRyYW5zZmVyIGBhbW91bnRgIGZyb20gYGZyb21gIHRvIGB0b2AsIGNvbnN1bWluZyB0aGUgYWxsb3dhbmNlIHRoYXQKYHNwZW5kZXJgIGhhcyBvbiBgZnJvbWAncyBiYWxhbmNlLiBBdXRob3JpemVkIGJ5IHNwZW5kZXIKKGBzcGVuZGVyLnJlcXVpcmVfYXV0aCgpYCkuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gdHJhbnNmZXIgdGhlIGFtb3VudCBmcm9tIGZyb20ncyBiYWxhbmNlCmlmIHRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlcgpoYXMgb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZQp3aWxsIGJlIHJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSB0cmFuc2ZlciwgYW5kIGhhdmluZyBpdHMKYWxsb3dhbmNlIGNvbnN1bWVkIGR1cmluZyB0aGUgdHJhbnNmZXIuCiogYGZyb21gIC0gVGhlIGFkZHJlc3MgaG9sZGluZyB0aGUgYmFsYW5jZSBvZiB0b2tlbnMgd2hpY2ggd2lsbCBiZQp3aXRoZHJhd24gZnJvbS4KKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSB0cmFuc2ZlcnJlZCB0b2tlbnMuCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSB0cmFuc2ZlcnJlZC4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJ0cmFuc2ZlciIsIGZyb206IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAANdHJhbnNmZXJfZnJvbQAAAAAAAAQAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAABQAAAAAAAAAAAAAAB0FwcHJvdmUAAAAAAQAAAAdhcHByb3ZlAAAAAAQAAAAAAAAABGZyb20AAAATAAAAAQAAAAAAAAAHc3BlbmRlcgAAAAATAAAAAQAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAAARZXhwaXJhdGlvbl9sZWRnZXIAAAAAAAAEAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAIVHJhbnNmZXIAAAABAAAACHRyYW5zZmVyAAAAAwAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAADVRyYW5zZmVyTXV4ZWQAAAAAAAABAAAACHRyYW5zZmVyAAAABAAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAAC3RvX211eGVkX2lkAAAAAAQAAAAAAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAgAAAAUAAAAAAAAAAAAAAARCdXJuAAAAAQAAAARidXJuAAAAAgAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAARNaW50AAAAAQAAAARtaW50AAAAAgAAAAAAAAACdG8AAAAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAhDbGF3YmFjawAAAAEAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAACFNldEFkbWluAAAAAQAAAAlzZXRfYWRtaW4AAAAAAAABAAAAAAAAAAluZXdfYWRtaW4AAAAAAAATAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAANU2V0QXV0aG9yaXplZAAAAAAAAAEAAAAOc2V0X2F1dGhvcml6ZWQAAAAAAAIAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAAAAAAJYXV0aG9yaXplAAAAAAAAAQAAAAAAAAAA");return Ua.fromSpec(r)}generate(e){this.validateOptions(e);const t=new xa(this.spec),n=new Ra(this.spec),r=t.generate(),o=n.generate();let s='export { Client } from "./client.js";';""!==r.trim()&&(s=s.concat('\nexport * from "./types.js";'));const i=new Ba,{packageJson:a,tsConfig:c,readme:u,gitignore:l}=i.generate(e);return{index:s,types:r,client:o,packageJson:a,tsConfig:c,readme:u,gitignore:l}}validateOptions(e){if(!e.contractName||""===e.contractName.trim())throw new Error("contractName is required and cannot be empty")}}e.Account=uo,e.AccountRequiresMemoError=B,e.Address=Xr,e.Asset=In,e.AssetType=En,e.AuthClawbackEnabledFlag=8,e.AuthImmutableFlag=4,e.AuthRequiredFlag=1,e.AuthRevocableFlag=2,e.BASE_FEE=xo,e.BadRequestError=I,e.BadResponseError=C,e.BindingGenerator=Ua,e.Claimant=Rn,e.Config=_,e.Contract=go,e.Federation=Yo,e.FeeBumpTransaction=co,e.Friendbot=ps,e.Horizon=xi,e.Hyper=oe.Hyper,e.Int128=Ao,e.Int256=So,e.Keypair=Tn,e.LiquidityPoolAsset=xn,e.LiquidityPoolFeeV18=30,e.LiquidityPoolId=_n,e.Memo=io,e.MemoHash=oo,e.MemoID=no,e.MemoNone=to,e.MemoReturn=so,e.MemoText=ro,e.MuxedAccount=ho,e.NetworkError=E,e.Networks=Oo,e.NotFoundError=k,e.Operation=Qr,e.ScInt=vo,e.SignerKey=mo,e.Soroban=Uo,e.SorobanDataBuilder=fo,e.StellarBase=Wo,e.StellarToml=ee,e.StrKey=wn,e.TimeoutInfinite=0,e.Transaction=ao,e.TransactionBase=Bn,e.TransactionBuilder=Ro,e.Uint128=yo,e.Uint256=wo,e.UnsignedHyper=oe.UnsignedHyper,e.Utils=P,e.WebAuth=ds,e.XdrLargeInt=bo,e.authorizeEntry=Fo,e.authorizeInvocation=Do,e.buildAuthorizationEntryPreimage=Mo,e.buildInvocationTree=$o,e.buildWithDelegatesEntry=qo,e.cereal=ie,e.contract=Ca,e.decodeAddressToMuxedAccount=Pn,e.encodeMuxedAccount=Un,e.encodeMuxedAccountToAddress=On,e.extractBaseAddress=Ln,e.getLiquidityPoolId=Cn,e.hash=nt,e.httpClient=T,e.humanizeEvents=No,e.nativeToScVal=Eo,e.rpc=Gi,e.scValToBigInt=To,e.scValToNative=ko,e.scvSortedMap=Io,e.sign=cn,e.verify=un,e.walkInvocationTree=Xo,e.xdr=se});
|
|
200
200
|
//# sourceMappingURL=stellar-sdk.min.js.map
|