@stellar/stellar-sdk 16.0.0-rc.2 → 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 +25 -27
- package/dist/stellar-sdk-axios.js.map +1 -1
- package/dist/stellar-sdk-axios.min.js +1 -1
- package/dist/stellar-sdk-axios.min.js.map +1 -1
- package/dist/stellar-sdk.js +26 -28
- package/dist/stellar-sdk.js.map +1 -1
- package/dist/stellar-sdk.min.js +2 -2
- package/dist/stellar-sdk.min.js.map +1 -1
- package/lib/axios/cjs/base/transaction_builder.js +13 -1
- package/lib/axios/cjs/base/transaction_builder.js.map +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/bindings/config.js.map +1 -1
- package/lib/axios/cjs/bindings/wasm_fetcher.js +1 -1
- package/lib/axios/cjs/bindings/wasm_fetcher.js.map +1 -1
- package/lib/axios/cjs/contract/assembled_transaction.js +1 -6
- package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/cjs/contract/client.js.map +1 -1
- package/lib/axios/cjs/contract/spec.js.map +1 -1
- package/lib/axios/cjs/contract/types.js.map +1 -1
- package/lib/axios/cjs/contract/utils.js.map +1 -1
- package/lib/axios/cjs/contract/wasm_spec_parser.js +1 -1
- package/lib/axios/cjs/contract/wasm_spec_parser.js.map +1 -1
- package/lib/axios/cjs/horizon/call_builder.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js.map +1 -1
- package/lib/axios/cjs/http-client/fetch-client.js +1 -1
- package/lib/axios/cjs/http-client/fetch-client.js.map +1 -1
- package/lib/axios/cjs/http-client/types.js.map +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/cjs/rpc/axios.js.map +1 -1
- package/lib/axios/cjs/rpc/jsonrpc.js.map +1 -1
- package/lib/axios/cjs/rpc/server.js +6 -15
- package/lib/axios/cjs/rpc/server.js.map +1 -1
- package/lib/axios/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/axios/esm/base/transaction_builder.js +13 -1
- package/lib/axios/esm/base/transaction_builder.js.map +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/bindings/config.js.map +1 -1
- package/lib/axios/esm/bindings/wasm_fetcher.js +1 -1
- package/lib/axios/esm/bindings/wasm_fetcher.js.map +1 -1
- package/lib/axios/esm/contract/assembled_transaction.js +1 -6
- package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/esm/contract/client.js.map +1 -1
- package/lib/axios/esm/contract/spec.js.map +1 -1
- package/lib/axios/esm/contract/types.d.ts +0 -9
- package/lib/axios/esm/contract/types.js.map +1 -1
- package/lib/axios/esm/contract/utils.js.map +1 -1
- package/lib/axios/esm/contract/wasm_spec_parser.js +1 -1
- package/lib/axios/esm/contract/wasm_spec_parser.js.map +1 -1
- package/lib/axios/esm/horizon/call_builder.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js.map +1 -1
- package/lib/axios/esm/http-client/fetch-client.js +1 -1
- package/lib/axios/esm/http-client/fetch-client.js.map +1 -1
- package/lib/axios/esm/http-client/types.js.map +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/axios/esm/rpc/axios.js.map +1 -1
- package/lib/axios/esm/rpc/jsonrpc.js.map +1 -1
- package/lib/axios/esm/rpc/server.d.ts +2 -7
- package/lib/axios/esm/rpc/server.js +6 -15
- package/lib/axios/esm/rpc/server.js.map +1 -1
- package/lib/axios/esm/webauth/challenge_transaction.js.map +1 -1
- package/lib/cjs/base/transaction_builder.js +13 -1
- package/lib/cjs/base/transaction_builder.js.map +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/bindings/config.js.map +1 -1
- package/lib/cjs/bindings/wasm_fetcher.js +1 -1
- package/lib/cjs/bindings/wasm_fetcher.js.map +1 -1
- package/lib/cjs/contract/assembled_transaction.js +1 -6
- package/lib/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/cjs/contract/client.js.map +1 -1
- package/lib/cjs/contract/spec.js.map +1 -1
- package/lib/cjs/contract/types.js.map +1 -1
- package/lib/cjs/contract/utils.js.map +1 -1
- package/lib/cjs/contract/wasm_spec_parser.js +1 -1
- package/lib/cjs/contract/wasm_spec_parser.js.map +1 -1
- package/lib/cjs/horizon/call_builder.js.map +1 -1
- package/lib/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js.map +1 -1
- package/lib/cjs/http-client/fetch-client.js +1 -1
- package/lib/cjs/http-client/fetch-client.js.map +1 -1
- package/lib/cjs/http-client/types.js.map +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/cjs/rpc/axios.js.map +1 -1
- package/lib/cjs/rpc/jsonrpc.js.map +1 -1
- package/lib/cjs/rpc/server.js +6 -15
- package/lib/cjs/rpc/server.js.map +1 -1
- package/lib/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/esm/base/transaction_builder.js +13 -1
- package/lib/esm/base/transaction_builder.js.map +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/bindings/config.js.map +1 -1
- package/lib/esm/bindings/wasm_fetcher.js +1 -1
- package/lib/esm/bindings/wasm_fetcher.js.map +1 -1
- package/lib/esm/contract/assembled_transaction.js +1 -6
- package/lib/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/esm/contract/client.js.map +1 -1
- package/lib/esm/contract/spec.js.map +1 -1
- package/lib/esm/contract/types.d.ts +0 -9
- package/lib/esm/contract/types.js.map +1 -1
- package/lib/esm/contract/utils.js.map +1 -1
- package/lib/esm/contract/wasm_spec_parser.js +1 -1
- package/lib/esm/contract/wasm_spec_parser.js.map +1 -1
- package/lib/esm/horizon/call_builder.js.map +1 -1
- package/lib/esm/horizon/horizon_api.js.map +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/horizon/horizon_axios_client.js.map +1 -1
- package/lib/esm/http-client/fetch-client.js +1 -1
- package/lib/esm/http-client/fetch-client.js.map +1 -1
- package/lib/esm/http-client/types.js.map +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/lib/esm/rpc/axios.js.map +1 -1
- package/lib/esm/rpc/jsonrpc.js.map +1 -1
- package/lib/esm/rpc/server.d.ts +2 -7
- package/lib/esm/rpc/server.js +6 -15
- package/lib/esm/rpc/server.js.map +1 -1
- package/lib/esm/webauth/challenge_transaction.js.map +1 -1
- package/package.json +2 -5
|
@@ -195,5 +195,5 @@
|
|
|
195
195
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
196
196
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
197
197
|
*/let ju=/^[a-zA-Z0-9-_]+[ \t]*$/;function Wu(e,t,n="="){let r=t-1,o=[],i=e.indexOf(n,t);if(i<0)throw new Iu("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let s=e[t=++r];if(" "!==s&&"\t"!==s)if('"'===s||"'"===s){if(s===e[t+1]&&s===e[t+2])throw new Iu("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Uu(e,t);if(a<0)throw new Iu("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let c=e.slice(a,r<0||r>i?i:r),u=Ou(c);if(u>-1)throw new Iu("newlines are not allowed in keys",{toml:e,ptr:t+r+u});if(c.trimStart())throw new Iu("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(n,a),i<0))throw new Iu("incomplete key-value: cannot find end of key",{toml:e,ptr:t});o.push(zu(e,t,a))}else{r=e.indexOf(".",t);let n=e.slice(t,r<0||r>i?i:r);if(!ju.test(n))throw new Iu("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});o.push(n.trimEnd())}}while(r+1&&r<i);return[o,Lu(e,i+1,!0,!0)]}function Zu(e,t,n,r){let o,i,s=t,a=n,c=!1;for(let t=0;t<e.length;t++){if(t){if(s=c?s[o]:s[o]={},a=(i=a[o]).c,0===r&&(1===i.t||2===i.t))return null;if(2===i.t){let e=s.length-1;s=s[e],a=a[e].c}}if(o=e[t],(c=Object.hasOwn(s,o))&&0===a[o]?.t&&a[o]?.d)return null;c||("__proto__"===o&&(Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&2===r?3:r,d:!1,i:0,c:{}})}if(i=a[o],i.t!==r&&(1!==r||3!==i.t))return null;if(2===r&&(i.d||(i.d=!0,s[o]=[]),s[o].push(s={}),i.c[i.i++]=i={t:1,d:!1,i:0,c:{}}),i.d)return null;if(i.d=!0,1===r)s=c?s[o]:s[o]={};else if(0===r&&c)return null;return[o,s,i.c]}const Ku=102400;class Xu{static async resolve(e,t={}){const{CancelToken:n}=bu,r=void 0===t.allowHttp?Ru.isAllowHttp():t.allowHttp,o=void 0===t.timeout?Ru.getTimeout():t.timeout,i=r?"http":"https";return bu.get(`${i}://${e}/.well-known/stellar.toml`,{maxRedirects:t.allowedRedirects??0,maxContentLength:Ku,cancelToken:o?new n(e=>setTimeout(()=>e(`timeout of ${o}ms exceeded`),o)):void 0,timeout:o}).then(e=>{try{const t=function(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},o={},i=r,s=o;for(let a=Lu(e,0);a<e.length;){if("["===e[a]){let t="["===e[++a],n=Wu(e,a+=+t,"]");if(t){if("]"!==e[n[1]-1])throw new Iu("expected end of table declaration",{toml:e,ptr:n[1]-1});n[1]++}let c=Zu(n[0],r,o,t?2:1);if(!c)throw new Iu("trying to redefine an already defined table or value",{toml:e,ptr:a});s=c[2],i=c[1],a=n[1]}else{let r=Wu(e,a),o=Zu(r[0],i,s,0);if(!o)throw new Iu("trying to redefine an already defined table or value",{toml:e,ptr:a});let c=Gu(e,r[1],void 0,t,n);o[1][o[0]]=c[0],a=c[1]}if(a=Lu(e,a,!0),e[a]&&"\n"!==e[a]&&"\r"!==e[a])throw new Iu("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Lu(e,a)}return r}(e.data);return Promise.resolve(t)}catch(e){return Promise.reject(new Error(`stellar.toml is invalid - Parsing error on line ${e.line}, column ${e.column}: ${e.message}`))}}).catch(e=>{throw e.message.match(/^maxContentLength size/)?new Error("stellar.toml file exceeds allowed size of 102400"):e})}}var Yu,Ju=Object.freeze({__proto__:null,Resolver:Xu,STELLAR_TOML_MAX_SIZE:Ku}),Qu={exports:{}};var el=(Yu||(Yu=1,function(e){var t;t=()=>(()=>{var e={348(e,t,n){const r=n(928);e.exports=r},350(e,t){t.byteLength=function(e){var t=a(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,i=a(e),s=i[0],c=i[1],u=new o(function(e,t,n){return 3*(t+n)/4-n}(0,s,c)),l=0,d=c>0?s-4:s;for(n=0;n<d;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,u[l++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},t.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],s=16383,a=0,c=r-o;a<c;a+=s)i.push(u(e,a,a+s>c?c:a+s));return 1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),i.join("")};for(var n=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=i[s],r[i.charCodeAt(s)]=s;function a(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 c(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function u(e,t,n){for(var r,o=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),o.push(c(r));return o.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},686(e,t,n){const r=n(350),o=n(947),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=c,t.IS=50;const s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(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 d(e)}return u(e,t,n)}function u(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=a(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(K(e,Uint8Array)){const t=new Uint8Array(e);return p(t.buffer,t.byteOffset,t.byteLength)}return h(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(K(e,ArrayBuffer)||e&&K(e.buffer,ArrayBuffer))return p(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(K(e,SharedArrayBuffer)||e&&K(e.buffer,SharedArrayBuffer)))return p(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 c.from(r,t,n);const o=function(e){if(c.isBuffer(e)){const t=0|f(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||X(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.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 l(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 d(e){return l(e),a(e<0?0:0|f(e))}function h(e){const t=e.length<0?0:0|f(e.length),n=a(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function p(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,c.prototype),r}function f(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(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 j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(o)return r?-1:j(e).length;t=(""+t).toLowerCase(),o=!0}}function m(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 I(this,t,n);case"utf8":case"utf-8":return k(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function w(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),X(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=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:b(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):b(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,o){let i,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function v(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(X(r))return s;e[n+s]=r}return s}function A(e,t,n,r){return Z(j(t,e.length-n),e,n,r)}function S(e,t,n,r){return Z(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 T(e,t,n,r){return Z(W(t),e,n,r)}function E(e,t,n,r){return Z(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function k(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=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)&&(i=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&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=C)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=C));return n}(r)}c.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}}(),c.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(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}}),c.poolSize=8192,c.from=function(e,t,n){return u(e,t,n)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array),c.alloc=function(e,t,n){return function(e,t,n){return l(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},c.allocUnsafe=function(e){return d(e)},c.allocUnsafeSlow=function(e){return d(e)},c.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==c.prototype},c.compare=function(e,t){if(K(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=c.from(t,t.offset,t.byteLength)),!c.isBuffer(e)||!c.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,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},c.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}},c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=c.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(K(t,Uint8Array))o+t.length>r.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},c.byteLength=g,c.prototype._isBuffer=!0,c.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)y(this,t,t+1);return this},c.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)y(this,t,t+3),y(this,t+1,t+2);return this},c.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)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},c.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?k(this,0,e):m.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){let e="";const n=t.IS;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},i&&(c.prototype[i]=c.prototype.inspect),c.prototype.compare=function(e,t,n,r,o){if(K(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.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 i=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0);const a=Math.min(i,s),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<a;++e)if(u[e]!==l[e]){i=u[e],s=l[e];break}return i<s?-1:s<i?1:0},c.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},c.prototype.indexOf=function(e,t,n){return w(this,e,t,n,!0)},c.prototype.lastIndexOf=function(e,t,n){return w(this,e,t,n,!1)},c.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 i=!1;for(;;)switch(r){case"hex":return v(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 T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function R(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 x(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 I(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+=Y[e[r]];return o}function B(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 O(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 P(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function L(e,t,n,r,o){H(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){H(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function N(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function F(e,t,n,r,i){return t=+t,n>>>=0,i||N(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function D(e,t,n,r,i){return t=+t,n>>>=0,i||N(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.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,c.prototype),r},c.prototype.readUintLE=c.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},c.prototype.readUintBE=c.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=J(function(e){z(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(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))}),c.prototype.readBigUInt64BE=J(function(e){z(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(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)}),c.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=J(function(e){z(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(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)}),c.prototype.readBigInt64BE=J(function(e){z(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(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)}),c.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||P(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||P(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(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},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(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},c.prototype.writeBigUInt64LE=J(function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=J(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);P(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);P(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(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},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(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},c.prototype.writeBigInt64LE=J(function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=J(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(!c.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},c.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&&!c.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 i=c.isBuffer(e)?e:c.from(e,r),s=i.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%s]}return this};const M={};function V(e,t,n){M[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 q(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 H(e,t,n,r,o,i){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*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new M.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||$(t,e.length-(n+1))}(r,o,i)}function z(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,n){if(Math.floor(e)!==e)throw z(e,n),new M.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}V("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),V("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),V("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=q(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=q(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function j(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.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;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){return r.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 Z(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 K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const Y=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?Q:e}function Q(){throw new Error("BigInt not supported")}},928(e,t,n){n.r(t),n.d(t,{Array:()=>H,Bool:()=>U,Double:()=>P,Enum:()=>j,Float:()=>O,Hyper:()=>R,Int:()=>T,LargeInt:()=>C,Opaque:()=>M,Option:()=>$,Quadruple:()=>L,Reference:()=>W,String:()=>F,Struct:()=>Z,Union:()=>X,UnsignedHyper:()=>B,UnsignedInt:()=>I,VarArray:()=>z,VarOpaque:()=>q,Void:()=>G,XdrReader:()=>c,XdrWriter:()=>d,config:()=>ie});class r extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class s extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var a=n(686).hp;class c{constructor(e){if(!a.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=a.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length<this._index)throw new o("attempt to read outside the boundary of the buffer");const n=4-(e%4||4);if(n>0){for(let e=0;e<n;e++)if(0!==this._buffer[this._index+e])throw new o("invalid padding");this._index+=n}return t}rewind(){this._index=0}remainingBytes(){return this._length-this._index}read(e){const t=this.advance(e);return this._buffer.subarray(t,t+e)}readInt32BE(){return this._buffer.readInt32BE(this.advance(4))}readUInt32BE(){return this._buffer.readUInt32BE(this.advance(4))}readBigInt64BE(){return this._buffer.readBigInt64BE(this.advance(8))}readBigUInt64BE(){return this._buffer.readBigUInt64BE(this.advance(8))}readFloatBE(){return this._buffer.readFloatBE(this.advance(4))}readDoubleBE(){return this._buffer.readDoubleBE(this.advance(8))}ensureInputConsumed(){if(this._index!==this._length)throw new o("invalid XDR contract typecast - source buffer not entirely consumed")}}var u=n(686).hp;const l=8192;class d{constructor(e){"number"==typeof e?e=u.allocUnsafe(e):e instanceof u||(e=u.allocUnsafe(l)),this._buffer=e,this._length=e.length}_buffer;_length;_index=0;alloc(e){const t=this._index;return this._index+=e,this._length<this._index&&this.resize(this._index),t}resize(e){const t=Math.ceil(e/l)*l,n=u.allocUnsafe(t);this._buffer.copy(n,0,0,this._length),this._buffer=n,this._length=t}finalize(){return this._buffer.subarray(0,this._index)}toArray(){return[...this.finalize()]}write(e,t){if("string"==typeof e){const n=this.alloc(t);this._buffer.write(e,n,"utf8")}else{e instanceof u||(e=u.from(e));const n=this.alloc(t);e.copy(this._buffer,n,0,t)}const n=4-(t%4||4);if(n>0){const e=this.alloc(n);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var h=n(686).hp;class p{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new d;return this.write(this,t),w(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const n=new c(b(e,t)),r=this.read(n);return n.ensureInputConsumed(),r}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const n=new d;return this.write(e,n),w(n.finalize(),t)}static fromXDR(e,t="raw"){const n=new c(b(e,t)),r=this.read(n);return n.ensureInputConsumed(),r}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class f extends p{static read(e){throw new s}static write(e,t){throw new s}static isValid(e){return!1}}class g extends p{isValid(e){return!1}}class m extends g{constructor(e){super(),this._maxDepth=e??m.DEFAULT_MAX_DEPTH}static checkDepth(e){if(void 0!==e){if(!Number.isFinite(e))throw new TypeError(`remainingDepth (current remaining decoding depth budget) must be a finite number, got ${typeof e}: ${e}`);if(e<0)throw new o("exceeded max decoding depth")}}}m.DEFAULT_MAX_DEPTH=200,m._maxDepth=m.DEFAULT_MAX_DEPTH;class y extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function w(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new y(t)}}function b(e,t){switch(t){case"raw":return e;case"hex":return h.from(e,"hex");case"base64":return h.from(e,"base64");default:throw new y(t)}}function v(e,t){return null!=e&&(e instanceof t||A(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&A(e,"XdrType"))}function A(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class T extends f{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new r("not a number");if((0|e)!==e)throw new r("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function E(e,t){return`${t?"u":"i"}${e}`}function _(e,t){if(t)return[0n,(1n<<BigInt(e))-1n];const n=1n<<BigInt(e-1);return[0n-n,n-1n]}function k(e,t){const n=BigInt.asIntN(t,e)===e,r=BigInt.asUintN(t,e)===e;if(!n&&!r)throw new RangeError(`slice value ${e} does not fit in ${t} bits`)}T.MAX_VALUE=S,T.MIN_VALUE=2147483648;class C extends f{constructor(e){super(),this._value=function(e,t,n){e instanceof Array?e.length&&e[0]instanceof Array&&(e=e[0]):e=[e];const r=t/e.length;switch(r){case 32:case 64:case 128:case 256:break;default:throw new RangeError(`expected slices to fit in 32/64/128/256 bits, got ${e}`)}try{for(let t=0;t<e.length;t++)"bigint"!=typeof e[t]&&(e[t]=BigInt(e[t].valueOf()))}catch(t){throw new TypeError(`expected bigint-like values, got: ${e} (${t})`)}if(1===e.length){const r=e[0];if(n&&r<0n)throw new RangeError(`expected a positive value, got: ${e}`);const[o,i]=_(t,n);if(r<o||r>i)throw new RangeError(`bigint value ${r} for ${E(t,n)} out of range [${o}, ${i}]`);return r}let o=0n;for(let t=0;t<e.length;t++)k(e[t],r),o|=BigInt.asUintN(r,e[t])<<BigInt(t*r);n||(o=BigInt.asIntN(t,o));const[i,s]=_(t,n);if(o>=i&&o<=s)return o;throw new RangeError(`bigint values [${e}] for ${E(t,n)} out of range [${i}, ${s}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(e){return function(e,t,n){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const r=t/n;if(1===r)return[e];if(n<32||n>128||2!==r&&4!==r&&8!==r)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${n}) combination`);const o=BigInt(n),i=new Array(r);for(let t=0;t<r;t++)i[t]=BigInt.asIntN(n,e),e>>=o;return i}(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t,unsigned:n}=this.prototype;return 64===t?new this(n?e.readBigUInt64BE():e.readBigInt64BE()):new this(...Array.from({length:t/64},()=>e.readBigUInt64BE()).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e<this.MIN_VALUE)throw new r(`${e} is not a ${this.name}`);const{unsigned:n,size:o}=this.prototype;if(64===o)n?t.writeBigUInt64BE(e):t.writeBigInt64BE(e);else{const r=n?e:BigInt.asUintN(o,e);for(let e=o/64-1;e>=0;e--)t.writeBigUInt64BE(r>>BigInt(64*e)&0xffffffffffffffffn)}}static isValid(e){return e instanceof this||"bigint"==typeof e&&e>=this.MIN_VALUE&&e<=this.MAX_VALUE}static fromString(e){return new this(e)}static MAX_VALUE=0n;static MIN_VALUE=0n;static defineIntBoundaries(){const[e,t]=_(this.prototype.size,this.prototype.unsigned);this.MIN_VALUE=e,this.MAX_VALUE=t}}class R extends C{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}R.defineIntBoundaries();const x=4294967295;class I extends f{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=x)||e%1!=0)throw new r("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=x}}I.MAX_VALUE=x,I.MIN_VALUE=0;class B extends C{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}B.defineIntBoundaries();class O extends f{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new r("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class P extends f{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new r("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class L extends f{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class U extends f{static read(e){const t=T.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const n=e?1:0;T.write(n,t)}static isValid(e){return"boolean"==typeof e}}var N=n(686).hp;class F extends g{constructor(e=I.MAX_VALUE){super(),this._maxLength=e}read(e){const t=I.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const n="string"==typeof e?N.byteLength(e,"utf8"):e.length;if(n>this._maxLength)throw new r(`got ${e.length} bytes, max allowed is ${this._maxLength}`);I.write(n,t),t.write(e,n)}isValid(e){return"string"==typeof e?N.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||N.isBuffer(e))&&e.length<=this._maxLength}}var D=n(686).hp;class M extends g{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:n}=e;if(n!==this._length)throw new r(`got ${e.length} bytes, expected ${this._length}`);t.write(e,n)}isValid(e){return D.isBuffer(e)&&e.length===this._length}}var V=n(686).hp;class q extends g{constructor(e=I.MAX_VALUE){super(),this._maxLength=e}read(e){const t=I.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:n}=e;if(e.length>this._maxLength)throw new r(`got ${e.length} bytes, max allowed is ${this._maxLength}`);I.write(n,t),t.write(e,n)}isValid(e){return V.isBuffer(e)&&e.length<=this._maxLength}}class H extends m{constructor(e,t,n=m.DEFAULT_MAX_DEPTH){super(n),this._childType=e,this._length=t}read(e,t=this._maxDepth){if(this._length>e.remainingBytes())throw new o(`Array length ${this._length} exceeds remaining ${e.remainingBytes()} bytes`);m.checkDepth(t);const n=[];for(let r=0;r<this._length;r++)n.push(this._childType.read(e,t-1));return n}write(e,t){if(!n.g.Array.isArray(e))throw new r("value is not array");if(e.length!==this._length)throw new r(`got array of size ${e.length}, expected ${this._length}`);for(const n of e)this._childType.write(n,t)}isValid(e){if(!(e instanceof n.g.Array)||e.length!==this._length)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class z extends m{constructor(e,t=I.MAX_VALUE,n=m.DEFAULT_MAX_DEPTH){super(n),this._childType=e,this._maxLength=t}read(e,t=this._maxDepth){m.checkDepth(t);const n=I.read(e);if(n>this._maxLength)throw new o(`saw ${n} length VarArray, max allowed is ${this._maxLength}`);if(n>e.remainingBytes())throw new o(`VarArray length ${n} exceeds remaining ${e.remainingBytes()} bytes`);const r=[];for(let o=0;o<n;o++)r.push(this._childType.read(e,t-1));return r}write(e,t){if(!(e instanceof Array))throw new r("value is not array");if(e.length>this._maxLength)throw new r(`got array of size ${e.length}, max allowed is ${this._maxLength}`);I.write(e.length,t);for(const n of e)this._childType.write(n,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class $ extends m{constructor(e,t=m.DEFAULT_MAX_DEPTH){super(t),this._childType=e}read(e,t=this._maxDepth){if(m.checkDepth(t),U.read(e))return this._childType.read(e,t-1)}write(e,t){const n=null!=e;U.write(n,t),n&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class G extends f{static read(){}static write(e){if(void 0!==e)throw new r("trying to write value to a void slot")}static isValid(e){return void 0===e}}class j extends f{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=T.read(e),n=this._byValue[t];if(void 0===n)throw new o(`unknown ${this.enumName} member for value ${t}`);return n}static write(e,t){if(!this.isValid(e))throw new r(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);T.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||v(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,n){const r=class extends j{};r.enumName=t,e.results[t]=r,r._members={},r._byValue={};for(const[e,t]of Object.entries(n)){const n=new r(e,t);r._members[e]=n,r._byValue[t]=n,r[e]=()=>n}return r}}class W extends f{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class Z extends m{constructor(e,t){super(t??new.target?._maxDepth),this._attributes=e||{}}static read(e,t=this._maxDepth){m.checkDepth(t);const n={};for(const[r,o]of this._fields)n[r]=o.read(e,t-1);return new this(n,this._maxDepth)}static write(e,t){if(!this.isValid(e))throw new r(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[n,r]of this._fields){const o=e._attributes[n];r.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||v(e,this)}static create(e,t,n,r=m.DEFAULT_MAX_DEPTH){const o=class extends Z{};o.structName=t,o._maxDepth=r,e.results[t]=o;const i=new Array(n.length);for(let t=0;t<n.length;t++){const r=n[t],s=r[0];let a=r[1];a instanceof W&&(a=a.resolve(e)),i[t]=[s,a],o.prototype[s]=K(s)}return o._fields=i,o}}function K(e){return function(t){return void 0!==t&&(this._attributes[e]=t),this._attributes[e]}}class X extends m{constructor(e,t,n){super(n??new.target?._maxDepth),this.set(e,t)}set(e,t){"string"==typeof e&&(e=this.constructor._switchOn.fromName(e)),this._switch=e;const n=this.constructor.armForSwitch(this._switch);this._arm=n,this._armType=n===G?G:this.constructor._arms[n],this._value=t}get(e=this._arm){if(this._arm!==G&&this._arm!==e)throw new TypeError(`${e} not set`);return this._value}switch(){return this._switch}arm(){return this._arm}armType(){return this._armType}value(){return this._value}static armForSwitch(e){const t=this._switches.get(e);if(void 0!==t)return t;if(this._defaultArm)return this._defaultArm;throw new TypeError(`Bad union switch: ${e}`)}static armTypeForArm(e){return e===G?G:this._arms[e]}static read(e,t=this._maxDepth){m.checkDepth(t);const n=this._switchOn.read(e,t-1),r=this.armForSwitch(n),o=r===G?G:this._arms[r];let i;return i=void 0!==o?o.read(e,t-1):r.read(e,t-1),new this(n,i,this._maxDepth)}static write(e,t){if(!this.isValid(e))throw new r(`${e} has union name ${e?.unionName}, not ${this.unionName}: ${JSON.stringify(e)}`);this._switchOn.write(e.switch(),t),e.armType().write(e.value(),t)}static isValid(e){return e?.constructor?.unionName===this.unionName||v(e,this)}static create(e,t,n,r=m.DEFAULT_MAX_DEPTH){const o=class extends X{};o.unionName=t,o._maxDepth=r,e.results[t]=o,n.switchOn instanceof W?o._switchOn=n.switchOn.resolve(e):o._switchOn=n.switchOn,o._switches=new Map,o._arms={};let i=n.defaultArm;i instanceof W&&(i=i.resolve(e)),o._defaultArm=i;for(const[e,t]of n.switches){const n="string"==typeof e?o._switchOn.fromName(e):e;o._switches.set(n,t)}if(void 0!==o._switchOn.values)for(const e of o._switchOn.values())o[e.name]=function(t){return new o(e,t)},o.prototype[e.name]=function(t){return this.set(e,t)};if(n.arms)for(const[t,r]of Object.entries(n.arms))o._arms[t]=r instanceof W?r.resolve(e):r,r!==G&&(o.prototype[t]=function(){return this.get(t)});return o}}class Y extends W{constructor(e){super(),this.name=e}resolve(e){return e.definitions[this.name].resolve(e)}}class J extends W{constructor(e,t,n=!1){super(),this.childReference=e,this.length=t,this.variable=n}resolve(e){let t=this.childReference,n=this.length;return t instanceof W&&(t=t.resolve(e)),n instanceof W&&(n=n.resolve(e)),this.variable?new z(t,n):new H(t,n)}}class Q extends W{constructor(e){super(),this.childReference=e,this.name=e.name}resolve(e){let t=this.childReference;return t instanceof W&&(t=t.resolve(e)),new $(t)}}class ee extends W{constructor(e,t){super(),this.sizedType=e,this.length=t}resolve(e){let t=this.length;return t instanceof W&&(t=t.resolve(e)),new this.sizedType(t)}}class te{constructor(e,t,n){this.constructor=e,this.name=t,this.config=n}resolve(e){return this.name in e.results?e.results[this.name]:this.constructor(e,this.name,this.config)}}function ne(e,t,n){return n instanceof W&&(n=n.resolve(e)),e.results[t]=n,n}function re(e,t,n){return e.results[t]=n,n}class oe{constructor(e){this._destination=e,this._definitions={}}enum(e,t){const n=new te(j.create,e,t);this.define(e,n)}struct(e,t){const n=new te(Z.create,e,t);this.define(e,n)}union(e,t){const n=new te(X.create,e,t);this.define(e,n)}typedef(e,t){const n=new te(ne,e,t);this.define(e,n)}const(e,t){const n=new te(re,e,t);this.define(e,n)}void(){return G}bool(){return U}int(){return T}hyper(){return R}uint(){return I}uhyper(){return B}float(){return O}double(){return P}quadruple(){return L}string(e){return new ee(F,e)}opaque(e){return new ee(M,e)}varOpaque(e){return new ee(q,e)}array(e,t){return new J(e,t)}varArray(e,t){return new J(e,t,!0)}option(e){return new Q(e)}define(e,t){if(void 0!==this._destination[e])throw new i(`${e} is already defined`);this._definitions[e]=t}lookup(e){return new Y(e)}resolve(){for(const e of Object.values(this._definitions))e.resolve({definitions:this._definitions,results:this._destination})}}function ie(e,t={}){if(e){const n=new oe(t);e(n),n.resolve()}return t}},947(e,t){t.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<<a)-1,u=c>>1,l=-7,d=n?o-1:0,h=n?-1:1,p=e[t+d];for(d+=h,i=p&(1<<-l)-1,p>>=-l,l+=a;l>0;i=256*i+e[t+d],d+=h,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+d],d+=h,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,r),i-=u}return(p?-1:1)*s*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<<u)-1,d=l>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=l?(a=0,s=l):s+d>=1?(a=(t*c-1)*Math.pow(2,o),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;e[n+p]=255&a,p+=f,a/=256,o-=8);for(s=s<<o|a,u+=o;u>0;e[n+p]=255&s,p+=f,s/=256,u-=8);e[n+p-f]|=128*g}}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}return n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(348)})(),e.exports=t()}(Qu)),Qu.exports),tl=el.config(e=>{const t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9,envelopeTypeSorobanAuthorizationWithAddress:10}),e.enum("BucketListType",{live:0,hotArchive:1}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("ContractId")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.typedef("DependentTxCluster",e.varArray(e.lookup("TransactionEnvelope"),2147483647)),e.typedef("ParallelTxExecutionStage",e.varArray(e.lookup("DependentTxCluster"),2147483647)),e.struct("ParallelTxsComponent",[["baseFee",e.option(e.lookup("Int64"))],["executionStages",e.varArray(e.lookup("ParallelTxExecutionStage"),2147483647)]]),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"],[1,"parallelTxsComponent"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647),parallelTxsComponent:e.lookup("ParallelTxsComponent")}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3,ledgerEntryRestored:4}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"],["ledgerEntryRestored","restored"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry"),restored:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("ContractId"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("OperationMetaV2",[["ext",e.lookup("ExtensionPoint")],["changes",e.lookup("LedgerEntryChanges")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.struct("SorobanTransactionMetaV2",[["ext",e.lookup("SorobanTransactionMetaExt")],["returnValue",e.option(e.lookup("ScVal"))]]),e.enum("TransactionEventStage",{transactionEventStageBeforeAllTxes:0,transactionEventStageAfterTx:1,transactionEventStageAfterAllTxes:2}),e.struct("TransactionEvent",[["stage",e.lookup("TransactionEventStage")],["event",e.lookup("ContractEvent")]]),e.struct("TransactionMetaV4",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMetaV2"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMetaV2"))],["events",e.varArray(e.lookup("TransactionEvent"),2147483647)],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"],[4,"v4"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3"),v4:e.lookup("TransactionMetaV4")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("TransactionResultMetaV1",[["ext",e.lookup("ExtensionPoint")],["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")],["postTxApplyFeeProcessing",e.lookup("LedgerEntryChanges")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfLiveSorobanState",e.lookup("Uint64")],["evictedKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["unused",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.struct("LedgerCloseMetaV2",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMetaV1"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfLiveSorobanState",e.lookup("Uint64")],["evictedKeys",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"],[2,"v2"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1"),v2:e.lookup("LedgerCloseMetaV2")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.struct("SorobanDelegateSignature",[["address",e.lookup("ScAddress")],["signature",e.lookup("ScVal")],["nestedDelegates",e.varArray(e.lookup("SorobanDelegateSignature"),2147483647)]]),e.struct("SorobanAddressCredentialsWithDelegates",[["addressCredentials",e.lookup("SorobanAddressCredentials")],["delegates",e.varArray(e.lookup("SorobanDelegateSignature"),2147483647)]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1,sorobanCredentialsAddressV2:2,sorobanCredentialsAddressWithDelegates:3}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"],["sorobanCredentialsAddressV2","addressV2"],["sorobanCredentialsAddressWithDelegates","addressWithDelegates"]],arms:{address:e.lookup("SorobanAddressCredentials"),addressV2:e.lookup("SorobanAddressCredentials"),addressWithDelegates:e.lookup("SorobanAddressCredentialsWithDelegates")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.typedef("SorobanAuthorizationEntries",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("HashIdPreimageSorobanAuthorizationWithAddress",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["address",e.lookup("ScAddress")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"],["envelopeTypeSorobanAuthorizationWithAddress","sorobanAuthorizationWithAddress"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization"),sorobanAuthorizationWithAddress:e.lookup("HashIdPreimageSorobanAuthorizationWithAddress")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["diskReadBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanResourcesExtV0",[["archivedSorobanEntries",e.varArray(e.lookup("Uint32"),2147483647)]]),e.union("SorobanTransactionDataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"resourceExt"]],arms:{resourceExt:e.lookup("SorobanResourcesExtV0")}}),e.struct("SorobanTransactionData",[["ext",e.lookup("SorobanTransactionDataExt")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5,claimClaimableBalanceTrustlineFrozen:-6}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()],["claimClaimableBalanceTrustlineFrozen",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7,liquidityPoolDepositTrustlineFrozen:-8}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()],["liquidityPoolDepositTrustlineFrozen",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5,liquidityPoolWithdrawTrustlineFrozen:-6}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()],["liquidityPoolWithdrawTrustlineFrozen",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17,txFrozenKeyAccessed:-18}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()],["txFrozenKeyAccessed",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()],["txFrozenKeyAccessed",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.typedef("ContractId",e.lookup("Hash")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.typedef("PoolId",e.lookup("Hash")),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1,scAddressTypeMuxedAccount:2,scAddressTypeClaimableBalance:3,scAddressTypeLiquidityPool:4}),e.struct("MuxedEd25519Account",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"],["scAddressTypeMuxedAccount","muxedAccount"],["scAddressTypeClaimableBalance","claimableBalanceId"],["scAddressTypeLiquidityPool","liquidityPoolId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("ContractId"),muxedAccount:e.lookup("MuxedEd25519Account"),claimableBalanceId:e.lookup("ClaimableBalanceId"),liquidityPoolId:e.lookup("PoolId")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvContractInstance","instance"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),instance:e.lookup("ScContractInstance"),nonceKey:e.lookup("ScNonceKey")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeMuxedAddress:20,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeMuxedAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),2147483647)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),2147483647)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),2147483647)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),2147483647)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),2147483647)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),2147483647)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEventParamLocationV0",{scSpecEventParamLocationData:0,scSpecEventParamLocationTopicList:1}),e.struct("ScSpecEventParamV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")],["location",e.lookup("ScSpecEventParamLocationV0")]]),e.enum("ScSpecEventDataFormat",{scSpecEventDataFormatSingleValue:0,scSpecEventDataFormatVec:1,scSpecEventDataFormatMap:2}),e.struct("ScSpecEventV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.lookup("ScSymbol")],["prefixTopics",e.varArray(e.lookup("ScSymbol"),2)],["params",e.varArray(e.lookup("ScSpecEventParamV0"),2147483647)],["dataFormat",e.lookup("ScSpecEventDataFormat")]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4,scSpecEntryEventV0:5}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"],["scSpecEntryEventV0","eventV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0"),eventV0:e.lookup("ScSpecEventV0")}}),e.typedef("EncodedLedgerKey",e.varOpaque()),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractParallelComputeV0",[["ledgerMaxDependentTxClusters",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxDiskReadEntries",e.lookup("Uint32")],["ledgerMaxDiskReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxDiskReadEntries",e.lookup("Uint32")],["txMaxDiskReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeDiskReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeDiskRead1Kb",e.lookup("Int64")],["sorobanStateTargetSizeBytes",e.lookup("Int64")],["rentFee1KbSorobanStateSizeLow",e.lookup("Int64")],["rentFee1KbSorobanStateSizeHigh",e.lookup("Int64")],["sorobanStateRentFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostExtV0",[["txMaxFootprintEntries",e.lookup("Uint32")],["feeWrite1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69,bn254EncodeFp:70,bn254DecodeFp:71,bn254G1CheckPointOnCurve:72,bn254G2CheckPointOnCurve:73,bn254G2CheckPointInSubgroup:74,bn254G1ProjectiveToAffine:75,bn254G1Add:76,bn254G1Mul:77,bn254Pairing:78,bn254FrFromU256:79,bn254FrToU256:80,bn254FrAddSub:81,bn254FrMul:82,bn254FrPow:83,bn254FrInv:84,bn254G1Msm:85}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["liveSorobanStateSizeWindowSampleSize",e.lookup("Uint32")],["liveSorobanStateSizeWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.struct("ConfigSettingScpTiming",[["ledgerTargetCloseTimeMilliseconds",e.lookup("Uint32")],["nominationTimeoutInitialMilliseconds",e.lookup("Uint32")],["nominationTimeoutIncrementMilliseconds",e.lookup("Uint32")],["ballotTimeoutInitialMilliseconds",e.lookup("Uint32")],["ballotTimeoutIncrementMilliseconds",e.lookup("Uint32")]]),e.struct("FrozenLedgerKeys",[["keys",e.varArray(e.lookup("EncodedLedgerKey"),2147483647)]]),e.struct("FrozenLedgerKeysDelta",[["keysToFreeze",e.varArray(e.lookup("EncodedLedgerKey"),2147483647)],["keysToUnfreeze",e.varArray(e.lookup("EncodedLedgerKey"),2147483647)]]),e.struct("FreezeBypassTxes",[["txHashes",e.varArray(e.lookup("Hash"),2147483647)]]),e.struct("FreezeBypassTxsDelta",[["addTxes",e.varArray(e.lookup("Hash"),2147483647)],["removeTxes",e.varArray(e.lookup("Hash"),2147483647)]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingLiveSorobanStateSizeWindow:12,configSettingEvictionIterator:13,configSettingContractParallelComputeV0:14,configSettingContractLedgerCostExtV0:15,configSettingScpTiming:16,configSettingFrozenLedgerKeys:17,configSettingFrozenLedgerKeysDelta:18,configSettingFreezeBypassTxes:19,configSettingFreezeBypassTxsDelta:20}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingLiveSorobanStateSizeWindow","liveSorobanStateSizeWindow"],["configSettingEvictionIterator","evictionIterator"],["configSettingContractParallelComputeV0","contractParallelCompute"],["configSettingContractLedgerCostExtV0","contractLedgerCostExt"],["configSettingScpTiming","contractScpTiming"],["configSettingFrozenLedgerKeys","frozenLedgerKeys"],["configSettingFrozenLedgerKeysDelta","frozenLedgerKeysDelta"],["configSettingFreezeBypassTxes","freezeBypassTxes"],["configSettingFreezeBypassTxsDelta","freezeBypassTxsDelta"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),liveSorobanStateSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator"),contractParallelCompute:e.lookup("ConfigSettingContractParallelComputeV0"),contractLedgerCostExt:e.lookup("ConfigSettingContractLedgerCostExtV0"),contractScpTiming:e.lookup("ConfigSettingScpTiming"),frozenLedgerKeys:e.lookup("FrozenLedgerKeys"),frozenLedgerKeysDelta:e.lookup("FrozenLedgerKeysDelta"),freezeBypassTxes:e.lookup("FreezeBypassTxes"),freezeBypassTxsDelta:e.lookup("FreezeBypassTxsDelta")}}),e.struct("LedgerCloseMetaBatch",[["startSequence",e.lookup("Uint32")],["endSequence",e.lookup("Uint32")],["ledgerCloseMeta",e.varArray(e.lookup("LedgerCloseMeta"),2147483647)]])});const nl={XdrWriter:el.XdrWriter,XdrReader:el.XdrReader};function rl(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 i=e?.length;if(!r||void 0!==t){const t=(n&&`"${n}" `)+"expected Uint8Array"+""+", got "+(r?`length=${i}`:"type="+typeof e);if(!r)throw new TypeError(t);throw new RangeError(t)}return e}function ol(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 il(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function sl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function al(e,t){return e<<32-t|e>>>t}function cl(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 ul=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ll(e,t,n){return e&t^~e&n}function dl(e,t,n){return e&t^e&n^t&n}class hl{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=sl(this.buffer)}update(e){ol(this),rl(e);const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){const t=sl(e);for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ol(this),function(e,t){rl(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:i}=this;t[i++]=128,il(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),o),this.process(n,0);const s=sl(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++)s.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:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const pl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fl=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),gl=BigInt(2**32-1),ml=BigInt(32);function yl(e,t=!1){return t?{h:Number(e&gl),l:Number(e>>ml&gl)}:{h:0|Number(e>>ml&gl),l:0|Number(e&gl)}}const wl=(e,t,n)=>e>>>n,bl=(e,t,n)=>e<<32-n|t>>>n,vl=(e,t,n)=>e>>>n|t<<32-n,Al=(e,t,n)=>e<<32-n|t>>>n,Sl=(e,t,n)=>e<<64-n|t>>>n-32,Tl=(e,t,n)=>e>>>n-32|t<<64-n;function El(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const _l=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),kl=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Cl=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Rl=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,xl=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Il=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,Bl=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]),Ol=new Uint32Array(64);class Pl extends hl{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ol[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ol[e-15],n=Ol[e-2],r=al(t,7)^al(t,18)^t>>>3,o=al(n,17)^al(n,19)^n>>>10;Ol[e]=o+Ol[e-7]+r+Ol[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(al(s,6)^al(s,11)^al(s,25))+ll(s,a,c)+Bl[e]+Ol[e]|0,l=(al(n,2)^al(n,13)^al(n,22))+dl(n,r,o)|0;u=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,i,s,a,c,u)}roundClean(){il(Ol)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),il(this.buffer)}}class Ll extends Pl{A=0|pl[0];B=0|pl[1];C=0|pl[2];D=0|pl[3];E=0|pl[4];F=0|pl[5];G=0|pl[6];H=0|pl[7];constructor(){super(32)}}const Ul=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:s}=yl(e[i],t);[r[i],o[i]]=[n,s]}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))))(),Nl=(()=>Ul[0])(),Fl=(()=>Ul[1])(),Dl=new Uint32Array(80),Ml=new Uint32Array(80);class Vl extends hl{constructor(e){super(128,e,16,!1)}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:l,Fl:d,Gh:h,Gl:p,Hh:f,Hl:g}=this;return[e,t,n,r,o,i,s,a,c,u,l,d,h,p,f,g]}set(e,t,n,r,o,i,s,a,c,u,l,d,h,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|i,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|d,this.Gh=0|h,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)Dl[n]=e.getUint32(t),Ml[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Dl[e-15],n=0|Ml[e-15],r=vl(t,n,1)^vl(t,n,8)^wl(t,0,7),o=Al(t,n,1)^Al(t,n,8)^bl(t,n,7),i=0|Dl[e-2],s=0|Ml[e-2],a=vl(i,s,19)^Sl(i,s,61)^wl(i,0,6),c=Al(i,s,19)^Tl(i,s,61)^bl(i,s,6),u=Cl(o,c,Ml[e-7],Ml[e-16]),l=Rl(u,r,a,Dl[e-7],Dl[e-16]);Dl[e]=0|l,Ml[e]=0|u}let{Ah:n,Al:r,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:l,El:d,Fh:h,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=vl(l,d,14)^vl(l,d,18)^Sl(l,d,41),w=Al(l,d,14)^Al(l,d,18)^Tl(l,d,41),b=l&h^~l&f,v=xl(y,w,d&p^~d&g,Fl[e],Ml[e]),A=Il(v,m,t,b,Nl[e],Dl[e]),S=0|v,T=vl(n,r,28)^Sl(n,r,34)^Sl(n,r,39),E=Al(n,r,28)^Tl(n,r,34)^Tl(n,r,39),_=n&o^n&s^o&s,k=r&i^r&a^i&a;m=0|f,y=0|g,f=0|h,g=0|p,h=0|l,p=0|d,({h:l,l:d}=El(0|c,0|u,0|A,0|S)),c=0|s,u=0|a,s=0|o,a=0|i,o=0|n,i=0|r;const C=_l(S,E,k);n=kl(C,A,T,_),r=0|C}({h:n,l:r}=El(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:i}=El(0|this.Bh,0|this.Bl,0|o,0|i)),({h:s,l:a}=El(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=El(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:d}=El(0|this.Eh,0|this.El,0|l,0|d)),({h:h,l:p}=El(0|this.Fh,0|this.Fl,0|h,0|p)),({h:f,l:g}=El(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=El(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,o,i,s,a,c,u,l,d,h,p,f,g,m,y)}roundClean(){il(Dl,Ml)}destroy(){this.destroyed=!0,il(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class ql extends Vl{Ah=0|fl[0];Al=0|fl[1];Bh=0|fl[2];Bl=0|fl[3];Ch=0|fl[4];Cl=0|fl[5];Dh=0|fl[6];Dl=0|fl[7];Eh=0|fl[8];El=0|fl[9];Fh=0|fl[10];Fl=0|fl[11];Gh=0|fl[12];Gl=0|fl[13];Hh=0|fl[14];Hl=0|fl[15];constructor(){super(64)}}const Hl=cl(()=>new Ll,ul(1)),zl=cl(()=>new ql,ul(3));function $l(e){const t="string"==typeof e?oo.Buffer.from(e,"utf8"):e;return oo.Buffer.from(Hl(t))}
|
|
198
|
-
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const Gl=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:jl,n:Wl,Gx:Zl,Gy:Kl,a:Xl,d:Yl,h:Jl}=Gl,Ql=32,ed=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,ed),t},td=(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 i=e?.length,s=void 0!==t;if(!r||s&&i!==t){const o=(n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e);throw r?new RangeError(o):new TypeError(o)}return e},nd=e=>new Uint8Array(e),rd=e=>Uint8Array.from(e),od=(e,t)=>e.toString(16).padStart(t,"0"),id=e=>Array.from(td(e)).map(e=>od(e,2)).join(""),sd=48,ad=57,cd=65,ud=70,ld=97,dd=102,hd=e=>e>=sd&&e<=ad?e-sd:e>=cd&&e<=ud?e-(cd-10):e>=ld&&e<=dd?e-(ld-10):void 0,pd=e=>{const t="hex invalid";if("string"!=typeof e)return ed(t);const n=e.length,r=n/2;if(n%2)return ed(t);const o=nd(r);for(let n=0,i=0;n<r;n++,i+=2){const r=hd(e.charCodeAt(i)),s=hd(e.charCodeAt(i+1));if(void 0===r||void 0===s)return ed(t);o[n]=16*r+s}return o},fd=()=>globalThis?.crypto,gd=(...e)=>{let t=0;for(const n of e)t+=td(n).length;const n=nd(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n},md=BigInt,yd=(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)},wd=(e,t=jl)=>{const n=e%t;return n>=0n?n:t+n},bd=(1n<<255n)-1n,vd=e=>{e<0n&&ed("negative coordinate");let t=19n*(e>>255n)+(e&bd);return t=19n*(t>>255n)+(t&bd),t%jl},Ad=e=>wd(e,Wl),Sd=e=>{const t=Hd[e];return"function"!=typeof t&&ed("hashes."+e+" not set"),t},Td=e=>td(e,64,"digest"),Ed=e=>e instanceof kd?e:ed("Point expected"),_d=2n**256n;class kd{static BASE;static ZERO;X;Y;Z;T;constructor(e,t,n,r){const o=_d;this.X=yd(e,0n,o),this.Y=yd(t,0n,o),this.Z=yd(n,1n,o),this.T=yd(r,0n,o),Object.freeze(this)}static CURVE(){return Gl}static fromAffine(e){return new kd(e.x,e.y,1n,vd(e.x*e.y))}static fromBytes(e,t=!1){const n=Yl,r=rd(td(e,Ql)),o=e[31];r[31]=-129&o;const i=Id(r);yd(i,0n,t?_d:jl);const s=vd(i*i),a=wd(s-1n),c=vd(n*s+1n);let{isValid:u,value:l}=Pd(a,c);u||ed("bad point: y not sqrt");const d=1n==(1n&l),h=!!(128&o);return!t&&0n===l&&h&&ed("bad point: x==0, isLastByteOdd"),h!==d&&(l=wd(-l)),new kd(l,i,1n,vd(l*i))}static fromHex(e,t){return kd.fromBytes(pd(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const e=Xl,t=Yl;if(this.is0())return ed("bad point: ZERO");const{X:n,Y:r,Z:o,T:i}=this,s=vd(n*n),a=vd(r*r),c=vd(o*o),u=vd(c*c),l=vd(s*e);if(vd(c*(l+a))!==wd(u+vd(t*vd(s*a))))return ed("bad point: equation left != right (1)");return vd(n*r)!==vd(o*i)?ed("bad point: equation left != right (2)"):this}equals(e){const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=Ed(e),a=vd(t*s),c=vd(o*r),u=vd(n*s),l=vd(i*r);return a===c&&u===l}is0(){return this.equals(Rd)}negate(){return new kd(wd(-this.X),this.Y,this.Z,wd(-this.T))}double(){const{X:e,Y:t,Z:n}=this,r=Xl,o=vd(e*e),i=vd(t*t),s=vd(2n*n*n),a=vd(r*o),c=wd(e+t),u=wd(vd(c*c)-o-i),l=wd(a+i),d=wd(l-s),h=wd(a-i),p=vd(u*d),f=vd(l*h),g=vd(u*h),m=vd(d*l);return new kd(p,f,m,g)}add(e){const{X:t,Y:n,Z:r,T:o}=this,{X:i,Y:s,Z:a,T:c}=Ed(e),u=Xl,l=Yl,d=vd(t*i),h=vd(n*s),p=vd(vd(o*l)*c),f=vd(r*a),g=wd(vd(wd(t+n)*wd(i+s))-d-h),m=wd(f-p),y=wd(f+p),w=wd(h-vd(u*d)),b=vd(g*m),v=vd(y*w),A=vd(g*w),S=vd(m*y);return new kd(b,v,S,A)}subtract(e){return this.add(Ed(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return Rd;if(yd(e,1n,Wl),!t&&this.is0())return Rd;if(1n===e)return this;if(this.equals(Cd))return Wd(e).p;let n=Rd,r=Cd;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(Rd))return{x:0n,y:1n};const r=((e,t)=>{(0n===e||t<=0n)&&ed("no inverse n="+e+" mod="+t);let n=wd(e,t),r=t,o=0n,i=1n;for(;0n!==n;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}return 1n===r?wd(o,t):ed("no inverse")})(n,jl);1n!==vd(n*r)&&ed("invalid inverse");return{x:vd(e*r),y:vd(t*r)}}toBytes(){const{x:e,y:t}=this.toAffine(),n=xd(t);return n[31]|=1n&e?128:0,n}toHex(){return id(this.toBytes())}clearCofactor(){return this.multiply(md(Jl),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.multiply(Wl/2n,!1).double();return Wl%2n&&(e=e.add(this)),e.is0()}}const Cd=new kd(Zl,Kl,1n,wd(Zl*Kl)),Rd=new kd(0n,1n,1n,0n);kd.BASE=Cd,kd.ZERO=Rd;const xd=e=>pd(od(yd(e,0n,_d),64)).reverse(),Id=e=>md("0x"+id(rd(td(e)).reverse())),Bd=(e,t)=>{let n=e;for(;t-- >0n;)n=vd(n*n);return n},Od=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Pd=(e,t)=>{const n=vd(t*vd(t*t)),r=vd(vd(n*n)*t),o=(e=>{const t=vd(e*e),n=vd(t*e),r=vd(Bd(n,2n)*n),o=vd(Bd(r,1n)*e),i=vd(Bd(o,5n)*o),s=vd(Bd(i,10n)*i),a=vd(Bd(s,20n)*s),c=vd(Bd(a,40n)*a),u=vd(Bd(c,80n)*c),l=vd(Bd(u,80n)*c),d=vd(Bd(l,10n)*i);return{pow_p_5_8:vd(Bd(d,2n)*e),b2:n}})(vd(e*r)).pow_p_5_8;let i=vd(e*vd(n*o));const s=vd(t*vd(i*i)),a=i,c=vd(i*Od),u=s===e,l=s===wd(-e),d=s===wd(-e*Od);return u&&(i=a),(l||d)&&(i=c),1n==(1n&wd(i))&&(i=wd(-i)),{isValid:u||l,value:i}},Ld=e=>Ad(Id(e)),Ud=(...e)=>Td(Sd("sha512")(gd(...e))),Nd=e=>{const t=rd(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;const r=t.slice(32,64),o=Ld(n),i=Cd.multiply(o),s=i.toBytes();return{head:n,prefix:r,scalar:o,point:i,pointBytes:s}},Fd=e=>Nd(Ud(td(e,Ql))),Dd=e=>e.finish(Ud(e.hashable)),Md=(e,t)=>{const n=td(e),r=Fd(t),o=Ud(r.prefix,n);return Dd(((e,t,n)=>{const{pointBytes:r,scalar:o}=e,i=Ld(t),s=Cd.multiply(i).toBytes();return{hashable:gd(s,r,n),finish:e=>{const t=Ad(i+Ld(e)*o);return td(gd(s,xd(t)),64)}}})(r,o,n))},Vd={zip215:!0},qd=(e,t,n,r=Vd)=>Dd(((e,t,n,r=Vd)=>{e=td(e,64),t=td(t),n=td(n,Ql);const{zip215:o=!0}=r,i=e.subarray(0,Ql),s=Id(e.subarray(Ql,64));let a,c,u,l=Uint8Array.of(),d=!1;try{a=kd.fromBytes(n,o),c=kd.fromBytes(i,o),u=Cd.multiply(s,!1),l=gd(i,n,t),d=!0}catch(e){}return{hashable:l,finish:e=>{if(!d)return!1;if(!o&&a.isSmallOrder())return!1;const t=Ld(e);return c.add(a.multiply(t,!1)).subtract(u).clearCofactor().is0()}}})(e,t,n,r)),Hd={sha512Async:async e=>{const t=fd()?.subtle??ed("crypto.subtle must be defined, consider polyfill"),n=gd(e);return nd(await t.digest("SHA-512",n.buffer))},sha512:void 0},zd=Object.freeze({getExtendedPublicKeyAsync:e=>((...e)=>Promise.resolve(Sd("sha512Async")(gd(...e))).then(Td))(td(e,Ql)).then(Nd),getExtendedPublicKey:Fd,randomSecretKey:e=>(e=void 0===e?((e=Ql)=>fd().getRandomValues(nd(e)))(Ql):e,td(e,Ql))}),$d=Math.ceil(32)+1;let Gd;const jd=(e,t)=>{const n=t.negate();return e?n:t},Wd=e=>{const t=Gd||(Gd=(()=>{const e=[];let t=Cd,n=t;for(let r=0;r<$d;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=Rd,r=Cd;const o=md(255),i=md(8);for(let s=0;s<$d;s++){let a=Number(e&o);e>>=i,a>128&&(a-=256,e+=1n);const c=128*s,u=c,l=c+Math.abs(a)-1,d=s%2!=0,h=a<0;0===a?r=r.add(jd(d,t[u])):n=n.add(jd(h,t[l]))}return 0n!==e&&ed("invalid wnaf"),{p:n,f:r}};function Zd(e){return oo.Buffer.from(Fd(e).pointBytes)}function Kd(e,t){return oo.Buffer.from(Md(oo.Buffer.from(e),t))}function Xd(e,t,n){return qd(oo.Buffer.from(t),oo.Buffer.from(e),oo.Buffer.from(n),{zip215:!1})}Hd.sha512=zl;const Yd=(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 Jd,Qd={};var eh=(Jd||(Jd=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 i(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 s(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),i.prototype.charmap=n.charmap,i.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 i=255&t[e];(r-=5)>0?o|=i<<r:r<0?(n.push(o|i>>-r),o=i<<(r+=8)&255):(n.push(o|i),r=8,o=0)}}),this.shift=r,this.carry=o,this},i.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},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,n,r,o=this.shift,i=this.carry;for(r=0;r<e.length;r++)t=i|(n=e[r])>>o,this.buf+=this.alphabet[31&t],o>5&&(t=n>>(o-=5),this.buf+=this.alphabet[31&t]),i=n<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.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 s(t).finalize(e)},e.decode=function(e,t){return new i(t).finalize(e)},e.Decoder=i,e.Encoder=s,e.charmap=t,e.crockford=r,e.rfc4648=n,e.base32hex=o}(Qd)),Qd),th=Bt(eh);const nh={ed25519PublicKey:48,ed25519SecretSeed:144,med25519PublicKey:96,preAuthTx:152,sha256Hash:184,signedPayload:120,contract:16,liquidityPool:88,claimableBalance:8},rh={G:"ed25519PublicKey",S:"ed25519SecretSeed",M:"med25519PublicKey",T:"preAuthTx",X:"sha256Hash",P:"signedPayload",C:"contract",L:"liquidityPool",B:"claimableBalance"};function oh(e){return Object.prototype.hasOwnProperty.call(nh,e)}class ih{static types=rh;static encodeEd25519PublicKey(e){return ch("ed25519PublicKey",e)}static decodeEd25519PublicKey(e){return ah("ed25519PublicKey",e)}static isValidEd25519PublicKey(e){return sh("ed25519PublicKey",e)}static encodeEd25519SecretSeed(e){return ch("ed25519SecretSeed",e)}static decodeEd25519SecretSeed(e){return ah("ed25519SecretSeed",e)}static isValidEd25519SecretSeed(e){return sh("ed25519SecretSeed",e)}static encodeMed25519PublicKey(e){return ch("med25519PublicKey",e)}static decodeMed25519PublicKey(e){return ah("med25519PublicKey",e)}static isValidMed25519PublicKey(e){return sh("med25519PublicKey",e)}static encodePreAuthTx(e){return ch("preAuthTx",e)}static decodePreAuthTx(e){return ah("preAuthTx",e)}static encodeSha256Hash(e){return ch("sha256Hash",e)}static decodeSha256Hash(e){return ah("sha256Hash",e)}static encodeSignedPayload(e){return ch("signedPayload",e)}static decodeSignedPayload(e){return ah("signedPayload",e)}static isValidSignedPayload(e){return sh("signedPayload",e)}static encodeContract(e){return ch("contract",e)}static decodeContract(e){return ah("contract",e)}static isValidContract(e){return sh("contract",e)}static encodeClaimableBalance(e){return ch("claimableBalance",e)}static decodeClaimableBalance(e){return ah("claimableBalance",e)}static isValidClaimableBalance(e){return sh("claimableBalance",e)}static encodeLiquidityPool(e){return ch("liquidityPool",e)}static decodeLiquidityPool(e){return ah("liquidityPool",e)}static isValidLiquidityPool(e){return sh("liquidityPool",e)}static getVersionByteForPrefix(e){if(e.length<1)return;const t=e[0];return rh[t]}}function sh(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=ah(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 ah(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");const n=th.decode(t),r=n[0],o=n.slice(0,-2),i=o.slice(1),s=n.slice(-2);if(t!==th.encode(n))throw new Error("invalid encoded string");if(!oh(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(nh).join(", ")}`);const a=nh[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}(uh(o),s))throw new Error("invalid checksum");return oo.Buffer.from(i)}function ch(e,t){if(null==t)throw new Error("cannot encode null data");if(!oh(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(nh).join(", ")}`);const n=nh[e];t=oo.Buffer.from(t);const r=oo.Buffer.from([n]),o=oo.Buffer.concat([r,t]),i=oo.Buffer.from(uh(o)),s=oo.Buffer.concat([o,i]);return th.encode(s)}function uh(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}Hd.sha512=zl;class lh{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=oo.Buffer.from(e.secretKey),32!==e.secretKey.length)throw new Error("secretKey length is invalid");if(this._secretSeed=e.secretKey,this._publicKey=Zd(e.secretKey),this._secretKey=e.secretKey,e.publicKey&&!this._publicKey.equals(oo.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=oo.Buffer.from(e.publicKey),32!==this._publicKey.length)throw new Error("publicKey length is invalid")}}static fromSecret(e){const t=ih.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($l(e))}static fromPublicKey(e){const t=ih.decodeEd25519PublicKey(e);if(32!==t.length)throw new Error("Invalid Stellar public key");return new this({type:"ed25519",publicKey:t})}static random(){const e=zd.randomSecretKey();return this.fromRawEd25519Seed(oo.Buffer.from(e))}xdrAccountId(){return tl.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrPublicKey(){return tl.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 tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromString(e),ed25519:this._publicKey}))}return tl.MuxedAccount.keyTypeEd25519(this._publicKey)}rawPublicKey(){return this._publicKey}signatureHint(){const e=this.xdrAccountId().toXDR();return e.subarray(e.length-4)}publicKey(){return ih.encodeEd25519PublicKey(this._publicKey)}secret(){if(!this._secretSeed)throw new Error("no secret key available");if("ed25519"===this.type)return ih.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 Kd(e,this._secretKey)}verify(e,t){try{return Xd(e,t,this._publicKey)}catch{return!1}}signDecorated(e){const t=this.sign(e),n=this.signatureHint();return new tl.DecoratedSignature({hint:n,signature:t})}signPayloadDecorated(e){const t=oo.Buffer.isBuffer(e)?e:oo.Buffer.from(e),n=this.sign(t),r=this.signatureHint();let o=oo.Buffer.from(t.subarray(-4));o.length<4&&(o=oo.Buffer.concat([o,oo.Buffer.alloc(4-o.length,0)]));for(let e=0;e<o.length;e++)o[e]=o[e]^r[e];return new tl.DecoratedSignature({hint:o,signature:n})}}const dh={native:"native",credit4:"credit_alphanum4",credit12:"credit_alphanum12",liquidityPoolShares:"liquidity_pool_shares"};function hh(e,t){return oo.Buffer.compare(oo.Buffer.from(e,"ascii"),oo.Buffer.from(t,"ascii"))}class ph{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&&!ih.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 ph("XLM")}static fromOperation(e){let t,n,r;switch(e.switch()){case tl.AssetType.assetTypeNative():return this.native();case tl.AssetType.assetTypeCreditAlphanum4():return t=e.alphaNum4(),r=ih.encodeEd25519PublicKey(t.issuer().ed25519()),n=Yd(t.assetCode().toString(),"\0"),new this(n,r);case tl.AssetType.assetTypeCreditAlphanum12():return t=e.alphaNum12(),r=ih.encodeEd25519PublicKey(t.issuer().ed25519()),n=Yd(t.assetCode().toString(),"\0"),new this(n,r);default:throw new Error(`Invalid asset type: ${e.switch().name}`)}}toXDRObject(){return this._toXDRObject(tl.Asset)}toChangeTrustXDRObject(){return this._toXDRObject(tl.ChangeTrustAsset)}toTrustLineXDRObject(){return this._toXDRObject(tl.TrustLineAsset)}contractId(e){const t=$l(oo.Buffer.from(e)),n=tl.HashIdPreimage.envelopeTypeContractId(new tl.HashIdPreimageContractId({networkId:t,contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject())}));return ih.encodeContract($l(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=tl.AlphaNum4,n="assetTypeCreditAlphanum4"):(t=tl.AlphaNum12,n="assetTypeCreditAlphanum12");const r=this.code.length<=4?4:12;return new e(n,new t({assetCode:this.code.padEnd(r,"\0"),issuer:lh.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 tl.AssetType.assetTypeNative().value:return dh.native;case tl.AssetType.assetTypeCreditAlphanum4().value:return dh.credit4;case tl.AssetType.assetTypeCreditAlphanum12().value:return dh.credit12;default:throw new Error("Supported asset types are: native, credit_alphanum4, credit_alphanum12")}}getRawAssetType(){return this.isNative()?tl.AssetType.assetTypeNative():this.code.length<=4?tl.AssetType.assetTypeCreditAlphanum4():tl.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 ph))throw new Error("assetA is invalid");if(!(t&&t instanceof ph))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=hh(e.getCode(),t.getCode());if(0!==o)return o;const i=e.getIssuer(),s=t.getIssuer();if(void 0===i||void 0===s)throw new Error("Issuer is undefined for non-native asset");return hh(i,s)}}function fh(e,t){if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");const{assetA:n,assetB:r,fee:o}=t??{};if(!(n&&n instanceof ph))throw new Error("assetA is invalid");if(!(r&&r instanceof ph))throw new Error("assetB is invalid");if(!o||30!==o)throw new Error("fee is invalid");if(-1!==ph.compare(n,r))throw new Error("Assets are not in lexicographic order");return $l(tl.LiquidityPoolParameters.liquidityPoolConstantProduct(new tl.LiquidityPoolConstantProductParameters({assetA:n.toXDRObject(),assetB:r.toXDRObject(),fee:o})).toXDR())}class gh{_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 tl.Transaction)return tl.Transaction.fromXDR(e);if(this._tx instanceof tl.TransactionV0)return tl.TransactionV0.fromXDR(e);if(this._tx instanceof tl.FeeBumpTransaction)return tl.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=oo.Buffer.from(t,"base64");try{n=lh.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 tl.DecoratedSignature({hint:r,signature:o}))}addDecoratedSignature(e){this.signatures.push(e)}signHashX(e){if("string"==typeof e&&(e=oo.Buffer.from(e,"hex")),e.length>64)throw new Error("preimage cannot be longer than 64 bytes");const t=e,n=$l(e),r=n.subarray(n.length-4);this.signatures.push(new tl.DecoratedSignature({hint:r,signature:t}))}hash(){return $l(this.signatureBase())}signatureBase(){throw new Error("Implement in subclass")}toEnvelope(){throw new Error("Implement in subclass")}toXDR(){return this.toEnvelope().toXDR().toString("base64")}}class mh{assetA;assetB;fee;constructor(e,t,n){if(!(e&&e instanceof ph))throw new Error("assetA is invalid");if(!(t&&t instanceof ph))throw new Error("assetB is invalid");if(-1!==ph.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===tl.AssetType.assetTypePoolShare()){const t=e.liquidityPool().constantProduct();return new this(ph.fromOperation(t.assetA()),ph.fromOperation(t.assetB()),t.fee())}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=new tl.LiquidityPoolConstantProductParameters({assetA:this.assetA.toXDRObject(),assetB:this.assetB.toXDRObject(),fee:this.fee}),t=tl.LiquidityPoolParameters.liquidityPoolConstantProduct(e);return tl.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:${fh("constant_product",this.getLiquidityPoolParameters()).toString("hex")}`}}class yh{_destination;_predicate;constructor(e,t){if(!ih.isValidEd25519PublicKey(e))throw new Error("Destination is invalid");if(this._destination=e,t){if(!(t instanceof tl.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");this._predicate=t}else this._predicate=tl.ClaimPredicate.claimPredicateUnconditional()}static predicateUnconditional(){return tl.ClaimPredicate.claimPredicateUnconditional()}static predicateAnd(e,t){if(!(e instanceof tl.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof tl.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateAnd([e,t])}static predicateOr(e,t){if(!(e instanceof tl.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof tl.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateOr([e,t])}static predicateNot(e){if(!(e instanceof tl.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateNot(e)}static predicateBeforeAbsoluteTime(e){return tl.ClaimPredicate.claimPredicateBeforeAbsoluteTime(tl.Int64.fromString(e))}static predicateBeforeRelativeTime(e){return tl.ClaimPredicate.claimPredicateBeforeRelativeTime(tl.Int64.fromString(e))}static fromXDR(e){let t;if(e.switch()===tl.ClaimantType.claimantTypeV0())return t=e.v0(),new this(ih.encodeEd25519PublicKey(t.destination().ed25519()),t.predicate());throw new Error(`Invalid claimant type: ${e.switch().name}`)}toXDRObject(){const e=new tl.ClaimantV0({destination:lh.fromPublicKey(this._destination).xdrAccountId(),predicate:this._predicate});return tl.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 wh{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===tl.AssetType.assetTypePoolShare()){const t=e.liquidityPoolId().toString("hex");return new wh(t)}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=oo.Buffer.from(this.liquidityPoolId,"hex");return tl.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 bh(e){return ih.isValidMed25519PublicKey(e)?function(e){const t=ih.decodeMed25519PublicKey(e);return tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):tl.MuxedAccount.keyTypeEd25519(ih.decodeEd25519PublicKey(e))}function vh(e){return e.switch().value===tl.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===tl.CryptoKeyType.keyTypeEd25519())return vh(e);const t=e.med25519();return ih.encodeMed25519PublicKey(oo.Buffer.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):ih.encodeEd25519PublicKey(e.ed25519())}function Ah(e,t){if(!ih.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 tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromString(t),ed25519:ih.decodeEd25519PublicKey(e)}))}function Sh(e){if(ih.isValidEd25519PublicKey(e))return e;if(!ih.isValidMed25519PublicKey(e))throw new TypeError(`expected muxed account (M...), got ${e}`);const t=bh(e);return ih.encodeEd25519PublicKey(t.med25519().ed25519())}var Th=function e(t){var n,r,o=/^(-?)0([xbo])(?=[^.])/i,i=/^-?(Infinity|NaN)$/,s=/^\s*\+(?!-)|^\s+|\s+$/g,a=A.prototype={constructor:A,toString:null,valueOf:null},c=new A(1),u=20,l=4,d=-7,h=21,p=-1e7,f=1e7,g=!1,m=!0,y=1,w=0,b={prefix:"",negativeSign:"-",positiveSign:"",groupSeparator:",",groupSize:3,secondaryGroupSize:0,decimalSeparator:".",fractionGroupSeparator:"",fractionGroupSize:0,suffix:""},v="0123456789abcdefghijklmnopqrstuvwxyz";function A(e,t){var n,r,a,c,u=this;if(!(u instanceof A))return new A(e,t);if(c=typeof e,null==t){if(_(e))return u.s=e.s,void(!e.c||e.e>f?u.c=u.e=null:e.e<p?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 S(u,String(e))}if("bigint"==c)return u.s=e<0?(e=-e,-1):1,S(u,String(e));if("string"==c)a=e;else{if(m)throw Error(Ch+"BigNumber, string, number, or BigInt expected: "+e);a=String(e)}if(Eh.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,S(u,a);if(a=a.replace(s,""),i.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"),Eh.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,S(u,a);if(m)throw Error(Ch+"Not a number: "+e);u.s=u.c=u.e=null}else{if("string"!=c){if(m)throw Error(Ch+"String expected: "+e);e=String(e)}Fh(t,2,v.length,"Base"),T(u,e.replace(s,""),t,e)}}function S(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<p)e.c=[e.e=0];else{if(e.e=n,e.c=[],r=(n+1)%xh,n<0&&(r+=xh),r<o){for(r&&e.c.push(+t.slice(0,r)),o-=xh;r<o;)e.c.push(+t.slice(r,r+=xh));r=xh-(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 i,s,a=v.slice(0,n),c=0,u="",l=!1,d=!1,h=!1;for(e.s=45===t.charCodeAt(0)?(t=t.slice(1),-1):1,s=t.length;c<s;c++){if(i=t.charAt(c),!(a.indexOf(i)>=0)){if("_"==i){if(d&&c+1<s){d=!1;continue}}else if("."==i){if(0==c||!l&&d){if(c+1==s)break;0==c&&(u="0"),u+=i,l=!0,d=!1;continue}}else if(!h&&(t==t.toUpperCase()&&a==a.toLowerCase()&&(t=t.toLowerCase())||t==t.toLowerCase()&&a==a.toUpperCase()&&(t=t.toUpperCase()))){c=-1,u="",h=!0,l=d=!1;continue}if(m)throw Error(Ch+"Not a base "+n+" number: "+o);return void(e.s=e.c=e.e=null)}u+=i,d=!0}S(e,r(u,n,10,e.s))}function E(e,t,n,r){var o,i,s,a,c;if(n=null==n?l:Fh(n,0,8),!e.c)return e.toString();if(o=e.c[0],s=e.e,null==t)c=Uh(e.c),c=1==r||2==r&&(s<=d||s>=h)?Vh(c,s):qh(c,s,"0");else if(i=(e=x(new A(e),t,n)).e,a=(c=Uh(e.c)).length,1==r||2==r&&(t<=i||i<=d)){for(;a<t;c+="0",a++);c=Vh(c,i)}else if(t-=s+(2===r&&i>s),c=qh(c,i,"0"),i+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=i-a)>0)for(i+1==a&&(c+=".");t--;c+="0");return e.s<0&&o?"-"+c:c}function _(e){return e instanceof A||!!e&&!0===e._isBigNumber}function k(e,t){for(var n,r,o=1,i=new A(e[0]);o<e.length;o++)(!(r=new A(e[o])).s||(n=Nh(i,r))===t||0===n&&i.s===t)&&(i=r);return i}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*xh-1)>f?e.c=e.e=null:n<p?e.c=[e.e=0]:(e.e=n,e.c=t),e}function R(e){var t,n={};for(t in b)b.hasOwnProperty(t)&&(n[t]=e.hasOwnProperty(t)?e[t]:b[t]);return n}function x(e,t,n,r){var o,i,s,a,c,u,l,d=e.c,h=Bh;if(d){e:{for(o=1,a=d[0];a>=10;a/=10,o++);if((i=t-o)<0)i+=xh,s=t,c=d[u=0],l=kh(c/h[o-s-1]%10);else if((u=_h((i+1)/xh))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,o=1,s=(i%=xh)-xh+1}else{for(c=a=d[u],o=1;a>=10;a/=10,o++);l=(s=(i%=xh)-xh+o)<0?0:kh(c/h[o-s-1]%10)}if(r=r||t<0||null!=d[u+1]||(s<0?c:c%h[o-s-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(i>0?s>0?c/h[o-s]: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]=h[(xh-t%xh)%xh],e.e=-t||0):d[0]=e.e=0,e;if(0==i?(d.length=u,a=1,u--):(d.length=u+1,a=h[xh-i],d[u]=s>0?kh(c/h[o-s]%h[s])*a:0),r)for(;;){if(0==u){for(i=1,s=d[0];s>=10;s/=10,i++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);i!=a&&(e.e++,d[0]==Rh&&(d[0]=1));break}if(d[u]+=a,d[u]!=Rh)break;d[u--]=0,a=1}for(i=d.length;0===d[--i];d.pop());}e.e>f?e.c=e.e=null:e.e<p&&(e.c=[e.e=0])}return e}function I(e){var t,n=e.e;return null===n?e.toString():(t=Uh(e.c),t=n<=d||n>=h?Vh(t,n):qh(t,n,"0"),e.s<0?"-"+t:t)}A.clone=e,A.ROUND_UP=0,A.ROUND_DOWN=1,A.ROUND_CEIL=2,A.ROUND_FLOOR=3,A.ROUND_HALF_UP=4,A.ROUND_HALF_DOWN=5,A.ROUND_HALF_EVEN=6,A.ROUND_HALF_CEIL=7,A.ROUND_HALF_FLOOR=8,A.EUCLID=9,A.config=A.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(Ch+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(u=Fh(e[t],0,Ph,t)),e.hasOwnProperty(t="ROUNDING_MODE")&&(l=Fh(e[t],0,8,t)),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(Dh(n=e[t])?(Fh(n[0],-Ph,0,t),Fh(n[1],0,Ph,t),d=n[0],h=n[1]):d=-(h=Fh(n,-Ph,Ph,t)<0?-n:n)),e.hasOwnProperty(t="RANGE")){if(!(n=e[t]))throw Error(Ch+t+" cannot be zero: "+n);Dh(n)?(Fh(n[0],-Ph,-1,t),Fh(n[1],1,Ph,t),p=n[0],f=n[1]):p=-(f=Fh(n,-Ph,Ph,t)<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(Ch+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw g=!n,Error(Ch+"crypto unavailable");g=n}else g=n}if(e.hasOwnProperty(t="STRICT")){if((n=e[t])!==!!n)throw Error(Ch+t+" not true or false: "+n);m=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(y=Fh(e[t],0,9,t)),e.hasOwnProperty(t="POW_PRECISION")&&(w=Fh(e[t],0,Ph,t)),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(Ch+t+" not an object: "+n);for(t in n)n.hasOwnProperty(t)&&b.hasOwnProperty(t)&&(b[t]=n[t])}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(Ch+t+" invalid: "+n);v=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,h],RANGE:[p,f],CRYPTO:g,STRICT:m,MODULO_MODE:y,POW_PRECISION:w,FORMAT:b,ALPHABET:v}},A.fromFormat=function(e,t){if("string"!=typeof e)throw Error(Ch+"Not a string: "+e);if(null==t)t=b;else{if("object"!=typeof t)throw Error(Ch+"Argument not an object: "+t);t=R(t)}var n,r,o,i,s=t.negativeSign||"-",a=t.positiveSign||"",c=t.prefix||"",u=t.suffix||"",l=t.groupSeparator||"",d=t.decimalSeparator||".",h=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(s)?(e=e.slice(s.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),i=e.slice(n+d.length),l)for(;o.indexOf(l)>-1;)o=o.replace(l,"");if(h)for(;i.indexOf(h)>-1;)i=i.replace(h,"");e=o+"."+i}return new A(r?"-"+e:e)},A.isBigNumber=function(e){if(!_(e))return!1;var t,n,r=e.c,o=e.e,i=e.s;if(!Dh(r))return null===r&&null===o&&(null===i||1===i||-1===i);if(1!==i&&-1!==i||o<-Ph||o>Ph||o!==kh(o))return!1;if(0===r[0])return 0===o&&1===r.length;if((t=(o+1)%xh)<1&&(t+=xh),String(r[0]).length!==t)return!1;for(t=0;t<r.length;t++)if((n=r[t])<0||n>=Rh||n!==kh(n))return!1;return 0!==n},A.maximum=A.max=function(){return k(arguments,-1)},A.minimum=A.min=function(){return k(arguments,1)},A.random=function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return kh(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var n,r,o,i,s,a=0,l=[],d=new A(c);if(e=null==e?u:Fh(e,0,Ph),i=_h(e/xh),g)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(i*=2));a<i;)(s=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(s%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw g=!1,Error(Ch+"crypto unavailable");for(n=crypto.randomBytes(i*=7);a<i;)(s=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(s%1e14),a+=7);a=i/7}if(!g)for(;a<i;)(s=t())<9e15&&(l[a++]=s%1e14);for(i=l[--a],e%=xh,i&&e&&(s=Bh[xh-e],l[a]=kh(i/s)*s);0===l[a];l.pop(),a--);if(a<0)l=[o=0];else{for(o=-1;0===l[0];l.splice(0,1),o-=xh);for(a=1,s=l[0];s>=10;s/=10,a++);a<xh&&(o-=xh-a)}return d.e=o,d.c=l,d}}(),A.sum=function(){for(var e=0,t=new A(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,i,s=[0],a=0,c=e.length;a<c;){for(i=s.length;i--;s[i]*=t);for(s[0]+=r.indexOf(e.charAt(a++)),o=0;o<s.length;o++)s[o]>n-1&&(null==s[o+1]&&(s[o+1]=0),s[o+1]+=s[o]/n|0,s[o]%=n)}return s.reverse()}return function(r,o,i,s,a){var c,d,h,p,f,g,m,y,b=r.indexOf("."),S=u,T=l;for(b>=0&&(p=w,w=0,r=r.replace(".",""),g=(y=new A(o)).pow(r.length-b),w=p,y.c=t(qh(Uh(g.c),g.e,"0"),10,i,e),y.e=y.c.length),h=p=(m=t(r,o,i,a?(c=v,e):(c=e,v))).length;0==m[--p];m.pop());if(!m[0])return c.charAt(0);if(b<0?--h:(g.c=m,g.e=h,g.s=s,m=(g=n(g,y,S,T,i)).c,f=g.r,h=g.e),b=m[d=h+S+1],p=i/2,f=f||d<0||null!=m[d+1],f=T<4?(null!=b||f)&&(0==T||T==(g.s<0?3:2)):b>p||b==p&&(4==T||f||6==T&&1&m[d-1]||T==(g.s<0?8:7)),d<1||!m[0])r=f?qh(c.charAt(1),-S,c.charAt(0)):c.charAt(0);else{if(d<m.length&&(m.length=d),f)for(--i;++m[--d]>i;)m[d]=0,d||(++h,m=[1].concat(m));for(p=m.length;!m[--p];);for(b=0,r="";b<=p;r+=c.charAt(m[b++]));r=qh(r,h,c.charAt(0))}return r}}(),n=function(){function e(e,t,n){var r,o,i,s,a=0,c=e.length,u=t%Oh,l=t/Oh|0;for(e=e.slice();c--;)a=((o=u*(i=e[c]%Oh)+(r=l*i+(s=e[c]/Oh|0)*u)%Oh*Oh+a)/n|0)+(r/Oh|0)+l*s,e[c]=o%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var o,i;if(n!=r)i=n>r?1:-1;else for(o=i=0;o<n;o++)if(e[o]!=t[o]){i=e[o]>t[o]?1:-1;break}return i}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,i,s,a){var c,u,l,d,h,p,f,g,m,y,w,b,v,S,T,E,_,k=r.s==o.s?1:-1,C=r.c,R=o.c;if(!(C&&C[0]&&R&&R[0]))return new A(r.s&&o.s&&(C?!R||C[0]!=R[0]:R)?C&&0==C[0]||!R?0*k:k/0:NaN);for(m=(g=new A(k)).c=[],k=i+(u=r.e-o.e)+1,a||(a=Rh,u=Lh(r.e/xh)-Lh(o.e/xh),k=k/xh|0),l=0;R[l]==(C[l]||0);l++);if(R[l]>(C[l]||0)&&u--,k<0)m.push(1),d=!0;else{for(S=C.length,E=R.length,l=0,k+=2,(h=kh(a/(R[0]+1)))>1&&(R=e(R,h,a),C=e(C,h,a),E=R.length,S=C.length),v=E,w=(y=C.slice(0,E)).length;w<E;y[w++]=0);_=R.slice(),_=[0].concat(_),T=R[0],R[1]>=a/2&&T++;do{if(h=0,(c=t(R,y,E,w))<0){if(b=y[0],E!=w&&(b=b*a+(y[1]||0)),(h=kh(b/T))>1)for(h>=a&&(h=a-1),f=(p=e(R,h,a)).length,w=y.length;1==t(p,y,f,w);)h--,n(p,E<f?_:R,f,a),f=p.length,c=1;else 0==h&&(c=h=1),f=(p=R.slice()).length;if(f<w&&(p=[0].concat(p)),n(y,p,w,a),w=y.length,-1==c)for(;t(R,y,E,w)<1;)h++,n(y,E<w?_:R,w,a),w=y.length}else 0===c&&(h++,y=[0]);m[l++]=h,y[0]?y[w++]=C[v]||0:(y=[C[v]],w=1)}while((v++<S||null!=y[0])&&k--);d=null!=y[0],m[0]||m.splice(0,1)}if(a==Rh){for(l=1,k=m[0];k>=10;k/=10,l++);x(g,i+(g.e=l+u*xh-1)+1,s,d)}else g.e=u,g.r=+d;return g}}(),a.absoluteValue=a.abs=function(){var e=new A(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return Nh(this,new A(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,o,i=this;if(null!=e)return x(new A(i),Fh(e,-Ph,Ph)+i.e+1,null==t?l:Fh(t,0,8));if(!(n=i.c))return null;if(r=((o=n.length-1)-Lh(this.e/xh))*xh,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 A(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new A(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,o,i,s,a,u,d,h=this;if((e=new A(e)).c&&!e.isInteger())throw Error(Ch+"Exponent not an integer: "+I(e));if(null!=t&&(t=new A(t)),s=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new A(Math.pow(+I(h),s?e.s*(2-Mh(e)):+I(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new A(NaN);(r=!a&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return i=h.s<0&&Mh(e)?-0:0,h.e>-1&&(i=1/i),new A(a?1/i:i);w&&(i=_h(w/xh+2))}for(s?(n=new A(.5),a&&(e.s=1),u=Mh(e)):u=(o=Math.abs(+I(e)))%2,d=new A(c);;){if(u){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):r&&(d=d.mod(t))}if(o){if(0===(o=kh(o/2)))break;u=o%2}else if(x(e=e.times(n),e.e+1,1),e.e>14)u=Mh(e);else{if(0===(o=+I(e)))break;u=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):r&&(h=h.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):i?x(d,w,l,void 0):d)},a.integerValue=function(e){var t=new A(this);return x(t,t.e+1,null==e?l:Fh(e,0,8))},a.isEqualTo=a.eq=function(e,t){return 0===Nh(this,new A(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return Nh(this,new A(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=Nh(this,new A(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Lh(this.e/xh)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return Nh(this,new A(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=Nh(this,new A(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,i,s=this,a=s.s;if(t=(e=new A(e,t)).s,!a||!t)return new A(NaN);if(a!=t)return e.s=-t,s.plus(e);var c=s.e/xh,u=e.e/xh,d=s.c,h=e.c;if(!c||!u){if(!d||!h)return d?(e.s=-t,e):new A(h?s:NaN);if(!d[0]||!h[0])return h[0]?(e.s=-t,e):new A(d[0]?s:3==l?-0:0)}if(c=Lh(c),u=Lh(u),d=d.slice(),a=c-u){for((i=a<0)?(a=-a,o=d):(u=c,o=h),o.reverse(),t=a;t--;o.push(0));o.reverse()}else for(r=(i=(a=d.length)<(t=h.length))?a:t,a=t=0;t<r;t++)if(d[t]!=h[t]){i=d[t]<h[t];break}if(i&&(o=d,d=h,h=o,e.s=-e.s),(t=(r=h.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=Rh-1;r>a;){if(d[--r]<h[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=Rh}d[r]-=h[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,i=this;return e=new A(e,t),!i.c||!e.s||e.c&&!e.c[0]?new A(NaN):!e.c||i.c&&!i.c[0]?new A(i):(9==y?(o=e.s,e.s=1,r=n(i,e,0,3),e.s=o,r.s*=o):r=n(i,e,0,y),(e=i.minus(r.times(e))).c[0]||1!=y||(e.s=i.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,o,i,s,a,c,u,l,d,h,p,f,g,m,y=this,w=y.c,b=(e=new A(e,t)).c;if(!(w&&b&&w[0]&&b[0]))return!y.s||!e.s||w&&!w[0]&&!b||b&&!b[0]&&!w?e.c=e.e=e.s=null:(e.s*=y.s,w&&b?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Lh(y.e/xh)+Lh(e.e/xh),e.s*=y.s,(c=w.length)<(d=b.length)&&(f=w,w=b,b=f,o=c,c=d,d=o),o=c+d,f=[];o--;f.push(0));for(g=Rh,m=Oh,o=d;--o>=0;){for(n=0,h=b[o]%m,p=b[o]/m|0,i=o+(s=c);i>o;)n=((u=h*(u=w[--s]%m)+(a=p*u+(l=w[s]/m|0)*h)%m*m+f[i]+n)/g|0)+(a/m|0)+p*l,f[i--]=u%g;f[i]=n}return n?++r:f.splice(0,1),C(e,f,r)},a.negated=function(){var e=new A(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,o=r.s;if(t=(e=new A(e,t)).s,!o||!t)return new A(NaN);if(o!=t)return e.s=-t,r.minus(e);var i=r.e/xh,s=e.e/xh,a=r.c,c=e.c;if(!i||!s){if(!a||!c)return new A(o/0);if(!a[0]||!c[0])return c[0]?e:new A(a[0]?r:0*o)}if(i=Lh(i),s=Lh(s),a=a.slice(),o=i-s){for(o>0?(s=i,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)/Rh|0,a[t]=Rh===a[t]?0:a[t]%Rh;return o&&(a=[o].concat(a),++s),C(e,a,s)},a.precision=a.sd=function(e,t){var n,r,o,i=this;if(null!=e&&e!==!!e)return x(new A(i),Fh(e,1,Ph),null==t?l:Fh(t,0,8));if(!(n=i.c))return null;if(r=(o=n.length-1)*xh+1,o=n[o]){for(;o%10==0;o/=10,r--);for(o=n[0];o>=10;o/=10,r++);}return e&&i.e+1>r&&(r=i.e+1),r},a.shiftedBy=function(e){return this.times("1e"+Fh(e,-Ih,Ih))},a.squareRoot=a.sqrt=function(){var e,t,r,o,i,s=this,a=s.c,c=s.s,d=s.e,h=u+4,p=new A("0.5");if(1!==c||!a||!a[0])return new A(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(c=Math.sqrt(+I(s)))||c==1/0?(((t=Uh(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Lh((d+1)/2)-(d<0||d%2),r=new A(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new A(c+""),r.c[0])for((c=(d=r.e)+h)<3&&(c=0);;)if(i=r,r=p.times(i.plus(n(s,i,h,1))),Uh(i.c).slice(0,c)===(t=Uh(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(s));break}if(!o&&(x(i,i.e+u+2,0),i.times(i).eq(s))){r=i;break}h+=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:Fh(e,0,Ph)+1,t,1)},a.toFixed=function(e,t){return E(this,null==e?e:Fh(e,-Ph,Ph)+this.e+1,t)},a.toFormat=function(e,t,n){var r,o,i,s=this;if(null==n)n=b,null!=e&&(null!=t?"object"==typeof t&&(n=R(t),t=null):"object"!=typeof e||Dh(e)||(n=R(e),e=t=null));else{if("object"!=typeof n)throw Error(Ch+"Argument not an object: "+n);n=R(n)}if(null!=e)if(Dh(e)&&e.length<=2){if(r=e[0],o=e[1],e=s.dp(),null!=o&&e>Fh(o,0,Ph)&&(e=o),null!=r&&0!==Fh(r,0,Ph)){if(null!=o&&r>o)throw Error(Ch+"Minimum must not exceed maximum");e<r&&(e=r)}}else Fh(e,-Ph,Ph);if(i=s.toFixed(e,t),s.s<0&&(i=i.slice(1)),s.c){var a,c=i.split("."),u=+n.groupSize,l=+n.secondaryGroupSize,d=n.groupSeparator||"",h=c[0],p=c[1],f=h.length;if(l&&(a=u,u=l,l=a,f-=a),u>0&&f>0){for(a=f%u||u,i=h.substr(0,a);a<f;a+=u)i+=d+h.substr(a,u);l>0&&(i+=d+h.slice(a))}p&&((a=+n.fractionGroupSize)&&(p=p.replace(new RegExp("\\d{"+a+"}\\B","g"),"$&"+(n.fractionGroupSeparator||""))),i+=(n.decimalSeparator||"")+p)}return(n.prefix||"")+(s.s<0?n.negativeSign||"":s.s>0&&n.positiveSign||"")+i+(n.suffix||"")},a.toFraction=function(e){var t,r,o,i,s,a,u,d,h,p,g,m,y=this,w=y.c;if(null!=e&&(!(u=new A(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(Ch+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+I(u));if(!w)return[new A(y.s||0),new A(0)];for(t=new A(c),h=r=new A(c),o=d=new A(c),m=Uh(w),s=t.e=m.length-y.e-1,t.c[0]=Bh[(a=s%xh)<0?xh+a:a],e=!e||u.comparedTo(t)>0?s>0?t:h:u,a=f,f=1/0,u=new A(m),d.c[0]=0;p=n(u,t,0,1),1!=(i=r.plus(p.times(o))).comparedTo(e);)r=o,o=i,h=d.plus(p.times(i=h)),d=i,t=u.minus(p.times(i=t)),u=i;return i=n(e.minus(r),o,0,1),d=d.plus(i.times(h)),r=r.plus(i.times(o)),d.s=h.s=y.s,g=n(h,o,s*=2,l).minus(y).abs().comparedTo(n(d,r,s,l).minus(y).abs())<1?[h,o]:[d,r],f=a,g},a.toNumber=function(){return+I(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:Fh(e,1,Ph),t,2)},a.toString=function(e){var t,n=this,o=n.s,i=n.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=d||i>=h?Vh(Uh(n.c),i):qh(Uh(n.c),i,"0"):(Fh(e,2,v.length,"Base"),t=r(qh(Uh(n.c),i,"0"),10,e,o,!0)),o<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return I(this)},a._isBigNumber=!0,null!=t&&A.set(t);return A}(),Eh=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,_h=Math.ceil,kh=Math.floor,Ch="[BigNumber Error] ",Rh=1e14,xh=14,Ih=9007199254740991,Bh=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Oh=1e7,Ph=1e9;function Lh(e){var t=0|e;return e>0||e===t?t:t-1}function Uh(e){for(var t,n,r=1,o=e.length,i=e[0]+"";r<o;){for(t=e[r++]+"",n=xh-t.length;n--;t="0"+t);i+=t}for(o=i.length;48===i.charCodeAt(--o););return i.slice(0,o+1||1)}function Nh(e,t){var n,r,o=e.c,i=t.c,s=e.s,a=t.s,c=e.e,u=t.e;if(!s||!a)return null;if(n=o&&!o[0],r=i&&!i[0],n||r)return n?r?0:-a:s;if(s!=a)return s;if(n=s<0,r=c==u,!o||!i)return r?0:!o^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=o.length)<(u=i.length)?c:u,s=0;s<a;s++)if(o[s]!=i[s])return o[s]>i[s]^n?1:-1;return c==u?0:c>u^n?1:-1}function Fh(e,t,n,r){if(e<t||e>n||e!==kh(e))throw Error(Ch+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e));return e}function Dh(e){return"[object Array]"=={}.toString.call(e)}function Mh(e){var t=e.c.length-1;return Lh(e.e/xh)==t&&e.c[t]%2!=0}function Vh(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function qh(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 Hh=Th.clone({STRICT:!0}),zh=2147483647,$h=new Hh(zh);const Gh=1e7;function jh(e,t){if(t.source)try{e.sourceAccount=bh(t.source)}catch{throw new Error("Source address is invalid")}}function Wh(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 Zh(e){const t=new Hh(e).times(Gh);return tl.Int64.fromString(t.toString())}function Kh(e){return new Hh(e.toString()).div(Gh).toFixed(7)}function Xh(e){return new Hh(e.n()).div(new Hh(e.d())).toString()}function Yh(e){let t;if("object"==typeof e&&"n"in e&&"d"in e)t=new tl.Price(e);else{const n=new Hh(e);if(!n.gt(0)||!n.isFinite())throw new Error("price must be positive");const r=function(e){let t,n,r=new Hh(e);const o=[[new Hh(0),new Hh(1)],[new Hh(1),new Hh(0)]];let i=2;for(;!r.gt(zh);){t=r.integerValue(Hh.ROUND_FLOOR),n=r.minus(t);const e=o[i-1],s=o[i-2];if(!e||!s)throw new Error(`Continued fraction approximation failed: missing fraction elements at indices ${i-1} and/or ${i-2}`);const a=t.times(e[0]).plus(s[0]),c=t.times(e[1]).plus(s[1]);if(a.gt(zh)||c.gt(zh))break;if(o.push([a,c]),n.eq(0))break;r=new Hh(1).div(n),i+=1}const s=o[o.length-1];if(!s)throw new Error("Missing last fraction element in continued fraction approximation");const[a,c]=s;if(a.isZero()||c.isZero()){if(new Hh(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=$h;if(t[0].gt(0)&&(e=Hh.min(e,$h.minus(n[0]).div(t[0]).integerValue(Hh.ROUND_FLOOR))),t[1].gt(0)&&(e=Hh.min(e,$h.minus(n[1]).div(t[1]).integerValue(Hh.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 tl.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 Jh(e,t=!1){if("string"!=typeof e)return!1;let n;try{n=new Hh(e)}catch{return!1}return!(!t&&n.isZero()||n.isNegative()||n.times(Gh).gt(new Hh("9223372036854775807").toString())||(n.decimalPlaces()??0)>7||n.isNaN()||!n.isFinite())}function Qh(e){return`${e} argument must be of type String, represent a positive number and have at most 7 digits after the decimal`}function ep(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.amount,!0))throw new TypeError(Qh("amount"));const r=Zh(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=void 0!==e.offerId?e.offerId.toString():"0",s=tl.Int64.fromString(i),a=new tl.ManageSellOfferOp({selling:t,buying:n,amount:r,price:o,offerId:s}),c={sourceAccount:null,body:tl.OperationBody.manageSellOffer(a)};return jh(c,e),new tl.Operation(c)}function tp(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.amount))throw new TypeError(Qh("amount"));const r=Zh(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=new tl.CreatePassiveSellOfferOp({selling:t,buying:n,amount:r,price:o}),s={sourceAccount:null,body:tl.OperationBody.createPassiveSellOffer(i)};return jh(s,e),new tl.Operation(s)}function np(e){let t;try{t=tl.OperationBody.accountMerge(bh(e.destination))}catch{throw new Error("destination is invalid")}const n={sourceAccount:null,body:t};return jh(n,e),new tl.Operation(n)}function rp(e){if(!ih.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");const t=lh.fromPublicKey(e.trustor).xdrAccountId();let n,r;if(e.assetCode.length<=4){const t=oo.Buffer.from(e.assetCode.padEnd(4,"\0"));n=tl.AssetCode.assetTypeCreditAlphanum4(t)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");{const t=oo.Buffer.from(e.assetCode.padEnd(12,"\0"));n=tl.AssetCode.assetTypeCreditAlphanum12(t)}}if("boolean"==typeof e.authorize)r=e.authorize?tl.TrustLineFlags.authorizedFlag().value:0;else{if(null==e.authorize)throw new Error("authorize is required");r=e.authorize}const o=new tl.AllowTrustOp({trustor:t,asset:n,authorize:r}),i={sourceAccount:null,body:tl.OperationBody.allowTrust(o)};return jh(i,e),new tl.Operation(i)}function op(e){if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new Hh(e.bumpTo)}catch{throw new Error("bumpTo must be a stringified number")}const t=tl.Int64.fromString(e.bumpTo),n=new tl.BumpSequenceOp({bumpTo:t}),r={sourceAccount:null,body:tl.OperationBody.bumpSequence(n)};return jh(r,e),new tl.Operation(r)}function ip(e){const t=e.asset??e.line;let n;if(t instanceof ph)n=t.toChangeTrustXDRObject();else{if(!(t instanceof mh))throw new TypeError("asset must be Asset or LiquidityPoolAsset");n=t.toXDRObject()}if(void 0!==e.limit&&!Jh(e.limit,!0))throw new TypeError(Qh("limit"));const r=e.limit?Zh(e.limit):tl.Int64.fromString("9223372036854775807"),o=new tl.ChangeTrustOp({line:n,limit:r}),i={sourceAccount:null,body:tl.OperationBody.changeTrust(o)};return jh(i,e),new tl.Operation(i)}function sp(e){if(!ih.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!Jh(e.startingBalance,!0))throw new TypeError(Qh("startingBalance"));const t=new tl.CreateAccountOp({destination:lh.fromPublicKey(e.destination).xdrAccountId(),startingBalance:Zh(e.startingBalance)}),n={sourceAccount:null,body:tl.OperationBody.createAccount(t)};return jh(n,e),new tl.Operation(n)}function ap(e){if(!(e.asset instanceof ph))throw new Error("must provide an asset for create claimable balance operation");if(!Jh(e.amount))throw new TypeError(Qh("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=Zh(e.amount),r=e.claimants.map(e=>e.toXDRObject()),o=new tl.CreateClaimableBalanceOp({asset:t,amount:n,claimants:r}),i={sourceAccount:null,body:tl.OperationBody.createClaimableBalance(o)};return jh(i,e),new tl.Operation(i)}function cp(e={}){up(e.balanceId);const t=tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n=new tl.ClaimClaimableBalanceOp({balanceId:t}),r={sourceAccount:null,body:tl.OperationBody.claimClaimableBalance(n)};return jh(r,e),new tl.Operation(r)}function up(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}function lp(e={}){up(e.balanceId);const t=tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n={sourceAccount:null,body:tl.OperationBody.clawbackClaimableBalance(new tl.ClawbackClaimableBalanceOp({balanceId:t}))};return jh(n,e),new tl.Operation(n)}function dp(e={}){const t={sourceAccount:null,body:tl.OperationBody.inflation()};return jh(t,e),new tl.Operation(t)}function hp(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&&!oo.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?oo.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 tl.ManageDataOp({dataName:e.name,dataValue:t}),r={sourceAccount:null,body:tl.OperationBody.manageData(n)};return jh(r,e),new tl.Operation(r)}function pp(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.buyAmount,!0))throw new TypeError(Qh("buyAmount"));const r=Zh(e.buyAmount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=void 0!==e.offerId?e.offerId.toString():"0",s=tl.Int64.fromString(i),a=new tl.ManageBuyOfferOp({selling:t,buying:n,buyAmount:r,price:o,offerId:s}),c={sourceAccount:null,body:tl.OperationBody.manageBuyOffer(a)};return jh(c,e),new tl.Operation(c)}function fp(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!Jh(e.sendMax))throw new TypeError(Qh("sendMax"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!Jh(e.destAmount))throw new TypeError(Qh("destAmount"));let t;try{t=bh(e.destination)}catch{throw new Error("destination is invalid")}const n=e.path?e.path:[],r=new tl.PathPaymentStrictReceiveOp({sendAsset:e.sendAsset.toXDRObject(),sendMax:Zh(e.sendMax),destination:t,destAsset:e.destAsset.toXDRObject(),destAmount:Zh(e.destAmount),path:n.map(e=>e.toXDRObject())}),o={sourceAccount:null,body:tl.OperationBody.pathPaymentStrictReceive(r)};return jh(o,e),new tl.Operation(o)}function gp(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!Jh(e.sendAmount))throw new TypeError(Qh("sendAmount"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!Jh(e.destMin))throw new TypeError(Qh("destMin"));const t=e.sendAsset.toXDRObject(),n=Zh(e.sendAmount);let r;try{r=bh(e.destination)}catch{throw new Error("destination is invalid")}const o=e.destAsset.toXDRObject(),i=Zh(e.destMin),s=(e.path??[]).map(e=>e.toXDRObject()),a=new tl.PathPaymentStrictSendOp({sendAsset:t,sendAmount:n,destination:r,destAsset:o,destMin:i,path:s}),c={sourceAccount:null,body:tl.OperationBody.pathPaymentStrictSend(a)};return jh(c,e),new tl.Operation(c)}function mp(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!Jh(e.amount))throw new TypeError(Qh("amount"));let t;try{t=bh(e.destination)}catch{throw new Error("destination is invalid")}const n=new tl.PaymentOp({destination:t,asset:e.asset.toXDRObject(),amount:Zh(e.amount)}),r={sourceAccount:null,body:tl.OperationBody.payment(n)};return jh(r,e),new tl.Operation(r)}function yp(e,t){if(e>=0&&e<=255)return!0;throw new Error(`${t} value must be between 0 and 255`)}function wp(e){let t=null;if(e.inflationDest){if(!ih.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t=lh.fromPublicKey(e.inflationDest).xdrAccountId()}const n=Wh("clearFlags",e.clearFlags)??null,r=Wh("setFlags",e.setFlags)??null,o=Wh("masterWeight",e.masterWeight,yp)??null,i=Wh("lowThreshold",e.lowThreshold,yp)??null,s=Wh("medThreshold",e.medThreshold,yp)??null,a=Wh("highThreshold",e.highThreshold,yp)??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=Wh("signer.weight",e.signer.weight,yp);let n,r=0;if(e.signer.ed25519PublicKey){if(!ih.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const t=ih.decodeEd25519PublicKey(e.signer.ed25519PublicKey);n=tl.SignerKey.signerKeyTypeEd25519(t),r+=1}if(e.signer.preAuthTx){let t;if(t="string"==typeof e.signer.preAuthTx?oo.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!oo.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");n=tl.SignerKey.signerKeyTypePreAuthTx(t),r+=1}if(e.signer.sha256Hash){let t;if(t="string"==typeof e.signer.sha256Hash?oo.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!oo.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");n=tl.SignerKey.signerKeyTypeHashX(t),r+=1}if(e.signer.ed25519SignedPayload){if(!ih.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const t=ih.decodeSignedPayload(e.signer.ed25519SignedPayload),o=tl.SignerKeyEd25519SignedPayload.fromXDR(t);n=tl.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 tl.Signer({key:n,weight:t})}const l=new tl.SetOptionsOp({inflationDest:t,clearFlags:n,setFlags:r,masterWeight:o,lowThreshold:i,medThreshold:s,highThreshold:a,homeDomain:c,signer:u}),d={sourceAccount:null,body:tl.OperationBody.setOptions(l)};return jh(d,e),new tl.Operation(d)}function bp(e){if(!ih.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");const t=new tl.BeginSponsoringFutureReservesOp({sponsoredId:lh.fromPublicKey(e.sponsoredId).xdrAccountId()}),n={sourceAccount:null,body:tl.OperationBody.beginSponsoringFutureReserves(t)};return jh(n,e),new tl.Operation(n)}function vp(e={}){const t={sourceAccount:null,body:tl.OperationBody.endSponsoringFutureReserves()};return jh(t,e),new tl.Operation(t)}function Ap(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");const t=tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(e.account).xdrAccountId()})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Sp(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.asset instanceof ph)t=e.asset.toTrustLineXDRObject();else{if(!(e.asset instanceof wh))throw new TypeError("asset must be an Asset or LiquidityPoolId");t=e.asset.toXDRObject()}const n=tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(e.account).xdrAccountId(),asset:t})),r=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(n),o={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(r)};return jh(o,e),new tl.Operation(o)}function Tp(e={}){if(!ih.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");const t=tl.LedgerKey.offer(new tl.LedgerKeyOffer({sellerId:lh.fromPublicKey(e.seller).xdrAccountId(),offerId:tl.Int64.fromString(e.offerId)})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Ep(e={}){if(!ih.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=tl.LedgerKey.data(new tl.LedgerKeyData({accountId:lh.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function _p(e={}){if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");const t=tl.LedgerKey.claimableBalance(new tl.LedgerKeyClaimableBalance({balanceId:tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function kp(e={}){if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");const t=tl.LedgerKey.liquidityPool(new tl.LedgerKeyLiquidityPool({liquidityPoolId:oo.Buffer.from(e.liquidityPoolId,"hex")})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Cp(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.signer.ed25519PublicKey){if(!ih.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const n=ih.decodeEd25519PublicKey(e.signer.ed25519PublicKey);t=tl.SignerKey.signerKeyTypeEd25519(n)}else if(e.signer.preAuthTx){let n;if(n="string"==typeof e.signer.preAuthTx?oo.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!oo.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");t=tl.SignerKey.signerKeyTypePreAuthTx(n)}else if(e.signer.sha256Hash){let n;if(n="string"==typeof e.signer.sha256Hash?oo.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!oo.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");t=tl.SignerKey.signerKeyTypeHashX(n)}else{if(!e.signer.ed25519SignedPayload)throw new Error("signer is invalid");{if(!ih.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const n=ih.decodeSignedPayload(e.signer.ed25519SignedPayload),r=tl.SignerKeyEd25519SignedPayload.fromXDR(n);t=tl.SignerKey.signerKeyTypeEd25519SignedPayload(r)}}const n=new tl.RevokeSponsorshipOpSigner({accountId:lh.fromPublicKey(e.account).xdrAccountId(),signerKey:t}),r=tl.RevokeSponsorshipOp.revokeSponsorshipSigner(n),o={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(r)};return jh(o,e),new tl.Operation(o)}function Rp(e){if(!Jh(e.amount))throw new TypeError(Qh("amount"));let t;try{t=bh(e.from)}catch{throw new Error("from address is invalid")}const n=new tl.ClawbackOp({amount:Zh(e.amount),asset:e.asset.toXDRObject(),from:t}),r={sourceAccount:null,body:tl.OperationBody.clawback(n)};return jh(r,e),new tl.Operation(r)}function xp(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:tl.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:tl.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:tl.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 i=e.flags[o],s=t[o];if(!s)throw new Error(`Invalid flag name: ${o}`);if("boolean"!=typeof i&&void 0!==i)throw new TypeError(`opts.flags.${o} must be a boolean (got ${typeof i})`);!0===i?r|=s.value:!1===i&&(n|=s.value)});const o=lh.fromPublicKey(e.trustor).xdrAccountId(),i=e.asset.toXDRObject(),s={sourceAccount:null,body:tl.OperationBody.setTrustLineFlags(new tl.SetTrustLineFlagsOp({trustor:o,asset:i,clearFlags:n,setFlags:r}))};return jh(s,e),new tl.Operation(s)}function Ip(e={}){const{liquidityPoolId:t,maxAmountA:n,maxAmountB:r,minPrice:o,maxPrice:i}=e;if(!t)throw new TypeError("liquidityPoolId argument is required");const s=oo.Buffer.from(t,"hex");if(!Jh(n,!0))throw new TypeError(Qh("maxAmountA"));const a=Zh(n);if(!Jh(r,!0))throw new TypeError(Qh("maxAmountB"));const c=Zh(r);if(void 0===o)throw new TypeError("minPrice argument is required");const u=Yh(o);if(void 0===i)throw new TypeError("maxPrice argument is required");const l=Yh(i),d=new tl.LiquidityPoolDepositOp({liquidityPoolId:s,maxAmountA:a,maxAmountB:c,minPrice:u,maxPrice:l}),h={sourceAccount:null,body:tl.OperationBody.liquidityPoolDeposit(d)};return jh(h,e),new tl.Operation(h)}function Bp(e={}){if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");const t=oo.Buffer.from(e.liquidityPoolId,"hex");if(!Jh(e.amount))throw new TypeError(Qh("amount"));const n=Zh(e.amount);if(!Jh(e.minAmountA,!0))throw new TypeError(Qh("minAmountA"));const r=Zh(e.minAmountA);if(!Jh(e.minAmountB,!0))throw new TypeError(Qh("minAmountB"));const o=Zh(e.minAmountB),i=new tl.LiquidityPoolWithdrawOp({liquidityPoolId:t,amount:n,minAmountA:r,minAmountB:o}),s={sourceAccount:null,body:tl.OperationBody.liquidityPoolWithdraw(i)};return jh(s,e),new tl.Operation(s)}class Op{_type;_key;constructor(e){if(ih.isValidEd25519PublicKey(e))this._type="account",this._key=ih.decodeEd25519PublicKey(e);else if(ih.isValidContract(e))this._type="contract",this._key=ih.decodeContract(e);else if(ih.isValidMed25519PublicKey(e))this._type="muxedAccount",this._key=ih.decodeMed25519PublicKey(e);else if(ih.isValidClaimableBalance(e))this._type="claimableBalance",this._key=ih.decodeClaimableBalance(e);else{if(!ih.isValidLiquidityPool(e))throw new Error(`Unsupported address type: ${e}`);this._type="liquidityPool",this._key=ih.decodeLiquidityPool(e)}}static fromString(e){return new Op(e)}static account(e){return new Op(ih.encodeEd25519PublicKey(e))}static contract(e){return new Op(ih.encodeContract(e))}static claimableBalance(e){return new Op(ih.encodeClaimableBalance(e))}static liquidityPool(e){return new Op(ih.encodeLiquidityPool(e))}static muxedAccount(e){return new Op(ih.encodeMed25519PublicKey(e))}static fromScVal(e){return Op.fromScAddress(e.address())}static fromScAddress(e){switch(e.switch().value){case tl.ScAddressType.scAddressTypeAccount().value:return Op.account(e.accountId().ed25519());case tl.ScAddressType.scAddressTypeContract().value:return Op.contract(e.contractId());case tl.ScAddressType.scAddressTypeMuxedAccount().value:{const t=oo.Buffer.concat([e.muxedAccount().ed25519(),e.muxedAccount().id().toXDR("raw")]);return Op.muxedAccount(t)}case tl.ScAddressType.scAddressTypeClaimableBalance().value:{const t=e.claimableBalanceId();return Op.claimableBalance(oo.Buffer.concat([oo.Buffer.from([t.switch().value]),t.v0()]))}case tl.ScAddressType.scAddressTypeLiquidityPool().value:return Op.liquidityPool(e.liquidityPoolId());default:throw new Error(`Unsupported address type: ${e.switch().name}`)}}toString(){switch(this._type){case"account":return ih.encodeEd25519PublicKey(this._key);case"contract":return ih.encodeContract(this._key);case"claimableBalance":return ih.encodeClaimableBalance(this._key);case"liquidityPool":return ih.encodeLiquidityPool(this._key);case"muxedAccount":return ih.encodeMed25519PublicKey(this._key);default:throw new Error("Unsupported address type")}}toScVal(){return tl.ScVal.scvAddress(this.toScAddress())}toScAddress(){switch(this._type){case"account":return tl.ScAddress.scAddressTypeAccount(tl.PublicKey.publicKeyTypeEd25519(this._key));case"contract":return tl.ScAddress.scAddressTypeContract(this._key);case"liquidityPool":return tl.ScAddress.scAddressTypeLiquidityPool(this._key);case"claimableBalance":return tl.ScAddress.scAddressTypeClaimableBalance(tl.ClaimableBalanceId.claimableBalanceIdTypeV0(this._key.subarray(1)));case"muxedAccount":return tl.ScAddress.scAddressTypeMuxedAccount(new tl.MuxedEd25519Account({ed25519:this._key.subarray(0,32),id:tl.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 Pp(e){if(!e.func)throw new TypeError(`host function invocation ('func') required (got ${JSON.stringify(e)})`);e.func.switch().value===tl.HostFunctionType.hostFunctionTypeInvokeContract().value&&e.func.invokeContract().args().forEach(e=>{let t;try{t=Op.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 tl.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),n={sourceAccount:null,body:tl.OperationBody.invokeHostFunction(t)};return jh(n,e),new tl.Operation(n)}function Lp(e){const t=new Op(e.contract);if("contract"!==t.type)throw new TypeError(`expected contract strkey instance, got ${t.toString()}`);return Pp({func:tl.HostFunction.hostFunctionTypeInvokeContract(new tl.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 Up(e){const t=oo.Buffer.from(e.salt||lh.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 Pp({func:tl.HostFunction.hostFunctionTypeCreateContractV2(new tl.CreateContractArgsV2({executable:tl.ContractExecutable.contractExecutableWasm(oo.Buffer.from(e.wasmHash)),contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAddress(new tl.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 Np(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 ph(r,n[1])}if(!(t instanceof ph))throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);return Pp({func:tl.HostFunction.hostFunctionTypeCreateContract(new tl.CreateContractArgs({executable:tl.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())})),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Fp(e){return Pp({func:tl.HostFunction.hostFunctionTypeUploadContractWasm(oo.Buffer.from(e.wasm)),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Dp(e){if((e.extendTo??-1)<=0)throw new RangeError("extendTo has to be positive");const t=new tl.ExtendFootprintTtlOp({ext:new tl.ExtensionPoint(0),extendTo:e.extendTo}),n={sourceAccount:null,body:tl.OperationBody.extendFootprintTtl(t)};return jh(n,e),new tl.Operation(n)}function Mp(e={}){const t=new tl.RestoreFootprintOp({ext:new tl.ExtensionPoint(0)}),n={sourceAccount:null,body:tl.OperationBody.restoreFootprint(t)};return jh(n,e),new tl.Operation(n)}class Vp{static fromXDRObject(e){const t={},n=e.sourceAccount();n&&(t.source=vh(n));const r=e.body().value(),o=e.body().switch().name;switch(o){case"createAccount":t.type="createAccount",t.destination=qp(r.destination()),t.startingBalance=Kh(r.startingBalance());break;case"payment":t.type="payment",t.destination=vh(r.destination()),t.asset=ph.fromOperation(r.asset()),t.amount=Kh(r.amount());break;case"pathPaymentStrictReceive":{t.type="pathPaymentStrictReceive",t.sendAsset=ph.fromOperation(r.sendAsset()),t.sendMax=Kh(r.sendMax()),t.destination=vh(r.destination()),t.destAsset=ph.fromOperation(r.destAsset()),t.destAmount=Kh(r.destAmount()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(ph.fromOperation(e[n]))});break}case"pathPaymentStrictSend":{t.type="pathPaymentStrictSend",t.sendAsset=ph.fromOperation(r.sendAsset()),t.sendAmount=Kh(r.sendAmount()),t.destination=vh(r.destination()),t.destAsset=ph.fromOperation(r.destAsset()),t.destMin=Kh(r.destMin()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(ph.fromOperation(e[n]))});break}case"changeTrust":if(t.type="changeTrust",r.line().switch()===tl.AssetType.assetTypePoolShare())t.line=mh.fromOperation(r.line());else t.line=ph.fromOperation(r.line());t.limit=Kh(r.limit());break;case"allowTrust":t.type="allowTrust",t.trustor=qp(r.trustor()),t.assetCode=r.asset().value().toString(),t.assetCode=Yd(t.assetCode,"\0"),t.authorize=r.authorize();break;case"setOptions":if(t.type="setOptions",r.inflationDest()&&(t.inflationDest=qp(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=qp(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=ih.encodeSignedPayload(t.toXDR())}e.weight=r.signer().weight(),t.signer=e}break;case"manageOffer":case"manageSellOffer":t.type="manageSellOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.amount=Kh(r.amount()),t.price=Xh(r.price()),t.offerId=r.offerId().toString();break;case"manageBuyOffer":t.type="manageBuyOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.buyAmount=Kh(r.buyAmount()),t.price=Xh(r.price()),t.offerId=r.offerId().toString();break;case"createPassiveOffer":case"createPassiveSellOffer":t.type="createPassiveSellOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.amount=Kh(r.amount()),t.price=Xh(r.price());break;case"accountMerge":t.type="accountMerge",t.destination=vh(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=ph.fromOperation(r.asset()),t.amount=Kh(r.amount()),t.claimants=[],r.claimants().forEach(e=>{t.claimants.push(yh.fromXDR(e))});break;case"claimClaimableBalance":t.type="claimClaimableBalance",t.balanceId=r.toXDR("hex");break;case"beginSponsoringFutureReserves":t.type="beginSponsoringFutureReserves",t.sponsoredId=qp(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 tl.LedgerEntryType.account().name:t.type="revokeAccountSponsorship",t.account=qp(n.account().accountId());break;case tl.LedgerEntryType.trustline().name:{t.type="revokeTrustlineSponsorship",t.account=qp(n.trustLine().accountId());const e=n.trustLine().asset();if(e.switch()===tl.AssetType.assetTypePoolShare())t.asset=wh.fromOperation(e);else t.asset=ph.fromOperation(e);break}case tl.LedgerEntryType.offer().name:t.type="revokeOfferSponsorship",t.seller=qp(n.offer().sellerId()),t.offerId=n.offer().offerId().toString();break;case tl.LedgerEntryType.data().name:t.type="revokeDataSponsorship",t.account=qp(n.data().accountId()),t.name=n.data().dataName().toString("ascii");break;case tl.LedgerEntryType.claimableBalance().name:t.type="revokeClaimableBalanceSponsorship",t.balanceId=n.claimableBalance().balanceId().toXDR("hex");break;case tl.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=qp(e.signer().accountId()),t.signer=function(e){const t={};switch(e.switch().name){case tl.SignerKeyType.signerKeyTypeEd25519().name:t.ed25519PublicKey=ih.encodeEd25519PublicKey(e.ed25519());break;case tl.SignerKeyType.signerKeyTypePreAuthTx().name:t.preAuthTx=e.preAuthTx().toString("hex");break;case tl.SignerKeyType.signerKeyTypeHashX().name:t.sha256Hash=e.hashX().toString("hex");break;case tl.SignerKeyType.signerKeyTypeEd25519SignedPayload().name:{const n=e.ed25519SignedPayload();t.ed25519SignedPayload=ih.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=Kh(r.amount()),t.from=vh(r.from()),t.asset=ph.fromOperation(r.asset());break;case"clawbackClaimableBalance":t.type="clawbackClaimableBalance",t.balanceId=r.toXDR("hex");break;case"setTrustLineFlags":{t.type="setTrustLineFlags",t.asset=ph.fromOperation(r.asset()),t.trustor=qp(r.trustor());const e=r.clearFlags(),n=r.setFlags(),o={authorized:tl.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:tl.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:tl.TrustLineFlags.trustlineClawbackEnabledFlag()},i=t=>{const r=o[t]?.value??0;return!!(n&r)||!(e&r)&&void 0},s={};Object.keys(o).forEach(e=>{s[e]=i(e)}),t.flags=s;break}case"liquidityPoolDeposit":t.type="liquidityPoolDeposit",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.maxAmountA=Kh(r.maxAmountA()),t.maxAmountB=Kh(r.maxAmountB()),t.minPrice=Xh(r.minPrice()),t.maxPrice=Xh(r.maxPrice());break;case"liquidityPoolWithdraw":t.type="liquidityPoolWithdraw",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.amount=Kh(r.amount()),t.minAmountA=Kh(r.minAmountA()),t.minAmountB=Kh(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=np;static allowTrust=rp;static bumpSequence=op;static changeTrust=ip;static createAccount=sp;static createClaimableBalance=ap;static claimClaimableBalance=cp;static clawbackClaimableBalance=lp;static createPassiveSellOffer=tp;static inflation=dp;static manageData=hp;static manageSellOffer=ep;static manageBuyOffer=pp;static pathPaymentStrictReceive=fp;static pathPaymentStrictSend=gp;static payment=mp;static setOptions=wp;static beginSponsoringFutureReserves=bp;static endSponsoringFutureReserves=vp;static revokeAccountSponsorship=Ap;static revokeTrustlineSponsorship=Sp;static revokeOfferSponsorship=Tp;static revokeDataSponsorship=Ep;static revokeClaimableBalanceSponsorship=_p;static revokeLiquidityPoolSponsorship=kp;static revokeSignerSponsorship=Cp;static clawback=Rp;static setTrustLineFlags=xp;static liquidityPoolDeposit=Ip;static liquidityPoolWithdraw=Bp;static invokeHostFunction=Pp;static extendFootprintTtl=Dp;static restoreFootprint=Mp;static createStellarAssetContract=Np;static invokeContractFunction=Lp;static createCustomContract=Up;static uploadContractWasm=Fp}function qp(e){return ih.encodeEd25519PublicKey(e.ed25519())}const Hp="none",zp="id",$p="text",Gp="hash",jp="return";class Wp{_type;_value;constructor(e,t=null){switch(this._type=e,this._value=t,this._type){case Hp:break;case zp:Wp._validateIdValue(t);break;case $p:Wp._validateTextValue(t);break;case Gp:case jp:Wp._validateHashValue(t),"string"==typeof t&&(this._value=oo.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 Hp:return null;case zp:case $p:return this._value;case Gp:case jp:return oo.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 Hh(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(oo.Buffer.byteLength(e,"utf8")>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(oo.Buffer.isBuffer(e)){if(e.length>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(!tl.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=oo.Buffer.from(e,"hex")}else{if(!oo.Buffer.isBuffer(e))throw t;n=oo.Buffer.from(e)}if(!n.length||32!==n.length)throw t}static none(){return new Wp(Hp)}static text(e){return new Wp($p,e)}static id(e){return new Wp(zp,e)}static hash(e){return new Wp(Gp,e)}static return(e){return new Wp(jp,e)}toXDRObject(){switch(this._type){case Hp:return tl.Memo.memoNone();case zp:return tl.Memo.memoId(tl.Uint64.fromString(el.UnsignedHyper.fromString(this._value).toString()));case $p:return tl.Memo.memoText(this._value);case Gp:return tl.Memo.memoHash(this._value);case jp:return tl.Memo.memoReturn(this._value);default:throw new Error("Invalid memo type")}}static fromXDRObject(e){switch(e.switch()){case tl.MemoType.memoId():return Wp.id(e.id().toString());case tl.MemoType.memoText():return Wp.text(e.value());case tl.MemoType.memoHash():return Wp.hash(e.hash());case tl.MemoType.memoReturn():return Wp.return(e.retHash())}if(void 0===e.value())return Wp.none();throw new Error("Unknown type")}}class Zp extends gh{_envelopeType;_source="";_memo;_sequence;_operations;_timeBounds;_ledgerBounds;_minAccountSequence;_minAccountSequenceAge;_minAccountSequenceLedgerGap;_extraSigners;constructor(e,t){if("string"==typeof e){const t=oo.Buffer.from(e,"base64");e=tl.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==tl.EnvelopeType.envelopeTypeTxV0()&&n!==tl.EnvelopeType.envelopeTypeTx())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${n.name}.`);const r=e.value(),o=r.tx(),i=o.fee().toString();if(super(o,(r.signatures()||[]).slice(),i,t),this._envelopeType=n,this._memo=o.memo(),this._sequence=o.seqNum().toString(),this._envelopeType===tl.EnvelopeType.envelopeTypeTxV0())this._source=ih.encodeEd25519PublicKey(o.sourceAccountEd25519());else this._source=vh(o.sourceAccount());let s=null,a=null;switch(this._envelopeType){case tl.EnvelopeType.envelopeTypeTxV0():a=o.timeBounds();break;case tl.EnvelopeType.envelopeTypeTx():switch(o.cond().switch()){case tl.PreconditionType.precondTime():a=o.cond().timeBounds();break;case tl.PreconditionType.precondV2():s=o.cond().v2(),a=s.timeBounds()}}if(a&&(this._timeBounds={minTime:a.minTime().toString(),maxTime:a.maxTime().toString()}),s){const e=s.ledgerBounds();e&&(this._ledgerBounds={minLedger:e.minLedger(),maxLedger:e.maxLedger()});const t=s.minSeqNum();t&&(this._minAccountSequence=t.toString()),this._minAccountSequenceAge=s.minSeqAge().toBigInt(),this._minAccountSequenceLedgerGap=s.minSeqLedgerGap(),this._extraSigners=s.extraSigners()}const c=o.operations()||[];this._operations=c.map(e=>Vp.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 Wp.fromXDRObject(this._memo)}set memo(e){throw new Error("Transaction is immutable")}signatureBase(){let e=this.tx;this._envelopeType===tl.EnvelopeType.envelopeTypeTxV0()&&(e=tl.Transaction.fromXDR(oo.Buffer.concat([oo.Buffer.alloc(4),e.toXDR()])));const t=tl.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(e);return new tl.TransactionSignaturePayload({networkId:tl.Hash.fromXDR($l(this.networkPassphrase)),taggedTransaction:t}).toXDR()}toEnvelope(){const e=this.tx.toXDR(),t=this.signatures.slice();let n;switch(this._envelopeType){case tl.EnvelopeType.envelopeTypeTxV0():n=tl.TransactionEnvelope.envelopeTypeTxV0(new tl.TransactionV0Envelope({tx:tl.TransactionV0.fromXDR(e),signatures:t}));break;case tl.EnvelopeType.envelopeTypeTx():n=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:tl.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{Vp.createClaimableBalance(t)}catch(e){throw new TypeError(`expected createClaimableBalance, got ${t.type}: ${String(e)}`)}const n=ih.decodeEd25519PublicKey(Sh(this.source)),r=$l(tl.HashIdPreimage.envelopeTypeOpId(new tl.HashIdPreimageOperationId({sourceAccount:tl.PublicKey.publicKeyTypeEd25519(n),seqNum:tl.Int64.fromString(this.sequence),opNum:e})).toXDR("raw"));return tl.ClaimableBalanceId.claimableBalanceIdTypeV0(r).toXDR("hex")}}class Kp extends gh{_feeSource;_innerTransaction;constructor(e,t){if("string"==typeof e){const t=oo.Buffer.from(e,"base64");e=tl.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==tl.EnvelopeType.envelopeTypeTxFeeBump())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ${n.name}.`);const r=e.value(),o=r.tx(),i=o.fee().toString();super(o,(r.signatures()||[]).slice(),i,t);const s=tl.TransactionEnvelope.envelopeTypeTx(o.innerTx().v1());this._feeSource=vh(this.tx.feeSource()),this._innerTransaction=new Zp(s,t)}get innerTransaction(){return this._innerTransaction}get operations(){return this._innerTransaction.operations}get feeSource(){return this._feeSource}signatureBase(){const e=tl.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx);return new tl.TransactionSignaturePayload({networkId:tl.Hash.fromXDR($l(this.networkPassphrase)),taggedTransaction:e}).toXDR()}toEnvelope(){const e=new tl.FeeBumpTransactionEnvelope({tx:tl.FeeBumpTransaction.fromXDR(this.tx.toXDR()),signatures:this.signatures.slice()});return tl.TransactionEnvelope.envelopeTypeTxFeeBump(e)}}class Xp{_accountId;sequence;constructor(e,t){if(ih.isValidMed25519PublicKey(e))throw new Error("accountId is an M-address; use MuxedAccount instead");if(!ih.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 Hh(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 Yp=BigInt("18446744073709551615");function Jp(e){let t;try{t=BigInt(e)}catch{throw new Error(`id is not a valid uint64 string: ${e}`)}if(t<BigInt(0)||t>Yp)throw new Error(`id value out of range for uint64 [0, ${Yp}]: ${e}`)}class Qp{account;_muxedXdr;_mAddress;_id;constructor(e,t){const n=e.accountId();if(!ih.isValidEd25519PublicKey(n))throw new Error("accountId is invalid");Jp(t),this.account=e,this._muxedXdr=Ah(n,t),this._mAddress=vh(this._muxedXdr),this._id=t}static fromAddress(e,t){const n=bh(e),r=Sh(e),o=n.med25519().id().toString();return new Qp(new Xp(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 Jp(e),this._muxedXdr.med25519().id(tl.Uint64.fromString(e)),this._mAddress=vh(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 ef{_data;constructor(e){let t;t=e?"string"==typeof e||ArrayBuffer.isView(e)?ef.fromXDR(e):ef.fromXDR(e.toXDR()):new tl.SorobanTransactionData({resources:new tl.SorobanResources({footprint:new tl.LedgerFootprint({readOnly:[],readWrite:[]}),instructions:0,diskReadBytes:0,writeBytes:0}),ext:new tl.SorobanTransactionDataExt(0),resourceFee:new tl.Int64(0)}),this._data=t}static fromXDR(e){return"string"==typeof e?tl.SorobanTransactionData.fromXDR(e,"base64"):tl.SorobanTransactionData.fromXDR(oo.Buffer.from(e),"raw")}setResourceFee(e){return this._data.resourceFee(new tl.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 tl.SorobanTransactionData.fromXDR(this._data.toXDR())}getReadOnly(){return this.getFootprint().readOnly()}getReadWrite(){return this.getFootprint().readWrite()}getFootprint(){return this._data.resources().footprint()}}class tf{static decodeAddress(e){const t=ih.getVersionByteForPrefix(e);if(void 0===t)throw new Error(`invalid signer key type (${t})`);const n=ah(t,e);switch(t){case"signedPayload":return tl.SignerKey.signerKeyTypeEd25519SignedPayload(new tl.SignerKeyEd25519SignedPayload({ed25519:n.subarray(0,32),payload:n.subarray(36,36+n.readUInt32BE(32))}));case"ed25519PublicKey":return tl.SignerKey.signerKeyTypeEd25519(n);case"preAuthTx":return tl.SignerKey.signerKeyTypePreAuthTx(n);case"sha256Hash":return tl.SignerKey.signerKeyTypeHashX(n);default:throw new Error(`invalid signer key type (${t})`)}}static encodeSignerKey(e){let t,n;switch(e.switch()){case tl.SignerKeyType.signerKeyTypeEd25519():t="ed25519PublicKey",n=e.value();break;case tl.SignerKeyType.signerKeyTypePreAuthTx():t="preAuthTx",n=e.value();break;case tl.SignerKeyType.signerKeyTypeHashX():t="sha256Hash",n=e.value();break;case tl.SignerKeyType.signerKeyTypeEd25519SignedPayload():t="signedPayload",n=e.ed25519SignedPayload().toXDR("raw");break;default:throw new Error(`invalid SignerKey (type: ${e.switch().name})`)}return ch(t,n)}}class nf{_id;constructor(e){try{this._id=ih.decodeContract(e)}catch{throw new Error(`Invalid contract ID: ${e}`)}}contractId(){return ih.encodeContract(this._id)}toString(){return this.contractId()}address(){return Op.contract(this._id)}call(e,...t){return Vp.invokeContractFunction({contract:this.address().toString(),function:e,args:t})}getFootprint(){return tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:this.address().toScAddress(),key:tl.ScVal.scvLedgerKeyContractInstance(),durability:tl.ContractDataDurability.persistent()}))}}class rf extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 128}}rf.defineIntBoundaries();class of extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 256}}of.defineIntBoundaries();class sf extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 128}}sf.defineIntBoundaries();class af extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 256}}af.defineIntBoundaries();class cf{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 el.Hyper(n);break;case"i128":this.int=new sf(...n);break;case"i256":this.int=new af(...n);break;case"u64":case"timepoint":case"duration":this.int=new el.UnsignedHyper(n);break;case"u128":this.int=new rf(...n);break;case"u256":this.int=new of(...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 tl.ScVal.scvI64(new tl.Int64(e))}toU64(){return this._sizeCheck(64),tl.ScVal.scvU64(new tl.Uint64(BigInt.asUintN(64,this.toBigInt())))}toTimepoint(){return this._sizeCheck(64),tl.ScVal.scvTimepoint(new tl.Uint64(BigInt.asUintN(64,this.toBigInt())))}toDuration(){return this._sizeCheck(64),tl.ScVal.scvDuration(new tl.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 tl.ScVal.scvI128(new tl.Int128Parts({hi:new tl.Int64(t),lo:new tl.Uint64(n)}))}toU128(){this._sizeCheck(128);const e=this.int.toBigInt();return tl.ScVal.scvU128(new tl.UInt128Parts({hi:new tl.Uint64(BigInt.asUintN(64,e>>64n)),lo:new tl.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 tl.ScVal.scvI256(new tl.Int256Parts({hiHi:new tl.Int64(t),hiLo:new tl.Uint64(n),loHi:new tl.Uint64(r),loLo:new tl.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 tl.ScVal.scvU256(new tl.UInt256Parts({hiHi:new tl.Uint64(t),hiLo:new tl.Uint64(n),loHi:new tl.Uint64(r),loLo:new tl.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 uf extends cf{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 lf(e){const t=e.switch().name,n=cf.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 cf(n,r).toBigInt();case"scvU128":case"scvI128":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new cf(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 cf(n,[e.loLo(),e.loHi(),e.hiLo(),e.hiHi()]).toBigInt()}default:throw TypeError(`expected integer type, got ${t}`)}}function df(e,t={}){switch(typeof e){case"object":{if(null===e)return tl.ScVal.scvVoid();if(e instanceof tl.ScVal)return e;if(e instanceof Op)return e.toScVal();if(e instanceof lh)return df(e.publicKey(),{type:"address"});if(e instanceof nf)return e.address().toScVal();if(e instanceof Uint8Array||oo.Buffer.isBuffer(e)){const n=oo.Buffer.from(e);switch(t?.type??"bytes"){case"bytes":return tl.ScVal.scvBytes(n);case"symbol":return tl.ScVal.scvSymbol(n);case"string":return tl.ScVal.scvString(n);default:throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for bytes-like value`)}}if(Array.isArray(e))return tl.ScVal.scvVec(e.map((e,n)=>Array.isArray(t.type)?df(e,{...t.type.length>n&&{type:t.type[n]}}):df(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 tl.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],i=r?{type:r}:{},s=o?{type:o}:{};return new tl.ScMapEntry({key:df(e,i),val:df(t,s)})}))}case"number":case"bigint":{const n=BigInt(e);switch(t?.type){case"u32":if(n<BigInt(tl.Uint32.MIN_VALUE)||n>BigInt(tl.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return tl.ScVal.scvU32(Number(e));case"i32":if(n<-BigInt(tl.Int32.MIN_VALUE)||n>BigInt(tl.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return tl.ScVal.scvI32(Number(e))}return new uf(e,{type:t?.type}).toScVal()}case"string":{const n=t?.type??"string";switch(n){case"string":return tl.ScVal.scvString(e);case"symbol":return tl.ScVal.scvSymbol(e);case"address":return new Op(e).toScVal();case"u32":{const t=BigInt(e);if(t<BigInt(tl.Uint32.MIN_VALUE)||t>BigInt(tl.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return tl.ScVal.scvU32(Number(t))}case"i32":{const t=BigInt(e);if(t<-BigInt(tl.Int32.MIN_VALUE)||t>BigInt(tl.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return tl.ScVal.scvI32(Number(t))}default:if(cf.isType(n))return new cf(n,e).toScVal();throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for string value`)}}case"boolean":return tl.ScVal.scvBool(e);case"undefined":return tl.ScVal.scvVoid();case"function":return df(e());default:throw new TypeError(`failed to convert typeof ${typeof e} (${JSON.stringify(e)})`)}}function hf(e){switch(e.switch().value){case tl.ScValType.scvVoid().value:return null;case tl.ScValType.scvU64().value:case tl.ScValType.scvI64().value:return e.value().toBigInt();case tl.ScValType.scvU128().value:case tl.ScValType.scvI128().value:case tl.ScValType.scvU256().value:case tl.ScValType.scvI256().value:return lf(e);case tl.ScValType.scvVec().value:return(e.vec()??[]).map(hf);case tl.ScValType.scvAddress().value:return Op.fromScVal(e).toString();case tl.ScValType.scvMap().value:return Object.fromEntries((e.map()??[]).map(e=>[hf(e.key()),hf(e.val())]));case tl.ScValType.scvBool().value:case tl.ScValType.scvU32().value:case tl.ScValType.scvI32().value:case tl.ScValType.scvBytes().value:return e.value();case tl.ScValType.scvSymbol().value:{const t=e.sym();if(oo.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case tl.ScValType.scvString().value:{const t=e.str();if(oo.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case tl.ScValType.scvTimepoint().value:case tl.ScValType.scvDuration().value:return e.value().toBigInt();case tl.ScValType.scvError().value:if(e.error().switch().value===tl.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 pf(e){const t=Array.from(e).sort((e,t)=>{const n=hf(e.key()),r=hf(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 tl.ScVal.scvMap(t)}tl.scvSortedMap=pf;const ff=el.Hyper.MAX_VALUE,gf=4294967295,mf="100";class yf{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=bf(t.timebounds.minTime),n=bf(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||Wp.none(),this.networkPassphrase=t.networkPassphrase||null,this.sorobanData=t.sorobanData?new ef(t.sorobanData).build():null}static cloneFrom(e,t={}){if(!(e instanceof Zp))throw new TypeError(`expected a 'Transaction', got: ${String(e)}`);const n=(BigInt(e.sequence)-1n).toString();let r;if(ih.isValidMed25519PublicKey(e.source))r=Qp.fromAddress(e.source,n);else{if(!ih.isValidEd25519PublicKey(e.source))throw new TypeError(`unsupported tx source account: ${e.source}`);r=new Xp(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 o={fee:(Math.floor(parseInt(e.fee,10)/e.operations.length)||mf).toString(),memo:e.memo,networkPassphrase:e.networkPassphrase};e.timeBounds&&(o.timebounds=e.timeBounds),e.ledgerBounds&&(o.ledgerbounds=e.ledgerBounds),e.minAccountSequence&&(o.minAccountSequence=e.minAccountSequence),void 0!==e.minAccountSequenceAge&&(o.minAccountSequenceAge=e.minAccountSequenceAge),void 0!==e.minAccountSequenceLedgerGap&&(o.minAccountSequenceLedgerGap=e.minAccountSequenceLedgerGap),e.extraSigners&&(o.extraSigners=e.extraSigners.map(e=>tf.encodeSignerKey(e))),Object.assign(o,t);const i=new yf(r,o);return e.tx.operations().forEach(e=>i.addOperation(e)),i}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 ef(e).build(),this}addSacTransferOperation(e,t,n,r){if(BigInt(n)<=0n)throw new Error("Amount must be a positive integer");if(BigInt(n)>ff)throw new Error("Amount exceeds maximum value for i64");if(r){const{instructions:e,readBytes:t,writeBytes:n,resourceFee:o}=r,i=4294967295;if(e<=0||e>i)throw new Error(`instructions must be greater than 0 and at most ${i}`);if(t<=0||t>i)throw new Error(`readBytes must be greater than 0 and at most ${i}`);if(n<=0||n>i)throw new Error(`writeBytes must be greater than 0 and at most ${i}`);if(o<=0n||o>ff)throw new Error("resourceFee must be greater than 0 and at most i64 max")}const o=ih.isValidContract(e);if(!o&&!ih.isValidEd25519PublicKey(e)&&!ih.isValidMed25519PublicKey(e))throw new Error("Invalid destination address. Must be a valid Stellar address or contract ID.");const i=o?e:Sh(e);if(i===Sh(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 s=t.contractId(this.networkPassphrase),a="transfer",c=this.source.accountId(),u=Sh(c),l=[df(c,{type:"address"}),df(e,{type:"address"}),df(n,{type:"i128"})],d=t.isNative(),h=new tl.SorobanAuthorizationEntry({credentials:tl.SorobanCredentials.sorobanCredentialsSourceAccount(),rootInvocation:new tl.SorobanAuthorizedInvocation({function:tl.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(new tl.InvokeContractArgs({contractAddress:Op.fromString(s).toScAddress(),functionName:a,args:l})),subInvocations:[]})}),p=new tl.LedgerFootprint({readOnly:[tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:Op.fromString(s).toScAddress(),key:tl.ScVal.scvLedgerKeyContractInstance(),durability:tl.ContractDataDurability.persistent()}))],readWrite:[]});if(o){if(p.readWrite().push(tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:Op.fromString(s).toScAddress(),key:tl.ScVal.scvVec([df("Balance",{type:"symbol"}),df(e,{type:"address"})]),durability:tl.ContractDataDurability.persistent()}))),!d){const e=t.getIssuer();if(!e)throw new Error("Asset issuer must be set for non-native assets.");p.readOnly().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(e).xdrPublicKey()})))}}else d?p.readWrite().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(i).xdrPublicKey()}))):t.getIssuer()!==i&&p.readWrite().push(tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(i).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));t.isNative()?p.readWrite().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(u).xdrPublicKey()}))):t.getIssuer()!==u&&p.readWrite().push(tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(u).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));const f={instructions:4e5,readBytes:1e3,writeBytes:1e3,resourceFee:BigInt(5e6)},g=new tl.SorobanTransactionData({resources:new tl.SorobanResources({footprint:p,instructions:r?r.instructions:f.instructions,diskReadBytes:r?r.readBytes:f.readBytes,writeBytes:r?r.writeBytes:f.writeBytes}),ext:new tl.SorobanTransactionDataExt(0),resourceFee:new tl.Int64(r?r.resourceFee:f.resourceFee)}),m=Vp.invokeContractFunction({contract:s,function:a,args:l,auth:[h]});return this.setSorobanData(g),this.addOperation(m)}build(){const e=new Hh(this.source.sequenceNumber()).plus(1),t=new Hh(this.baseFee).times(this.operations.length).toNumber();if(t>gf)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:tl.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).");wf(this.timebounds.minTime)&&(this.timebounds.minTime=Math.floor(this.timebounds.minTime.getTime()/1e3)),wf(this.timebounds.maxTime)&&(this.timebounds.maxTime=Math.floor(this.timebounds.maxTime.getTime()/1e3));const r=tl.Uint64.fromString(this.timebounds.minTime.toString()),o=tl.Uint64.fromString(this.timebounds.maxTime.toString()),i=new tl.TimeBounds({minTime:r,maxTime:o});if(this.hasV2Preconditions()){let e=null;null!==this.ledgerbounds&&(e=new tl.LedgerBounds({minLedger:this.ledgerbounds.minLedger??0,maxLedger:this.ledgerbounds.maxLedger??0}));const t=this.minAccountSequence?tl.Int64.fromString(this.minAccountSequence):null,r=tl.Uint64.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),o=this.minAccountSequenceLedgerGap||0,s=null!==this.extraSigners?this.extraSigners.map(e=>tf.decodeAddress(e)):[];n.cond=tl.Preconditions.precondV2(new tl.PreconditionsV2({timeBounds:i,ledgerBounds:e,minSeqNum:t,minSeqAge:r,minSeqLedgerGap:o,extraSigners:s}))}else n.cond=tl.Preconditions.precondTime(i);if(n.sourceAccount=bh(this.source.accountId()),this.sorobanData){if(n.ext=new tl.TransactionExt(1,this.sorobanData),n.fee=new Hh(n.fee).plus(this.sorobanData.resourceFee().toString()).toNumber(),n.fee>gf)throw new Error(`Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (4294967295). Got ${n.fee}.`)}else n.ext=new tl.TransactionExt(0);const s=new tl.Transaction(n);s.operations(this.operations);const a=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:s,signatures:[]}));if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to build a transaction");const c=new Zp(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,i=new Hh(mf);let s=new Hh(0);const a=n.toEnvelope();switch(a.switch().value){case tl.EnvelopeType.envelopeTypeTx().value:{const e=a.v1().tx().ext().value();s=new Hh(e?.resourceFee().toString()??0);break}}const c=new Hh(n.fee).minus(s).div(o),u=new Hh(t);if(u.lt(c))throw new Error(`Invalid baseFee, it should be at least ${c.toString()} stroops.`);if(u.lt(i))throw new Error(`Invalid baseFee, it should be at least ${i.toString()} stroops.`);let l,d=n.toEnvelope();if(d.switch()===tl.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 tl.Transaction({sourceAccount:tl.MuxedAccount.keyTypeEd25519(e.sourceAccountEd25519()),fee:e.fee(),seqNum:e.seqNum(),cond:tl.Preconditions.precondTime(t),memo:e.memo(),operations:e.operations(),ext:new tl.TransactionExt(0)});d=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:n,signatures:d.v0().signatures()}))}l="string"==typeof e?bh(e):e.xdrMuxedAccount();const h=new tl.FeeBumpTransaction({feeSource:l,fee:tl.Int64.fromString(u.times(o+1).plus(s).toString()),innerTx:tl.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new tl.FeeBumpTransactionExt(0)}),p=new tl.FeeBumpTransactionEnvelope({tx:h,signatures:[]}),f=tl.TransactionEnvelope.envelopeTypeTxFeeBump(p);return new Kp(f,r)}static fromXDR(e,t){return"string"==typeof e&&(e=tl.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===tl.EnvelopeType.envelopeTypeTxFeeBump()?new Kp(e,t):new Zp(e,t)}}function wf(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function bf(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 vf=(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))(vf||{});class Af{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 Sf(e){const t="function"==typeof e.contractId?e.contractId():null;return{...null!=t&&{contractId:ih.encodeContract(t)},type:e.type().name,topics:e.body().value().topics().map(e=>hf(e)),data:hf(e.body().value().data())}}function Tf(e){return e.map(e=>Sf("inSuccessfulContractCall"in e?e.event():e))}function Ef(e){return e instanceof ArrayBuffer?oo.Buffer.from(new Uint8Array(e)):oo.Buffer.from(e)}async function _f(e,t,n,r,o){if(e.credentials().switch().value===tl.SorobanCredentialsType.sorobanCredentialsSourceAccount().value)return e;const i=tl.SorobanAuthorizationEntry.fromXDR(e.toXDR()),s=i.credentials(),a=If(s);if(null===a)throw new Error(`unsupported credential type ${s.switch().name}`);a.signatureExpirationLedger(n);const c=Cf(i,n,r),u=$l(c.toXDR());let l,d;if("function"==typeof t){const e=await t(c);null!==e&&"object"==typeof e&&"signature"in e?(l=Ef(e.signature),d=e.publicKey):(l=Ef(e),d=Op.fromScAddress(a.address()).toString())}else l=Ef(t.sign(u)),d=t.publicKey();if(!lh.fromPublicKey(d).verify(u,l))throw new Error("signature doesn't match payload");const h=df({public_key:ih.decodeEd25519PublicKey(d),signature:l},{type:{public_key:["symbol",null],signature:["symbol",null]}}),p=tl.ScVal.scvVec([h]),f=void 0===o?[a]:function(e){switch(e.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return[e.address()];case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return[e.addressV2()];case tl.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[]}}(s).filter(e=>Op.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(p)),i}function kf(e){const{signer:t,validUntilLedgerSeq:n,invocation:r,networkPassphrase:o,publicKey:i="",authV2:s=!1}=e,a=lh.random().rawPublicKey(),c=new tl.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=i||(t instanceof lh?t.publicKey():null);if(!u)throw new Error("authorizeInvocation requires publicKey parameter");const l=new tl.SorobanAddressCredentials({address:new Op(u).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:tl.ScVal.scvVec([])});return _f(new tl.SorobanAuthorizationEntry({rootInvocation:r,credentials:s?tl.SorobanCredentials.sorobanCredentialsAddressV2(l):tl.SorobanCredentials.sorobanCredentialsAddress(l)}),t,n,o)}function Cf(e,t,n){const r=e.credentials(),o=If(r);if(null===o)throw new Error(`cannot build a signature payload for credential type ${r.switch().name}`);const i=$l(oo.Buffer.from(n));switch(r.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return tl.HashIdPreimage.envelopeTypeSorobanAuthorization(new tl.HashIdPreimageSorobanAuthorization({networkId:i,nonce:o.nonce(),invocation:e.rootInvocation(),signatureExpirationLedger:t}));case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:case tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return tl.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(new tl.HashIdPreimageSorobanAuthorizationWithAddress({networkId:i,nonce:o.nonce(),invocation:e.rootInvocation(),address:o.address(),signatureExpirationLedger:t}));default:throw new Error(`unsupported credential type ${r.switch().name}`)}}function Rf(e){const{entry:t,validUntilLedgerSeq:n,delegates:r,signature:o}=e,i=t.credentials(),s=If(i);if(null===s||i.switch().value===tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value)throw new Error(`buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${i.switch().name}`);return new tl.SorobanAuthorizationEntry({rootInvocation:t.rootInvocation(),credentials:tl.SorobanCredentials.sorobanCredentialsAddressWithDelegates(new tl.SorobanAddressCredentialsWithDelegates({addressCredentials:new tl.SorobanAddressCredentials({address:s.address(),nonce:s.nonce(),signatureExpirationLedger:n,signature:o??tl.ScVal.scvVoid()}),delegates:xf(r)}))})}function xf(e){const t=e.map(e=>new tl.SorobanDelegateSignature({address:new Op(e.address).toScAddress(),signature:e.signature??tl.ScVal.scvVoid(),nestedDelegates:xf(e.nestedDelegates??[])}));t.sort((e,t)=>oo.Buffer.compare(e.address().toXDR(),t.address().toXDR()));for(let e=1;e<t.length;e++)if(0===oo.Buffer.compare(t[e-1].address().toXDR(),t[e].address().toXDR()))throw new Error(`duplicate delegate address ${Op.fromScAddress(t[e].address()).toString()}`);return t}function If(e){switch(e.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return e.address();case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return e.addressV2();case tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return e.addressWithDelegates().addressCredentials();default:return null}}function Bf(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:Op.fromScAddress(e.contractAddress()).toString(),function:e.functionName().toString(),args:e.args().map(e=>hf(e))};break}case 1:case 2:{const e=r,o=2===t.switch().value;n.type="create";const i={},[s,a]=[e.executable(),e.contractIdPreimage()];if(!!s.switch().value!=!!a.switch().value)throw new Error(`creation function appears invalid: ${JSON.stringify(r)} (should be wasm+address or token+asset)`);switch(s.switch().value){case 0:{const e=a.fromAddress();i.type="wasm",i.wasm={salt:oo.Buffer.from(e.salt()).toString("hex"),hash:s.wasmHash().toString("hex"),address:Op.fromScAddress(e.address()).toString(),...o&&{constructorArgs:r.constructorArgs().map(e=>hf(e))}};break}case 1:i.type="sac",i.asset=ph.fromOperation(a.fromAsset()).toString();break;default:throw new Error(`unknown creation type: ${JSON.stringify(s)}`)}n.args=i;break}default:throw new Error(`unknown invocation type (${t.switch().value}): ${JSON.stringify(t)}`)}return n.invocations=e.subInvocations().map(e=>Bf(e)),n}function Of(e,t){Pf(e,1,t)}function Pf(e,t,n,r){!1!==n(e,t,r)&&e.subInvocations().forEach(r=>Pf(r,t+1,n,e))}var Lf=Object.freeze({__proto__:null,Account:Xp,Address:Op,Asset:ph,AssetType:dh,AuthClawbackEnabledFlag:8,AuthImmutableFlag:4,AuthRequiredFlag:1,AuthRevocableFlag:2,BASE_FEE:mf,Claimant:yh,Contract:nf,FeeBumpTransaction:Kp,Hyper:el.Hyper,Int128:sf,Int256:af,Keypair:lh,LiquidityPoolAsset:mh,LiquidityPoolFeeV18:30,LiquidityPoolId:wh,Memo:Wp,MemoHash:Gp,MemoID:zp,MemoNone:Hp,MemoReturn:jp,MemoText:$p,MuxedAccount:Qp,Networks:vf,Operation:Vp,ScInt:uf,SignerKey:tf,Soroban:Af,SorobanDataBuilder:ef,StrKey:ih,TimeoutInfinite:0,Transaction:Zp,TransactionBase:gh,TransactionBuilder:yf,Uint128:rf,Uint256:of,UnsignedHyper:el.UnsignedHyper,XdrLargeInt:cf,authorizeEntry:_f,authorizeInvocation:kf,buildAuthorizationEntryPreimage:Cf,buildInvocationTree:Bf,buildWithDelegatesEntry:Rf,cereal:nl,decodeAddressToMuxedAccount:bh,encodeMuxedAccount:Ah,encodeMuxedAccountToAddress:vh,extractBaseAddress:Sh,getLiquidityPoolId:fh,hash:$l,humanizeEvents:Tf,nativeToScVal:df,scValToBigInt:lf,scValToNative:hf,scvSortedMap:pf,sign:Kd,verify:Xd,walkInvocationTree:Of,xdr:tl});function Uf(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 Nf=102400;class Ff{serverURL;domain;timeout;static async resolve(e,t={}){if(e.indexOf("*")<0)return ih.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 Ff.createForDomain(r,t)).resolveAddress(e)}static async createForDomain(e,t={}){Uf(e);const n=await Xu.resolve(e,t);return n.FEDERATION_SERVER?new Ff(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,Uf(t);const r=void 0===n.allowHttp?Ru.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?Ru.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 bu.get(e.toString(),{maxContentLength:Nf,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 Eu(`Server query failed. Server responded: ${e.status} ${e.statusText}`,e.data))})}}var Df=Object.freeze({__proto__:null,FEDERATION_RESPONSE_MAX_SIZE:Nf,Server:Ff});class Mf extends Error{}function Vf(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=lh.fromPublicKey(e)}catch(e){throw new Mf(`Signer is not a valid address: ${e.message}`)}for(let i=0;i<r.length;i++){const s=r[i];if(s.hint().equals(t.signatureHint())&&t.verify(n,s.signature())){o.add(e),r.splice(i,1);break}}}return Array.from(o)}function qf(e,t){return 0!==Vf(e,[t]).length}const Hf=Object.prototype.toString;function zf(e){return function(e,t,n){return!!e&&(e.constructor===t||Hf.call(e)===n)}(e,Uint8Array,"[object Uint8Array]")}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder;function $f(e,{urlSafe:t=!1}={}){!function(e){if(!zf(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 Gf(e,t,n,r,o){if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");let i;try{i=new Zp(e,n)}catch{try{i=new Kp(e,n)}catch{throw new Mf("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new Mf("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(i.sequence,10))throw new Mf("The transaction sequence number should be zero");if(i.source!==t)throw new Mf("The transaction source account is not equal to the server's account");if(i.operations.length<1)throw new Mf("The transaction should contain at least one operation");const[s,...a]=i.operations;if(!s.source)throw new Mf("The transaction's operation should contain a source account");const c=s.source;let u,l=null;if(i.memo.type!==Hp){if(c.startsWith("M"))throw new Mf("The transaction has a memo but the client account ID is a muxed account");if(i.memo.type!==zp)throw new Mf("The transaction's memo must be of type `id`");l=i.memo.value}if("manageData"!==s.type)throw new Mf("The transaction's operation type should be 'manageData'");if(i.timeBounds&&0===Number.parseInt(i.timeBounds?.maxTime,10))throw new Mf("The transaction requires non-infinite timebounds");if(!xu.validateTimebounds(i,300))throw new Mf("The transaction has expired");if(void 0===s.value)throw new Mf("The transaction's operation values should not be null");if(!s.value)throw new Mf("The transaction's operation value should not be null");if(48!==oo.Buffer.from(s.value.toString(),"base64").length)throw new Mf("The transaction's operation value should be a 64 bytes base64 random string");if(!r)throw new Mf("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof r)`${r} auth`===s.name&&(u=r);else{if(!Array.isArray(r))throw new Mf(`Invalid homeDomains: homeDomains type is ${typeof r} but should be a string or an array`);u=r.find(e=>`${e} auth`===s.name)}if(!u)throw new Mf("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 Mf("The transaction has operations that are not of type 'manageData'");if(e.source!==t&&"client_domain"!==e.name)throw new Mf("The transaction has operations that are unrecognized");if("web_auth_domain"===e.name){if(void 0===e.value)throw new Mf("'web_auth_domain' operation value should not be null");if(e.value.compare(oo.Buffer.from(o)))throw new Mf(`'web_auth_domain' operation value does not match ${o}`)}}if(!qf(i,t))throw new Mf(`Transaction not signed by server: '${t}'`);return{tx:i,clientAccountID:c,matchedHomeDomain:u,memo:l}}function jf(e,t,n,r,o,i){const{tx:s}=Gf(e,t,n,o,i);let a;try{a=lh.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 Mf("No verifiable client signers provided, at least one G... address must be provided");let u;for(const e of s.operations)if("manageData"===e.type&&"client_domain"===e.name){if(u)throw new Mf("Found more than one client_domain operation");u=e.source}const l=[a.publicKey(),...Array.from(c)];u&&l.push(u);const d=Vf(s,l);let h=!1,p=!1;for(const e of d)e===a.publicKey()&&(h=!0),e===u&&(p=!0);if(!h)throw new Mf(`Transaction not signed by server: '${a.publicKey()}'`);if(u&&!p)throw new Mf("Transaction not signed by the source account of the 'client_domain' ManageData operation");if(1===d.length)throw new Mf("None of the given signers match the transaction signatures");if(d.length!==s.signatures.length)throw new Mf("Transaction has unrecognized signatures");if(d.splice(d.indexOf(a.publicKey()),1),u&&d.splice(d.indexOf(u),1),0===d.length)throw new Mf("None of the given signers match the transaction signatures");return d}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var Wf,Zf,Kf,Xf,Yf,Jf=Object.freeze({__proto__:null,InvalidChallengeError:Mf,buildChallengeTx:function(e,t,n,r=300,o,i,s=null,a=null,c=null){if(t.startsWith("M")&&s)throw Error("memo cannot be used if clientAccountID is a muxed account");const u=new Xp(e.publicKey(),"-1"),l=Math.floor(Date.now()/1e3),d=$f(crypto.getRandomValues(new Uint8Array(48))),h=new yf(u,{fee:mf,networkPassphrase:o,timebounds:{minTime:l,maxTime:l+r}}).addOperation(Vp.manageData({name:`${n} auth`,value:d,source:t})).addOperation(Vp.manageData({name:"web_auth_domain",value:i,source:u.accountId()}));if(a){if(!c)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(Vp.manageData({name:"client_domain",value:a,source:c}))}s&&h.addMemo(Wp.id(s));const p=h.build();return p.sign(e),p.toEnvelope().toXDR("base64").toString()},gatherTxSigners:Vf,readChallengeTx:Gf,verifyChallengeTxSigners:jf,verifyChallengeTxThreshold:function(e,t,n,r,o,i,s){const a=jf(e,t,n,o.map(e=>e.key),i,s);let c=0;for(const e of a){c+=o.find(t=>t.key===e)?.weight||0}if(c<r)throw new Mf(`signers with weight ${c} do not meet threshold ${r}"`);return a},verifyTxSignedBy:qf}),Qf=Object.freeze({__proto__:null});((Zf=Wf||(Wf={})).LiquidityPoolType||(Zf.LiquidityPoolType={})).constantProduct="constant_product",(Kf=Zf.OperationResponseType||(Zf.OperationResponseType={})).createAccount="create_account",Kf.payment="payment",Kf.pathPayment="path_payment_strict_receive",Kf.createPassiveOffer="create_passive_sell_offer",Kf.manageOffer="manage_sell_offer",Kf.setOptions="set_options",Kf.changeTrust="change_trust",Kf.allowTrust="allow_trust",Kf.accountMerge="account_merge",Kf.inflation="inflation",Kf.manageData="manage_data",Kf.bumpSequence="bump_sequence",Kf.manageBuyOffer="manage_buy_offer",Kf.pathPaymentStrictSend="path_payment_strict_send",Kf.createClaimableBalance="create_claimable_balance",Kf.claimClaimableBalance="claim_claimable_balance",Kf.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",Kf.endSponsoringFutureReserves="end_sponsoring_future_reserves",Kf.revokeSponsorship="revoke_sponsorship",Kf.clawback="clawback",Kf.clawbackClaimableBalance="clawback_claimable_balance",Kf.setTrustLineFlags="set_trust_line_flags",Kf.liquidityPoolDeposit="liquidity_pool_deposit",Kf.liquidityPoolWithdraw="liquidity_pool_withdraw",Kf.invokeHostFunction="invoke_host_function",Kf.bumpFootprintExpiration="bump_footprint_expiration",Kf.restoreFootprint="restore_footprint",(Xf=Zf.OperationResponseTypeI||(Zf.OperationResponseTypeI={}))[Xf.createAccount=0]="createAccount",Xf[Xf.payment=1]="payment",Xf[Xf.pathPayment=2]="pathPayment",Xf[Xf.createPassiveOffer=3]="createPassiveOffer",Xf[Xf.manageOffer=4]="manageOffer",Xf[Xf.setOptions=5]="setOptions",Xf[Xf.changeTrust=6]="changeTrust",Xf[Xf.allowTrust=7]="allowTrust",Xf[Xf.accountMerge=8]="accountMerge",Xf[Xf.inflation=9]="inflation",Xf[Xf.manageData=10]="manageData",Xf[Xf.bumpSequence=11]="bumpSequence",Xf[Xf.manageBuyOffer=12]="manageBuyOffer",Xf[Xf.pathPaymentStrictSend=13]="pathPaymentStrictSend",Xf[Xf.createClaimableBalance=14]="createClaimableBalance",Xf[Xf.claimClaimableBalance=15]="claimClaimableBalance",Xf[Xf.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",Xf[Xf.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",Xf[Xf.revokeSponsorship=18]="revokeSponsorship",Xf[Xf.clawback=19]="clawback",Xf[Xf.clawbackClaimableBalance=20]="clawbackClaimableBalance",Xf[Xf.setTrustLineFlags=21]="setTrustLineFlags",Xf[Xf.liquidityPoolDeposit=22]="liquidityPoolDeposit",Xf[Xf.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",Xf[Xf.invokeHostFunction=24]="invokeHostFunction",Xf[Xf.bumpFootprintExpiration=25]="bumpFootprintExpiration",Xf[Xf.restoreFootprint=26]="restoreFootprint",(Yf=Zf.TransactionFailedResultCodes||(Zf.TransactionFailedResultCodes={})).TX_FAILED="tx_failed",Yf.TX_BAD_SEQ="tx_bad_seq",Yf.TX_BAD_AUTH="tx_bad_auth",Yf.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",Yf.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",Yf.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",Yf.TX_NOT_SUPPORTED="tx_not_supported",Yf.TX_SUCCESS="tx_success",Yf.TX_TOO_EARLY="tx_too_early",Yf.TX_TOO_LATE="tx_too_late",Yf.TX_MISSING_OPERATION="tx_missing_operation",Yf.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",Yf.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",Yf.TX_INSUFFICIENT_FEE="tx_insufficient_fee",Yf.TX_INTERNAL_ERROR="tx_internal_error";var eg,tg,ng,rg=(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))(rg||{});(tg=eg||(eg={})).EffectType=rg,(ng=tg.TradeType||(tg.TradeType={})).all="all",ng.liquidityPools="liquidity_pool",ng.orderbook="orderbook",Wf.OperationResponseType,Wf.OperationResponseTypeI;class og{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 Xp(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 ig 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 sg=32;function ag(e){}function cg(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=ag,onError:n=ag,onRetry:r=ag,onComment:o}=e,i=[];let s,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:s,event:a,data:u}),s=void 0,u="",l=0,a=void 0,n=r+1,r=e.indexOf("\n",n);continue}const o=e.charCodeAt(n);if(ug(e,n,o)){const o=e.charCodeAt(n+5)===sg?n+6:n+5,i=e.slice(o,r);if(0===l&&10===e.charCodeAt(r+1)){t({id:s,event:a,data:i}),s=void 0,u="",a=void 0,n=r+2,r=e.indexOf("\n",n);continue}u=0===l?i:`${u}\n${i}`,l++}else lg(e,n,o)?a=e.slice(e.charCodeAt(n+6)===sg?n+7:n+6,r)||void 0:h(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;h(e,n,o),n=o+1,13===e.charCodeAt(n-1)&&10===e.charCodeAt(n)&&n++}return e.slice(n)}function h(e,n,r){if(n===r)return l>0&&t({id:s,event:a,data:u}),s=void 0,u="",l=0,void(a=void 0);const i=e.charCodeAt(n);if(ug(e,n,i)){const t=e.charCodeAt(n+5)===sg?n+6:n+5,o=e.slice(t,r);return u=0===l?o:`${u}\n${o}`,void l++}if(lg(e,n,i))return void(a=e.slice(e.charCodeAt(n+6)===sg?n+7:n+6,r)||void 0);if(105===i&&100===e.charCodeAt(n+1)&&58===e.charCodeAt(n+2)){const t=e.slice(e.charCodeAt(n+3)===sg?n+4:n+3,r);return void(s=t.includes("\0")?void 0:t)}if(58===i){if(o){const t=e.slice(n,r);o(t.slice(e.charCodeAt(n+1)===sg?2:1))}return}const c=e.slice(n,r),d=c.indexOf(":");if(-1===d)return void p(c,"",c);const h=c.slice(0,d),f=c.charCodeAt(d+1)===sg?2:1;p(h,c.slice(d+f),c)}function p(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":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new ig(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new ig(`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===i.length){const t=d(e);return void(""!==t&&i.push(t))}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return void i.push(e);i.push(e);const t=i.join("");i.length=0;const n=d(t);""!==n&&i.push(n)},reset:function(e={}){if(e.consume&&i.length>0){const e=i.join("");h(e,0,e.length)}c=!0,s=void 0,u="",l=0,a=void 0,i.length=0}}}function ug(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 lg(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 dg 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(pg(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(pg(this),t)}}function hg(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(hg).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${hg(e.cause)}`:e.message:`${e}`}function pg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var fg,gg,mg,yg,wg,bg,vg,Ag,Sg,Tg,Eg,_g,kg,Cg,Rg,xg,Ig,Bg,Og,Pg,Lg,Ug,Ng,Fg=e=>{throw TypeError(e)},Dg=(e,t,n)=>t.has(e)||Fg("Cannot "+n),Mg=(e,t,n)=>(Dg(e,t,"read from private field"),n?n.call(e):t.get(e)),Vg=(e,t,n)=>t.has(e)?Fg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),qg=(e,t,n,r)=>(Dg(e,t,"write to private field"),t.set(e,n),n),Hg=(e,t,n)=>(Dg(e,t,"access private method"),n);class zg extends EventTarget{constructor(e,t){var n,r;super(),Vg(this,Cg),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Vg(this,fg),Vg(this,gg),Vg(this,mg),Vg(this,yg),Vg(this,wg),Vg(this,bg),Vg(this,vg),Vg(this,Ag,null),Vg(this,Sg),Vg(this,Tg),Vg(this,Eg,null),Vg(this,_g,null),Vg(this,kg,null),Vg(this,xg,async e=>{var t;Mg(this,Tg).reset();const{body:n,redirected:r,status:o,headers:i}=e;if(204===o)return Hg(this,Cg,Lg).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(qg(this,mg,r?new URL(e.url):void 0),200!==o)return void Hg(this,Cg,Lg).call(this,`Non-200 status code (${o})`,o);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void Hg(this,Cg,Lg).call(this,'Invalid content type, expected "text/event-stream"',o);if(Mg(this,fg)===this.CLOSED)return;qg(this,fg,this.OPEN);const s=new Event("open");if(null==(t=Mg(this,kg))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof n||!n||!("getReader"in n))return Hg(this,Cg,Lg).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&&Mg(this,Tg).feed(a.decode(t,{stream:!e})),e&&(u=!1,Mg(this,Tg).reset(),Hg(this,Cg,Ug).call(this))}while(u)}),Vg(this,Ig,e=>{qg(this,Sg,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&Hg(this,Cg,Ug).call(this,hg(e))}),Vg(this,Og,e=>{"string"==typeof e.id&&qg(this,Ag,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Mg(this,mg)?Mg(this,mg).origin:Mg(this,gg).origin,lastEventId:e.id||""});Mg(this,_g)&&(!e.event||"message"===e.event)&&Mg(this,_g).call(this,t),this.dispatchEvent(t)}),Vg(this,Pg,e=>{qg(this,bg,e)}),Vg(this,Ng,()=>{qg(this,vg,void 0),Mg(this,fg)===this.CONNECTING&&Hg(this,Cg,Rg).call(this)});try{if(e instanceof URL)qg(this,gg,e);else{if("string"!=typeof e)throw new Error("Invalid URL");qg(this,gg,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")}qg(this,Tg,cg({onEvent:Mg(this,Og),onRetry:Mg(this,Pg)})),qg(this,fg,this.CONNECTING),qg(this,bg,3e3),qg(this,wg,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),qg(this,yg,null!=(r=null==t?void 0:t.withCredentials)&&r),Hg(this,Cg,Rg).call(this)}get readyState(){return Mg(this,fg)}get url(){return Mg(this,gg).href}get withCredentials(){return Mg(this,yg)}get onerror(){return Mg(this,Eg)}set onerror(e){qg(this,Eg,e)}get onmessage(){return Mg(this,_g)}set onmessage(e){qg(this,_g,e)}get onopen(){return Mg(this,kg)}set onopen(e){qg(this,kg,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(){Mg(this,vg)&&clearTimeout(Mg(this,vg)),Mg(this,fg)!==this.CLOSED&&(Mg(this,Sg)&&Mg(this,Sg).abort(),qg(this,fg,this.CLOSED),qg(this,Sg,void 0))}}fg=new WeakMap,gg=new WeakMap,mg=new WeakMap,yg=new WeakMap,wg=new WeakMap,bg=new WeakMap,vg=new WeakMap,Ag=new WeakMap,Sg=new WeakMap,Tg=new WeakMap,Eg=new WeakMap,_g=new WeakMap,kg=new WeakMap,Cg=new WeakSet,Rg=function(){qg(this,fg,this.CONNECTING),qg(this,Sg,new AbortController),Mg(this,wg)(Mg(this,gg),Hg(this,Cg,Bg).call(this)).then(Mg(this,xg)).catch(Mg(this,Ig))},xg=new WeakMap,Ig=new WeakMap,Bg=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Mg(this,Ag)?{"Last-Event-ID":Mg(this,Ag)}:void 0},cache:"no-store",signal:null==(e=Mg(this,Sg))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Og=new WeakMap,Pg=new WeakMap,Lg=function(e,t){var n;Mg(this,fg)!==this.CLOSED&&qg(this,fg,this.CLOSED);const r=new dg("error",{code:t,message:e});null==(n=Mg(this,Eg))||n.call(this,r),this.dispatchEvent(r)},Ug=function(e,t){var n;if(Mg(this,fg)===this.CLOSED)return;qg(this,fg,this.CONNECTING);const r=new dg("error",{code:t,message:e});null==(n=Mg(this,Eg))||n.call(this,r),this.dispatchEvent(r),qg(this,vg,setTimeout(Mg(this,Ng),Mg(this,bg)))},Ng=new WeakMap,zg.CONNECTING=0,zg.OPEN=1,zg.CLOSED=2,Object.defineProperty(zg,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});const $g="16.0.0-rc.2",Gg={};function jg(e){return Math.floor(e/1e3)}function Wg(e){const t=Gg[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;const{serverTime:n,localTimeRecorded:r}=t,o=jg((new Date).getTime());return o-r>300?null:o-r+n}function Zg(e){return Array.isArray(e)?e.join(","):e.toString()}const Kg=["transaction"];class Xg{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",$g);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 i=()=>{o=setTimeout(()=>{r?.close(),r=s()},e.reconnectTimeout||15e3)},s=()=>{try{r=new zg(t.toString())}catch(t){e.onerror&&e.onerror(t)}if(i(),!r)return r;let n=!1;const a=()=>{n||(clearTimeout(o),r.close(),s(),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),i(),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 s(),()=>{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 Tu("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(Zg(r))}),i=new URL(o,n);return r.forEach(e=>{const n=t[e];void 0!==n&&i.searchParams.set(e,Zg(n))}),i.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&&Kg.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 Su(e.response.statusText??"Not Found",e.response.data)):Promise.reject(new Au(e.response.statusText??"Unknown",e.response.data)):Promise.reject(new Error(e.message))}}class Yg extends Xg{constructor(e,t){super(e,t),this.setPath("accounts")}accountId(e){const t=new Xg(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 Jg extends Xg{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 Qg extends Xg{constructor(e,t){super(e,t),this.setPath("claimable_balances")}claimableBalance(e){const t=new Xg(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 em extends Xg{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 tm extends Xg{constructor(e,t,n){super(e,t),this.setPath("friendbot"),this.url.searchParams.set("addr",n)}}class nm extends Xg{constructor(e,t){super(e,t),this.setPath("ledgers")}ledger(e){return this.filter.push(["ledgers",e.toString()]),this}}class rm extends Xg{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 Xg(new URL(this.url),this.httpClient);return t.filter.push([e.toLowerCase()]),t}}class om extends Xg{constructor(e,t){super(e,t,"offers"),this.setPath("offers")}offer(e){const t=new Xg(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 im extends Xg{constructor(e,t){super(e,t,"operations"),this.setPath("operations")}operation(e){const t=new Xg(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 sm extends Xg{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 i=r.getIssuer();r.isNative()||void 0===i?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",i))}}class am extends Xg{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 cm extends Xg{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 i=r.getIssuer();r.isNative()||void 0===i?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",i))}}class um extends Xg{constructor(e,t,n,r,o){super(e,t),this.setPath("paths/strict-send");const i=n.getIssuer();if(n.isNative()?this.url.searchParams.set("source_asset_type","native"):void 0!==i&&(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",i)),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 lm=[6e4,3e5,9e5,36e5,864e5,6048e5];class dm extends Xg{constructor(e,t,n,r,o,i,s,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 i)throw new Tu("Invalid time bounds",[o,i]);if(this.url.searchParams.set("start_time",o.toString()),this.url.searchParams.set("end_time",i.toString()),!this.isValidResolution(s))throw new Tu("Invalid resolution",s);if(this.url.searchParams.set("resolution",s.toString()),!this.isValidOffset(a,s))throw new Tu("Invalid offset",a);this.url.searchParams.set("offset",a.toString())}isValidResolution(e){return lm.some(t=>t===e)}isValidOffset(e,t){const n=36e5;return!(e>t||e>=24*n||e%n!==0)}}class hm extends Xg{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 pm extends Xg{constructor(e,t){super(e,t,"transactions"),this.setPath("transactions")}transaction(e){const t=new Xg(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 fm(e){return new Hh(e).div(1e7).toString()}var gm,mm=Object.freeze({__proto__:null,AccountResponse:og,get HorizonApi(){return Wf},SERVER_TIME_MAP:Gg,Server:class{serverURL;httpClient;constructor(e,t={}){this.serverURL=new URL(e);const n=void 0===t.allowHttp?Ru.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=vu({headers:{...e,"X-Client-Name":"js-stellar-sdk","X-Client-Version":$g}});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 i=0;if(e.headers instanceof Headers){const t=e.headers.get("date");t&&(i=jg(Date.parse(t)))}else if("object"==typeof e.headers&&"date"in e.headers){const t=e.headers;"string"==typeof t.date&&(i=jg(Date.parse(t.date)))}const s=jg((new Date).getTime());return Number.isNaN(i)||(Gg[o]={serverTime:i,localTimeRecorded:s}),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=Wg(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 Xg(this.serverURL,this.httpClient);return e.filter.push(["fee_stats"]),e.call()}async root(){return new Xg(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=tl.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 Hh(0),o=new Hh(0);const i=e.value().value().success(),s=i.offersClaimed().map(e=>{const t=e.value();let r="";switch(e.switch()){case tl.ClaimAtomType.claimAtomTypeV0():r=ih.encodeEd25519PublicKey(t.sellerEd25519());break;case tl.ClaimAtomType.claimAtomTypeOrderBook():r=ih.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error(`Invalid offer result type: ${e.switch()}`)}const i=new Hh(t.amountBought().toString()),s=new Hh(t.amountSold().toString());n=n.plus(s),o=o.plus(i);const a=ph.fromOperation(t.assetSold()),c=ph.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:fm(s),assetBought:l,amountBought:fm(i)}}),a=i.offer().switch().name;let c;if("function"==typeof i.offer().value&&i.offer().value()){const e=i.offer().value();c={offerId:e.offerId().toString(),selling:{},buying:{},amount:fm(e.amount().toString()),price:{n:e.price().n(),d:e.price().d()}};const t=ph.fromOperation(e.selling());c.selling={type:t.getAssetType(),assetCode:t.getCode(),issuer:t.getIssuer()};const n=ph.fromOperation(e.buying());c.buying={type:n.getAssetType(),assetCode:n.getCode(),issuer:n.getIssuer()}}return{offersClaimed:s,effect:a,operationIndex:t,currentOffer:c,amountBought:fm(n),amountSold:fm(o),isFullyOpen:!s.length&&"manageOfferDeleted"!==a,wasPartiallyFilled:!!s.length&&"manageOfferDeleted"!==a,wasImmediatelyFilled:!!s.length&&"manageOfferDeleted"===a,wasImmediatelyDeleted:!s.length&&"manageOfferDeleted"===a}}).filter(e=>!!e)),{...e.data,offerResults:r?n:void 0}}).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new Eu(`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 Eu(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}accounts(){return new Yg(this.serverURL,this.httpClient)}claimableBalances(){return new Qg(this.serverURL,this.httpClient)}ledgers(){return new nm(this.serverURL,this.httpClient)}transactions(){return new pm(this.serverURL,this.httpClient)}offers(){return new om(this.serverURL,this.httpClient)}orderbook(e,t){return new sm(this.serverURL,this.httpClient,e,t)}trades(){return new hm(this.serverURL,this.httpClient)}operations(){return new im(this.serverURL,this.httpClient)}liquidityPools(){return new rm(this.serverURL,this.httpClient)}strictReceivePaths(e,t,n){return new cm(this.serverURL,this.httpClient,e,t,n)}strictSendPaths(e,t,n){return new um(this.serverURL,this.httpClient,e,t,n)}payments(){return new am(this.serverURL,this.httpClient)}effects(){return new em(this.serverURL,this.httpClient)}friendbot(e){return new tm(this.serverURL,this.httpClient,e)}assets(){return new Jg(this.serverURL,this.httpClient)}async loadAccount(e){const t=await this.accounts().accountId(e).call();return new og(t)}tradeAggregation(e,t,n,r,o,i){return new dm(this.serverURL,this.httpClient,e,t,n,r,o,i)}async checkMemoRequired(e){if(e instanceof Kp&&(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 _u("account requires memo",o,n)}catch(e){if(e instanceof _u)throw e;if(!(e instanceof Su))throw e;continue}}}},get ServerApi(){return eg},getCurrentServerTime:Wg});(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}})(gm||(gm={}));async function ym(e,t,n,r=null){const o=await e.post(t,{jsonrpc:"2.0",id:1,method:n,params:r});if(i=o.data,s="error",Object.prototype.hasOwnProperty.call(i,s))throw o.data.error;return o.data?.result;var i,s}function wm(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=>tl.DiagnosticEvent.fromXDR(e,"base64"))},errorResult:tl.TransactionResult.fromXDR(t,"base64")}:{...e}}function bm(e){const t=tl.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),n={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:tl.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:tl.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:t,events:{contractEventsXdr:(e.events?.contractEventsXdr??[]).map(e=>e.map(e=>tl.ContractEvent.fromXDR(e,"base64"))),transactionEventsXdr:(e.events?.transactionEventsXdr??[]).map(e=>tl.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=>tl.DiagnosticEvent.fromXDR(e,"base64"))),n}function vm(e){return{status:e.status,txHash:e.txHash,...bm(e)}}function Am(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 nf(e.contractId)},topic:(e.topic??[]).map(e=>tl.ScVal.fromXDR(e,"base64")),value:tl.ScVal.fromXDR(e.value,"base64")}})}}function Sm(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:tl.LedgerKey.fromXDR(e.key,"base64"),val:tl.LedgerEntryData.fromXDR(e.xdr,"base64"),...void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq}}})}}function Tm(e){if(!gm.isSimulationRaw(e))return e;const t={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:e.events?.map(e=>tl.DiagnosticEvent.fromXDR(e,"base64"))??[]};return"string"==typeof e.error?{...t,error:e.error}:function(e,t){const n={...t,transactionData:new ef(e.transactionData),minResourceFee:e.minResourceFee,...(e.results?.length??0)>0&&{result:e.results.map(e=>({auth:(e.auth??[]).map(e=>tl.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:e.xdr?tl.ScVal.fromXDR(e.xdr,"base64"):tl.ScVal.scvVoid()}))[0]},...(e.stateChanges?.length??0)>0&&{stateChanges:e.stateChanges?.map(e=>({type:e.type,key:tl.LedgerKey.fromXDR(e.key,"base64"),before:e.before?tl.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?tl.LedgerEntry.fromXDR(e.after,"base64"):null}))}};return e.restorePreamble&&""!==e.restorePreamble.transactionData?{...n,restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new ef(e.restorePreamble.transactionData)}}:n}(e,t)}function Em(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=tl.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64"),n=tl.LedgerHeaderHistoryEntry.fromXDR(e.headerXdr,"base64");return{hash:e.hash,sequence:e.sequence,ledgerCloseTime:e.ledgerCloseTime,metadataXdr:t,headerXdr:n}}function _m(e){const t=tl.LedgerHeader.fromXDR(e.headerXdr,"base64"),n=tl.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 km(e,t){if("innerTransaction"in e)return km(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=Tm(t);if(!gm.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 i=yf.cloneFrom(e,{fee:r.toString(),sorobanData:n.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){i.clearOperations();const t=e.operations[0],r=t.auth??[];i.addOperation(Vp.invokeHostFunction({source:t.source,func:t.func,auth:r.length>0?r:n.result.auth}))}return i}var Cm=(e=>(e.Temporary="temporary",e.Persistent="persistent",e))(Cm||{});const Rm=e=>1e3;class xm{serverURL;httpClient;constructor(e,t={}){var n;if(this.serverURL=new URL(e),this.httpClient=(n=t.headers,vu({headers:{...n,"X-Client-Name":"js-stellar-sdk","X-Client-Version":"16.0.0-rc.2"}})),"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 Xp(e,t.seqNum().toString())}async getAccountEntry(e){const t=tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.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=tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.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(ih.isValidClaimableBalance(e)){let n=ih.decodeClaimableBalance(e),r=oo.Buffer.concat([oo.Buffer.from("\0\0\0"),n.subarray(0,1)]);t=tl.ClaimableBalanceId.fromXDR(oo.Buffer.concat([r,n.subarray(1)]))}else if(e.match(/[a-f0-9]{72}/i))t=tl.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=tl.ClaimableBalanceId.fromXDR(e.padStart(72,"0"),"hex")}const n=tl.LedgerKey.claimableBalance(new tl.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 Op)r=e.toString();else{if(!(e instanceof nf))throw new TypeError(`invalid address: ${e}`);r=e.toString()}if(ih.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(ih.isValidContract(r))return this.getSACBalance(r,t,n);throw new Error(`invalid address: ${e}`)}async getHealth(){return ym(this.httpClient,this.serverURL.toString(),"getHealth")}async getContractData(e,t,n="persistent"){let r,o;if("string"==typeof e)r=new nf(e).address().toScAddress();else if(e instanceof Op)r=e.toScAddress();else{if(!(e instanceof nf))throw new TypeError(`unknown contract type: ${e}`);r=e.address().toScAddress()}switch(n){case"temporary":o=tl.ContractDataDurability.temporary();break;case"persistent":o=tl.ContractDataDurability.persistent();break;default:throw new TypeError(`invalid durability: ${n}`)}const i=tl.LedgerKey.contractData(new tl.LedgerKeyContractData({key:t,contract:r,durability:o}));try{return await this.getLedgerEntry(i)}catch{throw{code:404,message:`Contract data not found for ${Op.fromScAddress(r).toString()} with key ${t.toXDR("base64")} and durability: ${n}`}}}async getContractWasmByContractId(e){const t=new nf(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?oo.Buffer.from(e,t):e,r=tl.LedgerKey.contractCode(new tl.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(Sm)}_getLedgerEntries(...e){return ym(this.httpClient,this.serverURL.toString(),"getLedgerEntries",{keys:e.map(e=>e.toXDR("base64"))})}async getLedgerEntry(e){const t=await this._getLedgerEntries(e).then(Sm);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!==gm.GetTransactionStatus.NOT_FOUND)return r;await xu.sleep((t?.sleepStrategy??Rm)(o))}return r}async getTransaction(e){return this._getTransaction(e).then(t=>{const n={};t.status!==gm.GetTransactionStatus.NOT_FOUND&&Object.assign(n,bm(t));return{status:t.status,txHash:e,latestLedger:t.latestLedger,latestLedgerCloseTime:t.latestLedgerCloseTime,oldestLedger:t.oldestLedger,oldestLedgerCloseTime:t.oldestLedgerCloseTime,...n}})}async _getTransaction(e){return ym(this.httpClient,this.serverURL.toString(),"getTransaction",{hash:e})}async getTransactions(e){return this._getTransactions(e).then(e=>({transactions:(e.transactions||[]).map(vm),latestLedger:e.latestLedger,latestLedgerCloseTimestamp:e.latestLedgerCloseTimestamp,oldestLedger:e.oldestLedger,oldestLedgerCloseTimestamp:e.oldestLedgerCloseTimestamp,cursor:e.cursor}))}async _getTransactions(e){return ym(this.httpClient,this.serverURL.toString(),"getTransactions",e)}async getEvents(e){return this._getEvents(e).then(Am)}async _getEvents(e){return ym(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 ym(this.httpClient,this.serverURL.toString(),"getNetwork")}async getLatestLedger(){return this._getLatestLedger().then(_m)}async _getLatestLedger(){return ym(this.httpClient,this.serverURL.toString(),"getLatestLedger")}async simulateTransaction(e,t,n,r=!1){return this._simulateTransaction(e,t,n,r).then(Tm)}async _simulateTransaction(e,t,n,r=!1){return ym(this.httpClient,this.serverURL.toString(),"simulateTransaction",{transaction:e.toXDR(),authMode:n,...void 0!==t&&{resourceConfig:{instructionLeeway:t.cpuInstructions}},...r&&{authV2:!0}})}async prepareTransaction(e){const t=await this.simulateTransaction(e);if(gm.isSimulationError(t))throw new Error(t.error);return km(e,t).build()}async sendTransaction(e){return this._sendTransaction(e).then(wm)}async _sendTransaction(e){return ym(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=tl.TransactionMeta.fromXDR(r.data.result_meta_xdr,"base64");else{const t=await this.getTransaction(r.data.hash);if(t.status!==gm.GetTransactionStatus.SUCCESS)throw new Error(`Funding account ${e} failed`);o=t.resultMetaXdr}const i=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()===tl.LedgerEntryChangeType.ledgerEntryCreated()&&e.created().data().switch()===tl.LedgerEntryType.account())?.created()?.data()?.account()?.seqNum()?.toString();if(n)return n;throw new Error("No account created in transaction")}(o);return new Xp(n,i)}catch(e){if(400===e.response?.status&&e.response.data?.detail?.includes("createAccountAlreadyExist"))return this.getAccount(n);throw e}}async fundAddress(e,t){if(!ih.isValidEd25519PublicKey(e)&&!ih.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!==gm.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 ym(this.httpClient,this.serverURL.toString(),"getFeeStats")}async getVersionInfo(){return ym(this.httpClient,this.serverURL.toString(),"getVersionInfo")}async getSACBalance(e,t,n){const r=e instanceof Op?e.toString():e;if(!ih.isValidContract(r))throw new TypeError(`expected contract ID, got ${r}`);const o=n??await this.getNetwork().then(e=>e.passphrase),i=t.contractId(o),s=df(["Balance",r],{type:["symbol","address"]}),a=tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:new Op(i).toScAddress(),durability:tl.ContractDataDurability.persistent(),key:s})),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!==tl.LedgerEntryType.contractData().value)return{latestLedger:c.latestLedger};const h=hf(d.contractData().val());return{latestLedger:c.latestLedger,balanceEntry:{liveUntilLedgerSeq:l,lastModifiedLedgerSeq:u,amount:h.amount.toString(),authorized:h.authorized,clawback:h.clawback}}}async getLedgers(e){return this._getLedgers(e).then(e=>({ledgers:(e.ledgers||[]).map(Em),latestLedger:e.latestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedger:e.oldestLedger,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor}))}async _getLedgers(e){return ym(this.httpClient,this.serverURL.toString(),"getLedgers",e)}}var Im=Object.freeze({__proto__:null,get Api(){return gm},BasicSleepStrategy:Rm,Durability:Cm,LinearSleepStrategy:e=>1e3*e,Server:xm,assembleTransaction:km,parseRawEvents:Am,parseRawSimulation:Tm});class Bm{constructor(e){this.value=e}value;unwrapErr(){throw new Error("No error")}unwrap(){return this.value}isOk(){return!0}isErr(){return!1}}class Om{constructor(e){this.error=e}error;unwrapErr(){return this.error}unwrap(){throw new Error(this.error.message)}isOk(){return!1}isErr(){return!0}}const Pm=300,Lm="GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";const Um=/Error\(Contract, #(\d+)\)/;function Nm(e){const t=new nl.XdrReader(e),n=[];for(;!t.eof;)n.push(tl.ScSpecEntry.read(t));return n}async function Fm(e,t){return e.publicKey?t.getAccount(e.publicKey):new Xp(Lm,"0")}class Dm{constructor(e){this.assembled=e;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.assembled.options;this.server=t??new xm(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 Dm(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 Dm.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??Pm;if(this.getTransactionResponseAll=await async function(e,t,n,r=1.5,o=!1){const i=[];let s=0;if(i.push(await e()),!t(i[i.length-1]))return i;const a=new Date(Date.now()+1e3*n).valueOf();let c=1e3,u=c;for(;Date.now()<a&&t(i[i.length-1]);)s+=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,i.push(await e(i[i.length-1])),o&&t(i[i.length-1])&&console.info(`${s}. Called ${e}; ${i.length} prev attempts. Most recent: ${JSON.stringify(i[i.length-1],null,2)}`);return i}(async()=>{const n=await this.server.getTransaction(t);return e?.onProgress&&e.onProgress(n),n},e=>e.status===gm.GetTransactionStatus.NOT_FOUND,n),this.getTransactionResponse=this.getTransactionResponseAll[this.getTransactionResponseAll.length-1],this.getTransactionResponse.status===gm.GetTransactionStatus.NOT_FOUND)throw new Dm.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 Dm.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 Dm.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 Mm extends Error{}class Vm extends Error{}class qm extends Error{}class Hm extends Error{}class zm extends Error{}class $m extends Error{}class Gm extends Error{}class jm extends Error{}class Wm extends Error{}class Zm extends Error{}class Km extends Error{}class Xm extends Error{}class Ym extends Error{}class Jm{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 xm(o,{allowHttp:n,headers:r})}options;raw;originalOp;built;simulation;simulationResult;simulationTransactionData;server;signed;static Errors={ExpiredState:Mm,RestorationFailure:Vm,NeedsMoreSignatures:qm,NoSignatureNeeded:Hm,NoUnsignedNonInvokerAuthEntries:zm,NoSigner:$m,NotYetSimulated:Gm,FakeAccount:jm,SimulationFailed:Wm,InternalWalletError:Zm,ExternalServiceError:Km,InvalidClientRequest:Xm,UserRejected:Ym};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 i,s;try{i=o.contractAddress(),s=o.functionName().toString("utf-8")}catch{throw new Error("Could not extract contract address or method name from the transaction envelope.")}if(!i||!s)throw new Error("Could not extract contract address or method name from the transaction envelope.");const a=Op.fromScAddress(i).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 Jm(e);o.built=yf.fromXDR(t,e.networkPassphrase);const i=Jm.validateInvokeContractOp(o.built,e.contractId).functionName().toString("utf-8");if(i!==e.method)throw new Error(`Transaction envelope calls method '${i}', but the provided method is '${e.method}'.`);return o.simulationResult={auth:n.auth.map(e=>tl.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:tl.ScVal.fromXDR(n.retval,"base64")},o.simulationTransactionData=tl.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=tl.TransactionEnvelope.fromXDR(t,"base64"),o=yf.fromXDR(r,e.networkPassphrase),i=Jm.validateInvokeContractOp(o,e.contractId).functionName().toString("utf-8"),s=new Jm({...e,method:i,parseResultXdr:e=>n.funcResToNative(i,e)});return s.built=o,s}handleWalletError(e){if(!e)return;const{message:t,code:n}=e,r=`${t}${e.ext?` (${e.ext.join(", ")})`:""}`;switch(n){case-1:throw new Jm.Errors.InternalWalletError(r);case-2:throw new Jm.Errors.ExternalServiceError(r);case-3:throw new Jm.Errors.InvalidClientRequest(r);case-4:throw new Jm.Errors.UserRejected(r);default:throw new Error(`Unhandled error: ${r}`)}}static build(e){const t=new nf(e.contractId);return Jm.buildWithOp(t.call(e.method,...e.args??[]),e)}static async buildWithOp(e,t){const n=new Jm(t);n.originalOp=e;const r=await Fm(t,n.server);return n.raw=new yf(r,{fee:t.fee??mf,networkPassphrase:t.networkPassphrase}).setTimeout(t.timeoutInSeconds??Pm).addOperation(e),t.simulate&&await n.simulate(),n}static async buildFootprintRestoreTransaction(e,t,n,r){const o=new Jm(e);return o.raw=new yf(n,{fee:r,networkPassphrase:e.networkPassphrase}).setSorobanData(t instanceof ef?t.build():t).addOperation(Vp.restoreFootprint({})).setTimeout(e.timeoutInSeconds??Pm),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,void 0,void 0,this.options.authV2),e&&gm.isSimulationRestore(this.simulation)){const e=await Fm(this.options,this.server),t=await this.restoreFootprint(this.simulation.restorePreamble,e);if(t.status===gm.GetTransactionStatus.SUCCESS){const t=this.originalOp?this.originalOp:new nf(this.options.contractId).call(this.options.method,...this.options.args??[]);return this.raw=new yf(e,{fee:this.options.fee??mf,networkPassphrase:this.options.networkPassphrase}).addOperation(t).setTimeout(this.options.timeoutInSeconds??Pm),delete this.built,await this.simulate(),this}throw new Jm.Errors.RestorationFailure(`Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n${JSON.stringify(t)}`)}return gm.isSimulationSuccess(this.simulation)&&(this.built=km(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 Jm.Errors.NotYetSimulated("Transaction has not yet been simulated");if(gm.isSimulationError(e))throw new Jm.Errors.SimulationFailed(`Transaction simulation failed: "${e.error}"`);if(gm.isSimulationRestore(e))throw new Jm.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:tl.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(Um);if(!t)return;const n=parseInt(t[1],10),r=this.options.errorTypes[n];return r?new Om(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 Jm.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 Jm.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");if(!this.options.publicKey)throw new Jm.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 Jm.Errors.NeedsMoreSignatures(`Transaction requires signatures from ${n}. See \`needsNonInvokerSigningBy\` for details.`);const r=this.options.timeoutInSeconds??Pm;this.built=yf.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:i,error:s}=await t(this.built.toXDR(),o);this.handleWalletError(s),this.signed=yf.fromXDR(i,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 Dm.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=>If(e.credentials())).filter(t=>null!==t&&(e||"scvVoid"===t.signature().switch().name)).map(e=>Op.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=_f}={})=>{if(!this.built)throw new Error("Transaction has not yet been assembled or simulated");if(r===_f){const e=this.needsNonInvokerSigningBy();if(0===e.length)throw new Jm.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");if(-1===e.indexOf(n??""))throw new Jm.Errors.NoSignatureNeeded(`No auth entries for public key "${n}"`);if(!t)throw new Jm.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`")}const o=this.built.operations[0].auth??[];for(const[i,s]of o.entries()){const a=If(tl.SorobanCredentials.fromXDR(s.credentials().toXDR()));if(null===a)continue;if(Op.fromScAddress(a.address()).toString()!==n)continue;const c=t??Promise.resolve;o[i]=await r(s,async e=>{const{signedAuthEntry:t,error:r}=await c(e.toXDR("base64"),{address:n});return this.handleWalletError(r),oo.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 Fm(this.options,this.server);const n=await Jm.buildFootprintRestoreTransaction({...this.options},e.transactionData,t,e.minResourceFee),r=await n.signAndSend();if(!r.getTransactionResponse)throw new Jm.Errors.RestorationFailure(`The attempt at automatic restore failed. \n${JSON.stringify(r)}`);return r.getTransactionResponse}}function Qm(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 i(){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=i(),s=r;if(0===e){const e=i();if(e>0&&r+e<=s+n){const i=o(e),a=o(n-(r-s));try{const e=new TextDecoder("utf-8",{fatal:!0}).decode(i);a.length>0&&t.set(e,(t.get(e)||[]).concat(a))}catch{}}}r=s+n}return t}(e);let n=t.get("contractspecv0");if(!n||0===n.length)throw new Error("Could not obtain contract spec from wasm");return oo.Buffer.from(n[0])}function ey(e){return/^\d+$/.test(e.name().toString())}const ty={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 ny(e){let t;switch(e.switch().value){case tl.ScSpecType.scSpecTypeVal().value:t="Val";break;case tl.ScSpecType.scSpecTypeBool().value:return{type:"boolean"};case tl.ScSpecType.scSpecTypeVoid().value:return{type:"null"};case tl.ScSpecType.scSpecTypeError().value:t="Error";break;case tl.ScSpecType.scSpecTypeU32().value:t="U32";break;case tl.ScSpecType.scSpecTypeI32().value:t="I32";break;case tl.ScSpecType.scSpecTypeU64().value:t="U64";break;case tl.ScSpecType.scSpecTypeI64().value:t="I64";break;case tl.ScSpecType.scSpecTypeTimepoint().value:t="Timepoint";break;case tl.ScSpecType.scSpecTypeDuration().value:t="Duration";break;case tl.ScSpecType.scSpecTypeU128().value:t="U128";break;case tl.ScSpecType.scSpecTypeI128().value:t="I128";break;case tl.ScSpecType.scSpecTypeU256().value:t="U256";break;case tl.ScSpecType.scSpecTypeI256().value:t="I256";break;case tl.ScSpecType.scSpecTypeBytes().value:t="DataUrl";break;case tl.ScSpecType.scSpecTypeString().value:t="ScString";break;case tl.ScSpecType.scSpecTypeSymbol().value:t="ScSymbol";break;case tl.ScSpecType.scSpecTypeAddress().value:t="Address";break;case tl.ScSpecType.scSpecTypeMuxedAddress().value:t="MuxedAddress";break;case tl.ScSpecType.scSpecTypeOption().value:return ny(e.option().valueType());case tl.ScSpecType.scSpecTypeResult().value:return ny(e.result().okType());case tl.ScSpecType.scSpecTypeVec().value:return{type:"array",items:ny(e.vec().elementType())};case tl.ScSpecType.scSpecTypeMap().value:{const t=e.map();return{type:"array",items:{type:"array",items:[ny(t.keyType()),ny(t.valueType())],minItems:2,maxItems:2}}}case tl.ScSpecType.scSpecTypeTuple().value:{const t=e.tuple(),n=t.valueTypes().length,r=n;return{type:"array",items:t.valueTypes().map(ny),minItems:n,maxItems:r}}case tl.ScSpecType.scSpecTypeBytesN().value:return{$ref:"#/definitions/DataUrl",maxLength:e.bytesN().n()};case tl.ScSpecType.scSpecTypeUdt().value:t=e.udt().name().toString();break}return{$ref:`#/definitions/${t}`}}function ry(e){const t={},n=[];e.forEach(e=>{const r=e.type(),o=e.name().toString();t[o]=ny(r),r.switch().value!==tl.ScSpecType.scSpecTypeOption().value&&n.push(o)});const r={properties:t};return n.length>0&&(r.required=n),r}class oy{entries=[];static fromWasm(e){const t=Qm(e);return new oy(t)}constructor(e){if(oo.Buffer.isBuffer(e))this.entries=Nm(e);else if("string"==typeof e)this.entries=Nm(oo.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=>tl.ScSpecEntry.fromXDR(e,"base64")):e}}funcs(){return this.entries.filter(e=>e.switch().value===tl.ScSpecEntryKind.scSpecEntryFunctionV0().value).map(e=>e.functionV0())}getFunc(e){const t=this.findEntry(e);if(t.switch().value!==tl.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?tl.ScVal.fromXDR(t,"base64"):t,r=this.getFunc(e).outputs();if(0===r.length){const e=n.switch();if(e.value!==tl.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===tl.ScSpecType.scSpecTypeResult().value?n.switch().value===tl.ScValType.scvError().value?new Om({message:n.error().toXDR("base64")}):new Bm(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===tl.ScSpecType.scSpecTypeUdt().value){const n=t.udt();return this.nativeToUdt(e,n.name().toString())}if(r===tl.ScSpecType.scSpecTypeOption().value){const n=t.option();return null==e?tl.ScVal.scvVoid():this.nativeToScVal(e,n.valueType())}switch(typeof e){case"object":if(null===e){if(r===tl.ScSpecType.scSpecTypeVoid().value)return tl.ScVal.scvVoid();throw new TypeError(`Type ${t} was not void, but value was null`)}if(e instanceof tl.ScVal)return e;if(e instanceof Op){if(t.switch().value!==tl.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.toScVal()}if(e instanceof nf){if(t.switch().value!==tl.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.address().toScVal()}if(e instanceof Uint8Array||oo.Buffer.isBuffer(e)){const n=Uint8Array.from(e);switch(r){case tl.ScSpecType.scSpecTypeBytesN().value:{const e=t.bytesN();if(n.length!==e.n())throw new TypeError(`expected ${e.n()} bytes, but got ${n.length}`);return tl.ScVal.scvBytes(n)}case tl.ScSpecType.scSpecTypeBytes().value:return tl.ScVal.scvBytes(n);default:throw new TypeError(`invalid type (${t}) specified for Bytes and BytesN`)}}if(Array.isArray(e))switch(r){case tl.ScSpecType.scSpecTypeVec().value:{const n=t.vec().elementType();return tl.ScVal.scvVec(e.map(e=>this.nativeToScVal(e,n)))}case tl.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 tl.ScVal.scvVec(e.map((e,t)=>this.nativeToScVal(e,n[t])))}case tl.ScSpecType.scSpecTypeMap().value:{const n=t.map(),r=n.keyType(),o=n.valueType();return tl.ScVal.scvMap(e.map(e=>{const t=this.nativeToScVal(e[0],r),n=this.nativeToScVal(e[1],o);return new tl.ScMapEntry({key:t,val:n})}))}default:throw new TypeError(`Type ${t} was not vec, but value was Array`)}if(e.constructor===Map){if(r!==tl.ScSpecType.scSpecTypeMap().value)throw new TypeError(`Type ${t} was not map, but value was Map`);const n=t.map(),o=[],i=e.entries();let s=i.next();for(;!s.done;){const[e,t]=s.value,r=this.nativeToScVal(e,n.keyType()),a=this.nativeToScVal(t,n.valueType());o.push(new tl.ScMapEntry({key:r,val:a})),s=i.next()}return tl.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 tl.ScSpecType.scSpecTypeU32().value:if(BigInt(e)<BigInt(tl.Uint32.MIN_VALUE)||BigInt(e)>BigInt(tl.Uint32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for U32`);return tl.ScVal.scvU32(Number(e));case tl.ScSpecType.scSpecTypeI32().value:if(BigInt(e)<-BigInt(tl.Int32.MIN_VALUE)||BigInt(e)>BigInt(tl.Int32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for I32`);return tl.ScVal.scvI32(Number(e));case tl.ScSpecType.scSpecTypeU64().value:case tl.ScSpecType.scSpecTypeI64().value:case tl.ScSpecType.scSpecTypeU128().value:case tl.ScSpecType.scSpecTypeI128().value:case tl.ScSpecType.scSpecTypeU256().value:case tl.ScSpecType.scSpecTypeI256().value:case tl.ScSpecType.scSpecTypeTimepoint().value:case tl.ScSpecType.scSpecTypeDuration().value:{const t=n.name.substring(10).toLowerCase();return new cf(t,e).toScVal()}default:throw new TypeError(`invalid type (${t}) specified for integer`)}case"string":return function(e,t){switch(t.value){case tl.ScSpecType.scSpecTypeString().value:return tl.ScVal.scvString(e);case tl.ScSpecType.scSpecTypeSymbol().value:return tl.ScVal.scvSymbol(e);case tl.ScSpecType.scSpecTypeAddress().value:case tl.ScSpecType.scSpecTypeMuxedAddress().value:return Op.fromString(e).toScVal();case tl.ScSpecType.scSpecTypeU64().value:return new cf("u64",e).toScVal();case tl.ScSpecType.scSpecTypeI64().value:return new cf("i64",e).toScVal();case tl.ScSpecType.scSpecTypeU128().value:return new cf("u128",e).toScVal();case tl.ScSpecType.scSpecTypeI128().value:return new cf("i128",e).toScVal();case tl.ScSpecType.scSpecTypeU256().value:return new cf("u256",e).toScVal();case tl.ScSpecType.scSpecTypeI256().value:return new cf("i256",e).toScVal();case tl.ScSpecType.scSpecTypeBytes().value:case tl.ScSpecType.scSpecTypeBytesN().value:return tl.ScVal.scvBytes(oo.Buffer.from(e,"base64"));case tl.ScSpecType.scSpecTypeTimepoint().value:return tl.ScVal.scvTimepoint(new tl.Uint64(e));case tl.ScSpecType.scSpecTypeDuration().value:return tl.ScVal.scvDuration(new tl.Uint64(e));default:throw new TypeError(`invalid type ${t.name} specified for string value`)}}(e,n);case"boolean":if(r!==tl.ScSpecType.scSpecTypeBool().value)throw TypeError(`Type ${t} was not bool, but value was bool`);return tl.ScVal.scvBool(e);case"undefined":if(!t)return tl.ScVal.scvVoid();switch(r){case tl.ScSpecType.scSpecTypeVoid().value:case tl.ScSpecType.scSpecTypeOption().value:return tl.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 tl.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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,n.udtStructV0());case tl.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=tl.ScVal.scvSymbol(n);switch(r.switch()){case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return tl.ScVal.scvVec([o]);case tl.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),tl.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(ey)){if(!n.every(ey))throw new Error("mixed numeric and non-numeric field names are not allowed");return tl.ScVal.scvVec(n.map((t,r)=>this.nativeToScVal(e[r],n[r].type())))}return tl.ScVal.scvMap(n.map(t=>{const n=t.name().toString();return new tl.ScMapEntry({key:this.nativeToScVal(n,tl.ScSpecTypeDef.scSpecTypeSymbol()),val:this.nativeToScVal(e[n],t.type())})}))}nativeToEnum(e,t){if(t.cases().some(t=>t.value()===e))return tl.ScVal.scvU32(e);throw new TypeError(`no such enum entry: ${e} in ${t}`)}scValStrToNative(e,t){return this.scValToNative(tl.ScVal.fromXDR(e,"base64"),t)}scValToNative(e,t){const n=t.switch(),r=n.value;if(r===tl.ScSpecType.scSpecTypeOption().value)return e.switch().value===tl.ScValType.scvVoid().value?null:this.scValToNative(e,t.option().valueType());if(r===tl.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case tl.ScValType.scvVoid().value:return null;case tl.ScValType.scvU64().value:case tl.ScValType.scvI64().value:case tl.ScValType.scvTimepoint().value:case tl.ScValType.scvDuration().value:case tl.ScValType.scvU128().value:case tl.ScValType.scvI128().value:case tl.ScValType.scvU256().value:case tl.ScValType.scvI256().value:return lf(e);case tl.ScValType.scvVec().value:if(r===tl.ScSpecType.scSpecTypeVec().value){const n=t.vec();return(e.vec()??[]).map(e=>this.scValToNative(e,n.elementType()))}if(r===tl.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 tl.ScValType.scvAddress().value:return Op.fromScVal(e).toString();case tl.ScValType.scvMap().value:{const o=e.map()??[];if(r===tl.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 tl.ScValType.scvBool().value:case tl.ScValType.scvU32().value:case tl.ScValType.scvI32().value:case tl.ScValType.scvBytes().value:return e.value();case tl.ScValType.scvString().value:case tl.ScValType.scvSymbol().value:if(r!==tl.ScSpecType.scSpecTypeString().value&&r!==tl.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 tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,n.udtStructV0());case tl.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!==tl.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 tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case tl.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 i={tag:r};if(o.switch().value===tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){const e=o.tupleCase().type().map((e,t)=>this.scValToNative(n[t+1],e));i.values=e}return i}structToNative(e,t){const n={},r=t.fields();if(r.some(ey)){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!==tl.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}errorCases(){return this.entries.filter(e=>e.switch().value===tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value).flatMap(e=>e.value().cases())}jsonSchema(e){const t={};this.entries.forEach(e=>{switch(e.switch().value){case tl.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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0().value:{const n=e.udtStructV0();t[n.name().toString()]=function(e){const t=e.fields();if(t.some(ey)){if(!t.every(ey))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((e,n)=>ny(t[n].type())),minItems:t.length,maxItems:t.length}}const n=e.doc().toString(),{properties:r,required:o}=ry(t);return{description:n,properties:r,required:o,additionalProperties:!1,type:"object"}}(n);break}case tl.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 tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:{const t=e.voidCase().name().toString();r.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break}case tl.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(ny)}},required:["tag","values"],additionalProperties:!1})}}});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case tl.ScSpecEntryKind.scSpecEntryFunctionV0().value:{const n=e.functionV0(),r=n.name().toString(),{input:o}=function(e){const{properties:t,required:n}=ry(e.inputs()),r={additionalProperties:!1,properties:t,type:"object"};n?.length>0&&(r.required=n);const o={properties:{args:r}},i=e.outputs(),s=i.length>0?ny(i[0]):ny(tl.ScSpecTypeDef.scSpecTypeVoid()),a=e.doc().toString();return a.length>0&&(o.description=a),o.additionalProperties=!1,s.additionalProperties=!1,{input:o,output:s}}(n);t[r]=o;break}case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}});const n={$schema:"http://json-schema.org/draft-07/schema#",definitions:{...ty,...t}};return e&&(n.$ref=`#/definitions/${e}`),n}}function iy(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 sy(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ay(e,t=!1){switch(e.switch()){case tl.ScSpecType.scSpecTypeVal():return"any";case tl.ScSpecType.scSpecTypeBool():return"boolean";case tl.ScSpecType.scSpecTypeVoid():return"null";case tl.ScSpecType.scSpecTypeError():return"Error";case tl.ScSpecType.scSpecTypeU32():case tl.ScSpecType.scSpecTypeI32():return"number";case tl.ScSpecType.scSpecTypeU64():case tl.ScSpecType.scSpecTypeI64():case tl.ScSpecType.scSpecTypeTimepoint():case tl.ScSpecType.scSpecTypeDuration():case tl.ScSpecType.scSpecTypeU128():case tl.ScSpecType.scSpecTypeI128():case tl.ScSpecType.scSpecTypeU256():case tl.ScSpecType.scSpecTypeI256():return"bigint";case tl.ScSpecType.scSpecTypeBytes():case tl.ScSpecType.scSpecTypeBytesN():return"Buffer";case tl.ScSpecType.scSpecTypeString():case tl.ScSpecType.scSpecTypeSymbol():return"string";case tl.ScSpecType.scSpecTypeAddress():case tl.ScSpecType.scSpecTypeMuxedAddress():return t?"string | Address":"string";case tl.ScSpecType.scSpecTypeVec():return`Array<${ay(e.vec().elementType(),t)}>`;case tl.ScSpecType.scSpecTypeMap():return`Map<${ay(e.map().keyType(),t)}, ${ay(e.map().valueType(),t)}>`;case tl.ScSpecType.scSpecTypeTuple():return`[${e.tuple().valueTypes().map(e=>ay(e,t)).join(", ")}]`;case tl.ScSpecType.scSpecTypeOption():for(;e.option().valueType().switch()===tl.ScSpecType.scSpecTypeOption();)e=e.option().valueType();return`${ay(e.option().valueType(),t)} | null`;case tl.ScSpecType.scSpecTypeResult():return`Result<${ay(e.result().okType(),t)}, ${ay(e.result().errorType(),t)}>`;case tl.ScSpecType.scSpecTypeUdt():return iy(e.udt().name().toString());default:return"unknown"}}function cy(e,t){switch(e.switch()){case tl.ScSpecType.scSpecTypeUdt():return void t.typeFileImports.add(iy(e.udt().name().toString()));case tl.ScSpecType.scSpecTypeAddress():case tl.ScSpecType.scSpecTypeMuxedAddress():return void t.stellarImports.add("Address");case tl.ScSpecType.scSpecTypeBytes():case tl.ScSpecType.scSpecTypeBytesN():return void(t.needsBufferImport=!0);case tl.ScSpecType.scSpecTypeVal():return void t.stellarImports.add("xdr");case tl.ScSpecType.scSpecTypeResult():t.stellarContractImports.add("Result");break;case tl.ScSpecType.scSpecTypeBool():case tl.ScSpecType.scSpecTypeVoid():case tl.ScSpecType.scSpecTypeError():case tl.ScSpecType.scSpecTypeU32():case tl.ScSpecType.scSpecTypeI32():case tl.ScSpecType.scSpecTypeU64():case tl.ScSpecType.scSpecTypeI64():case tl.ScSpecType.scSpecTypeTimepoint():case tl.ScSpecType.scSpecTypeDuration():case tl.ScSpecType.scSpecTypeU128():case tl.ScSpecType.scSpecTypeI128():case tl.ScSpecType.scSpecTypeU256():case tl.ScSpecType.scSpecTypeI256():case tl.ScSpecType.scSpecTypeString():case tl.ScSpecType.scSpecTypeSymbol():return}const n=function(e){switch(e.switch()){case tl.ScSpecType.scSpecTypeVec():return[e.vec().elementType()];case tl.ScSpecType.scSpecTypeMap():return[e.map().keyType(),e.map().valueType()];case tl.ScSpecType.scSpecTypeTuple():return e.tuple().valueTypes();case tl.ScSpecType.scSpecTypeOption():return[e.option().valueType()];case tl.ScSpecType.scSpecTypeResult():return[e.result().okType(),e.result().errorType()];default:return[]}}(e);n.forEach(e=>cy(e,t))}function uy(e){const t={typeFileImports:new Set,stellarContractImports:new Set,stellarImports:new Set,needsBufferImport:!1};return e.forEach(e=>cy(e,t)),t}function ly(e,t){const n=[],r=e.typeFileImports,o=[...e.stellarContractImports,...t?.additionalStellarContractImports||[]],i=[...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(i.length>0){const e=Array.from(new Set(i));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk';`)}return e.needsBufferImport&&n.push("import { Buffer } from 'buffer';"),n.join("\n")}function dy(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 hy="__constructor";class py{constructor(e,t){if(this.spec=e,this.options=t,void 0===t.server){const{allowHttp:e,headers:n}=t;t.server=new xm(t.rpcUrl,{allowHttp:e,headers:n})}this.spec.funcs().forEach(n=>{const r=n.name().toString();if(r===hy)return;const o=(n,o)=>Jm.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[iy(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:i,timeoutInSeconds:s,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:i}=t,s=new xm(r,{allowHttp:o,headers:i}),a=await s.getContractWasmByHash(e,n);return oy.fromWasm(a)}(n,c,o),l=Vp.createCustomContract({address:new Op(t.address||t.publicKey),wasmHash:"string"==typeof n?oo.Buffer.from(n,o??"hex"):n,salt:r,constructorArgs:e?u.funcArgsToScVals(hy,e):[]});return Jm.buildWithOp(l,{fee:i,timeoutInSeconds:s,simulate:a,...c,contractId:"ignored",method:hy,parseResultXdr:e=>new py(u,{...c,contractId:Op.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:i}=t,s=t.server??new xm(r,{allowHttp:o,headers:i}),a=await s.getContractWasmByHash(e,n);return py.fromWasm(a,t)}static async fromWasm(e,t){const n=await oy.fromWasm(e);return new py(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,i=new xm(t,{allowHttp:r,headers:o}),s=await i.getContractWasmByContractId(n);return py.fromWasm(s,e)}txFromJSON=e=>{const{method:t,...n}=JSON.parse(e);return Jm.fromJSON({...this.options,method:t,parseResultXdr:e=>this.spec.funcResToNative(t,e)},n)};txFromXDR=e=>Jm.fromXDR(this.options,e,this.spec)}var fy=Object.freeze({__proto__:null,AssembledTransaction:Jm,Client:py,DEFAULT_TIMEOUT:Pm,Err:Om,NULL_ACCOUNT:Lm,Ok:Bm,SentTransaction:Dm,Spec:oy,Watcher:class{},basicNodeSigner:(e,t)=>({signTransaction:async(n,r)=>{const o=yf.fromXDR(n,r?.networkPassphrase||t);return o.sign(e),{signedTxXdr:o.toXDR(),signerAddress:e.publicKey()}},signAuthEntry:async t=>({signedAuthEntry:e.sign($l(oo.Buffer.from(t,"base64"))).toString("base64"),signerAddress:e.publicKey()})})});class gy{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-rc.2",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 my{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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().every((e,t)=>e.name().toString().trim()===t.toString())?this.generateTupleStruct(e.udtStructV0()):this.generateStruct(e.udtStructV0());case tl.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.generateUnion(e.udtUnionV0());case tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.generateEnum(e.udtEnumV0());case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():return this.generateErrorEnum(e.udtErrorEnumV0());default:return null}}generateImports(){return ly(uy(this.spec.entries.flatMap(e=>{switch(e.switch()){case tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().map(e=>e.type());case tl.ScSpecEntryKind.scSpecEntryUdtUnionV0():return e.udtUnionV0().cases().flatMap(e=>e.switch()===tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0()?e.tupleCase().type():[]);case tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():default:return[]}})),{includeTypeFileImports:!1})}generateStruct(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Struct: ${t}`,0)}export interface ${t} {\n${e.fields().map(e=>{const t=iy(e.name().toString()),n=ay(e.type());return`${dy(e.doc().toString(),2)} ${t}: ${n};`}).join("\n")}\n}`}generateUnion(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Union: ${t}`,0)} export type ${t} =\n${e.cases().map(e=>this.generateUnionCase(e)).map(e=>e.types.length>0?`${dy(e.doc,2)} { tag: "${sy(e.name)}"; values: readonly [${e.types.join(", ")}] }`:`${dy(e.doc,2)} { tag: "${sy(e.name)}"; values: void }`).join(" |\n")};`}generateEnum(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Enum: ${t}`,0)}export enum ${t} {\n${e.cases().map(e=>{const t=iy(e.name().toString()),n=e.value();return`${dy(e.doc().toString()||`Enum Case: ${t}`,2)} ${t} = ${n}`}).join(",\n")}\n}`}generateErrorEnum(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Error Enum: ${t}`,0)}export const ${t} = {\n${e.cases().map(e=>this.generateEnumCase(e)).map(e=>`${dy(e.doc,2)} ${e.value} : { message: "${sy(e.name)}" }`).join(",\n")}\n}`}generateUnionCase(e){switch(e.switch()){case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():{const t=e.voidCase();return{doc:t.doc().toString(),name:t.name().toString(),types:[]}}case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const t=e.tupleCase();return{doc:t.doc().toString(),name:t.name().toString(),types:t.type().map(e=>ay(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=iy(e.name().toString());return`${dy(e.doc().toString()||`Tuple Struct: ${t}`,0)}export type ${t} = readonly [${e.fields().map(e=>ay(e.type())).join(", ")}];`}}class yy{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 ly(uy(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=iy(e.name().toString()),n=e.inputs().map(e=>({name:iy(e.name().toString()),type:ay(e.type(),!0)})),r=e.outputs().length>0?ay(e.outputs()[0]):"void";return`${dy(e.doc().toString(),2)} ${t}(${this.formatMethodParameters(n)}): Promise<AssembledTransaction<${r}>>;`}generateFromJSONMethod(e){return` ${iy(e.name().toString())} : this.txFromJSON<${e.outputs().length>0?ay(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:iy(e.name().toString()),type:ay(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 wy extends Error{constructor(e,t){super(e),this.cause=t,this.name="WasmFetchError"}cause}async function by(e,t){try{const n=tl.LedgerKey.contractCode(new tl.LedgerKeyContractCode({hash:tl.Hash.fromXDR(t,"raw")})),r=await e.getLedgerEntries(n);if(!r.entries||0===r.entries.length)throw new wy("WASM not found for the given hash");const o=r.entries[0];if(o.key.switch()!==tl.LedgerEntryType.contractCode())throw new wy("Invalid ledger entry type returned");const i=o.val.contractCode();return oo.Buffer.from(i.code())}catch(e){if(e instanceof wy)throw e;throw new wy("Failed to fetch WASM from hash",e)}}async function vy(e,t){try{const n=new nf(t.toString()),r=await e.getLedgerEntries(n.getFootprint());if(!r.entries||0===r.entries.length)throw new wy("Contract instance not found");const o=r.entries[0];if(o.key.switch()!==tl.LedgerEntryType.contractData())throw new wy("Invalid ledger entry type returned");const i=o.val.contractData().val().instance();if(function(e){return e.executable().switch()===tl.ContractExecutableType.contractExecutableStellarAsset()}(i))return{type:"stellar-asset-contract"};const s=i.executable().wasmHash();return{type:"wasm",wasmBytes:await by(e,s)}}catch(e){if(e instanceof wy)throw e;throw new wy("Failed to fetch WASM from contract",e)}}class Ay{spec;constructor(e){this.spec=e}static fromSpec(e){return new Ay(e)}static fromWasm(e){const t=new oy(Qm(e));return new Ay(t)}static async fromWasmHash(e,t){const n=await async function(e,t){try{const n=oo.Buffer.from(e,"hex");if(32!==n.length)throw new wy(`Invalid WASM hash length: expected 32 bytes, got ${n.length}`);return{type:"wasm",wasmBytes:await by(t,n)}}catch(t){throw new wy(`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 Ay.fromWasm(n.wasmBytes)}static async fromContractId(e,t){const n=await async function(e,t){try{if(!ih.isValidContract(e))throw new wy(`Invalid contract ID: ${e}`);const n=Op.fromString(e);return await vy(t,n)}catch(t){throw new wy(`Failed to fetch WASM from contract ${e}`,t)}}(e,t);if("wasm"===n.type)return Ay.fromWasm(n.wasmBytes);const r=new oy("AAAAAAAAAYpSZXR1cm5zIHRoZSBhbGxvd2FuY2UgZm9yIGBzcGVuZGVyYCB0byB0cmFuc2ZlciBmcm9tIGBmcm9tYC4KClRoZSBhbW91bnQgcmV0dXJuZWQgaXMgdGhlIGFtb3VudCB0aGF0IHNwZW5kZXIgaXMgYWxsb3dlZCB0byB0cmFuc2ZlcgpvdXQgb2YgZnJvbSdzIGJhbGFuY2UuIFdoZW4gdGhlIHNwZW5kZXIgdHJhbnNmZXJzIGFtb3VudHMsIHRoZSBhbGxvd2FuY2UKd2lsbCBiZSByZWR1Y2VkIGJ5IHRoZSBhbW91bnQgdHJhbnNmZXJyZWQuCgojIEFyZ3VtZW50cwoKKiBgZnJvbWAgLSBUaGUgYWRkcmVzcyBob2xkaW5nIHRoZSBiYWxhbmNlIG9mIHRva2VucyB0byBiZSBkcmF3biBmcm9tLgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIHNwZW5kaW5nIHRoZSB0b2tlbnMgaGVsZCBieSBgZnJvbWAuAAAAAAAJYWxsb3dhbmNlAAAAAAAAAgAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAEAAAALAAAAAAAAAIlSZXR1cm5zIHRydWUgaWYgYGlkYCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBpZGAgLSBUaGUgYWRkcmVzcyBmb3Igd2hpY2ggdG9rZW4gYXV0aG9yaXphdGlvbiBpcyBiZWluZyBjaGVja2VkLgAAAAAAAAphdXRob3JpemVkAAAAAAABAAAAAAAAAAJpZAAAAAAAEwAAAAEAAAABAAAAAAAAA59TZXQgdGhlIGFsbG93YW5jZSBieSBgYW1vdW50YCBmb3IgYHNwZW5kZXJgIHRvIHRyYW5zZmVyL2J1cm4gZnJvbQpgZnJvbWAuCgpUaGUgYW1vdW50IHNldCBpcyB0aGUgYW1vdW50IHRoYXQgc3BlbmRlciBpcyBhcHByb3ZlZCB0byB0cmFuc2ZlciBvdXQgb2YKZnJvbSdzIGJhbGFuY2UuIFRoZSBzcGVuZGVyIHdpbGwgYmUgYWxsb3dlZCB0byB0cmFuc2ZlciBhbW91bnRzLCBhbmQKd2hlbiBhbiBhbW91bnQgaXMgdHJhbnNmZXJyZWQgdGhlIGFsbG93YW5jZSB3aWxsIGJlIHJlZHVjZWQgYnkgdGhlCmFtb3VudCB0cmFuc2ZlcnJlZC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHRvIGJlIGRyYXduIGZyb20uCiogYHNwZW5kZXJgIC0gVGhlIGFkZHJlc3MgYmVpbmcgYXV0aG9yaXplZCB0byBzcGVuZCB0aGUgdG9rZW5zIGhlbGQgYnkKYGZyb21gLgoqIGBhbW91bnRgIC0gVGhlIHRva2VucyB0byBiZSBtYWRlIGF2YWlsYWJsZSB0byBgc3BlbmRlcmAuCiogYGV4cGlyYXRpb25fbGVkZ2VyYCAtIFRoZSBsZWRnZXIgbnVtYmVyIHdoZXJlIHRoaXMgYWxsb3dhbmNlIGV4cGlyZXMuIENhbm5vdApiZSBsZXNzIHRoYW4gdGhlIGN1cnJlbnQgbGVkZ2VyIG51bWJlciB1bmxlc3MgdGhlIGFtb3VudCBpcyBiZWluZyBzZXQgdG8gMC4KQW4gZXhwaXJlZCBlbnRyeSAod2hlcmUgZXhwaXJhdGlvbl9sZWRnZXIgPCB0aGUgY3VycmVudCBsZWRnZXIgbnVtYmVyKQpzaG91bGQgYmUgdHJlYXRlZCBhcyBhIDAgYW1vdW50IGFsbG93YW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJhcHByb3ZlIiwgZnJvbTogQWRkcmVzcywKc3BlbmRlcjogQWRkcmVzc10sIGRhdGEgPSBbYW1vdW50OiBpMTI4LCBleHBpcmF0aW9uX2xlZGdlcjogdTMyXWAAAAAAB2FwcHJvdmUAAAAABAAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAABFleHBpcmF0aW9uX2xlZGdlcgAAAAAAAAQAAAAAAAAAAAAAAJhSZXR1cm5zIHRoZSBiYWxhbmNlIG9mIGBpZGAuCgojIEFyZ3VtZW50cwoKKiBgaWRgIC0gVGhlIGFkZHJlc3MgZm9yIHdoaWNoIGEgYmFsYW5jZSBpcyBiZWluZyBxdWVyaWVkLiBJZiB0aGUKYWRkcmVzcyBoYXMgbm8gZXhpc3RpbmcgYmFsYW5jZSwgcmV0dXJucyAwLgAAAAdiYWxhbmNlAAAAAAEAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAsAAAAAAAABYkJ1cm4gYGFtb3VudGAgZnJvbSBgZnJvbWAuCgpSZWR1Y2VzIGZyb20ncyBiYWxhbmNlIGJ5IHRoZSBhbW91bnQsIHdpdGhvdXQgdHJhbnNmZXJyaW5nIHRoZSBiYWxhbmNlCnRvIGFub3RoZXIgaG9sZGVyJ3MgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAABGJ1cm4AAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAALaQnVybiBgYW1vdW50YCBmcm9tIGBmcm9tYCwgY29uc3VtaW5nIHRoZSBhbGxvd2FuY2Ugb2YgYHNwZW5kZXJgLgoKUmVkdWNlcyBmcm9tJ3MgYmFsYW5jZSBieSB0aGUgYW1vdW50LCB3aXRob3V0IHRyYW5zZmVycmluZyB0aGUgYmFsYW5jZQp0byBhbm90aGVyIGhvbGRlcidzIGJhbGFuY2UuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gYnVybiB0aGUgYW1vdW50IGZyb20gZnJvbSdzIGJhbGFuY2UsIGlmCnRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlciBoYXMKb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZSB3aWxsIGJlCnJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSBidXJuLCBhbmQgaGF2aW5nIGl0cyBhbGxvd2FuY2UKY29uc3VtZWQgZHVyaW5nIHRoZSBidXJuLgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAACWJ1cm5fZnJvbQAAAAAAAAMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAABUUNsYXdiYWNrIGBhbW91bnRgIGZyb20gYGZyb21gIGFjY291bnQuIGBhbW91bnRgIGlzIGJ1cm5lZCBpbiB0aGUKY2xhd2JhY2sgcHJvY2Vzcy4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2UgZnJvbSB3aGljaCB0aGUgY2xhd2JhY2sgd2lsbAp0YWtlIHRva2Vucy4KKiBgYW1vdW50YCAtIFRoZSBhbW91bnQgb2YgdG9rZW5zIHRvIGJlIGNsYXdlZCBiYWNrLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbImNsYXdiYWNrIiwgYWRtaW46IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAACAUmV0dXJucyB0aGUgbnVtYmVyIG9mIGRlY2ltYWxzIHVzZWQgdG8gcmVwcmVzZW50IGFtb3VudHMgb2YgdGhpcyB0b2tlbi4KCiMgUGFuaWNzCgpJZiB0aGUgY29udHJhY3QgaGFzIG5vdCB5ZXQgYmVlbiBpbml0aWFsaXplZC4AAAAIZGVjaW1hbHMAAAAAAAAAAQAAAAQAAAAAAAAA801pbnRzIGBhbW91bnRgIHRvIGB0b2AuCgojIEFyZ3VtZW50cwoKKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSBtaW50ZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgbWludGVkLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbIm1pbnQiLCBhZG1pbjogQWRkcmVzcywgdG86IEFkZHJlc3NdLCBkYXRhCj0gYW1vdW50OiBpMTI4YAAAAAAEbWludAAAAAIAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAFlSZXR1cm5zIHRoZSBuYW1lIGZvciB0aGlzIHRva2VuLgoKIyBQYW5pY3MKCklmIHRoZSBjb250cmFjdCBoYXMgbm90IHlldCBiZWVuIGluaXRpYWxpemVkLgAAAAAAAARuYW1lAAAAAAAAAAEAAAAQAAAAAAAAAQxTZXRzIHRoZSBhZG1pbmlzdHJhdG9yIHRvIHRoZSBzcGVjaWZpZWQgYWRkcmVzcyBgbmV3X2FkbWluYC4KCiMgQXJndW1lbnRzCgoqIGBuZXdfYWRtaW5gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCBoZW5jZWZvcnRoIGJlIHRoZSBhZG1pbmlzdHJhdG9yCm9mIHRoaXMgdG9rZW4gY29udHJhY3QuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsic2V0X2FkbWluIiwgYWRtaW46IEFkZHJlc3NdLCBkYXRhID0KW25ld19hZG1pbjogQWRkcmVzc11gAAAACXNldF9hZG1pbgAAAAAAAAEAAAAAAAAACW5ld19hZG1pbgAAAAAAABMAAAAAAAAAAAAAAEZSZXR1cm5zIHRoZSBhZG1pbiBvZiB0aGUgY29udHJhY3QuCgojIFBhbmljcwoKSWYgdGhlIGFkbWluIGlzIG5vdCBzZXQuAAAAAAAFYWRtaW4AAAAAAAAAAAAAAQAAABMAAAAAAAABUFNldHMgd2hldGhlciB0aGUgYWNjb3VudCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4gSWYKYGF1dGhvcml6ZWRgIGlzIHRydWUsIGBpZGAgc2hvdWxkIGJlIGFibGUgdG8gdXNlIGl0cyBiYWxhbmNlLgoKIyBBcmd1bWVudHMKCiogYGlkYCAtIFRoZSBhZGRyZXNzIGJlaW5nIChkZS0pYXV0aG9yaXplZC4KKiBgYXV0aG9yaXplYCAtIFdoZXRoZXIgb3Igbm90IGBpZGAgY2FuIHVzZSBpdHMgYmFsYW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJzZXRfYXV0aG9yaXplZCIsIGlkOiBBZGRyZXNzXSwgZGF0YSA9ClthdXRob3JpemU6IGJvb2xdYAAAAA5zZXRfYXV0aG9yaXplZAAAAAAAAgAAAAAAAAACaWQAAAAAABMAAAAAAAAACWF1dGhvcml6ZQAAAAAAAAEAAAAAAAAAAAAAAFtSZXR1cm5zIHRoZSBzeW1ib2wgZm9yIHRoaXMgdG9rZW4uCgojIFBhbmljcwoKSWYgdGhlIGNvbnRyYWN0IGhhcyBub3QgeWV0IGJlZW4gaW5pdGlhbGl6ZWQuAAAAAAZzeW1ib2wAAAAAAAAAAAABAAAAEAAAAAAAAAFiVHJhbnNmZXIgYGFtb3VudGAgZnJvbSBgZnJvbWAgdG8gYHRvYC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKd2l0aGRyYXduIGZyb20uCiogYHRvYCAtIFRoZSBhZGRyZXNzIHdoaWNoIHdpbGwgcmVjZWl2ZSB0aGUgdHJhbnNmZXJyZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgdHJhbnNmZXJyZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsidHJhbnNmZXIiLCBmcm9tOiBBZGRyZXNzLCB0bzogQWRkcmVzc10sCmRhdGEgPSBhbW91bnQ6IGkxMjhgAAAAAAAIdHJhbnNmZXIAAAADAAAAAAAAAARmcm9tAAAAEwAAAAAAAAACdG8AAAAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAADMVRyYW5zZmVyIGBhbW91bnRgIGZyb20gYGZyb21gIHRvIGB0b2AsIGNvbnN1bWluZyB0aGUgYWxsb3dhbmNlIHRoYXQKYHNwZW5kZXJgIGhhcyBvbiBgZnJvbWAncyBiYWxhbmNlLiBBdXRob3JpemVkIGJ5IHNwZW5kZXIKKGBzcGVuZGVyLnJlcXVpcmVfYXV0aCgpYCkuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gdHJhbnNmZXIgdGhlIGFtb3VudCBmcm9tIGZyb20ncyBiYWxhbmNlCmlmIHRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlcgpoYXMgb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZQp3aWxsIGJlIHJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSB0cmFuc2ZlciwgYW5kIGhhdmluZyBpdHMKYWxsb3dhbmNlIGNvbnN1bWVkIGR1cmluZyB0aGUgdHJhbnNmZXIuCiogYGZyb21gIC0gVGhlIGFkZHJlc3MgaG9sZGluZyB0aGUgYmFsYW5jZSBvZiB0b2tlbnMgd2hpY2ggd2lsbCBiZQp3aXRoZHJhd24gZnJvbS4KKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSB0cmFuc2ZlcnJlZCB0b2tlbnMuCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSB0cmFuc2ZlcnJlZC4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJ0cmFuc2ZlciIsIGZyb206IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAANdHJhbnNmZXJfZnJvbQAAAAAAAAQAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAABQAAAAAAAAAAAAAAB0FwcHJvdmUAAAAAAQAAAAdhcHByb3ZlAAAAAAQAAAAAAAAABGZyb20AAAATAAAAAQAAAAAAAAAHc3BlbmRlcgAAAAATAAAAAQAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAAARZXhwaXJhdGlvbl9sZWRnZXIAAAAAAAAEAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAIVHJhbnNmZXIAAAABAAAACHRyYW5zZmVyAAAAAwAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAADVRyYW5zZmVyTXV4ZWQAAAAAAAABAAAACHRyYW5zZmVyAAAABAAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAAC3RvX211eGVkX2lkAAAAAAQAAAAAAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAgAAAAUAAAAAAAAAAAAAAARCdXJuAAAAAQAAAARidXJuAAAAAgAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAARNaW50AAAAAQAAAARtaW50AAAAAgAAAAAAAAACdG8AAAAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAhDbGF3YmFjawAAAAEAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAACFNldEFkbWluAAAAAQAAAAlzZXRfYWRtaW4AAAAAAAABAAAAAAAAAAluZXdfYWRtaW4AAAAAAAATAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAANU2V0QXV0aG9yaXplZAAAAAAAAAEAAAAOc2V0X2F1dGhvcml6ZWQAAAAAAAIAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAAAAAAJYXV0aG9yaXplAAAAAAAAAQAAAAAAAAAA");return Ay.fromSpec(r)}generate(e){this.validateOptions(e);const t=new my(this.spec),n=new yy(this.spec),r=t.generate(),o=n.generate();let i='export { Client } from "./client.js";';""!==r.trim()&&(i=i.concat('\nexport * from "./types.js";'));const s=new gy,{packageJson:a,tsConfig:c,readme:u,gitignore:l}=s.generate(e);return{index:i,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=Xp,e.AccountRequiresMemoError=_u,e.Address=Op,e.Asset=ph,e.AssetType=dh,e.AuthClawbackEnabledFlag=8,e.AuthImmutableFlag=4,e.AuthRequiredFlag=1,e.AuthRevocableFlag=2,e.BASE_FEE=mf,e.BadRequestError=Tu,e.BadResponseError=Eu,e.BindingGenerator=Ay,e.Claimant=yh,e.Config=Ru,e.Contract=nf,e.Federation=Df,e.FeeBumpTransaction=Kp,e.Friendbot=Qf,e.Horizon=mm,e.Hyper=el.Hyper,e.Int128=sf,e.Int256=af,e.Keypair=lh,e.LiquidityPoolAsset=mh,e.LiquidityPoolFeeV18=30,e.LiquidityPoolId=wh,e.Memo=Wp,e.MemoHash=Gp,e.MemoID=zp,e.MemoNone=Hp,e.MemoReturn=jp,e.MemoText=$p,e.MuxedAccount=Qp,e.NetworkError=Au,e.Networks=vf,e.NotFoundError=Su,e.Operation=Vp,e.ScInt=uf,e.SignerKey=tf,e.Soroban=Af,e.SorobanDataBuilder=ef,e.StellarBase=Lf,e.StellarToml=Ju,e.StrKey=ih,e.TimeoutInfinite=0,e.Transaction=Zp,e.TransactionBase=gh,e.TransactionBuilder=yf,e.Uint128=rf,e.Uint256=of,e.UnsignedHyper=el.UnsignedHyper,e.Utils=xu,e.WebAuth=Jf,e.XdrLargeInt=cf,e.authorizeEntry=_f,e.authorizeInvocation=kf,e.buildAuthorizationEntryPreimage=Cf,e.buildInvocationTree=Bf,e.buildWithDelegatesEntry=Rf,e.cereal=nl,e.contract=fy,e.decodeAddressToMuxedAccount=bh,e.encodeMuxedAccount=Ah,e.encodeMuxedAccountToAddress=vh,e.extractBaseAddress=Sh,e.getLiquidityPoolId=fh,e.hash=$l,e.httpClient=bu,e.humanizeEvents=Tf,e.nativeToScVal=df,e.rpc=Im,e.scValToBigInt=lf,e.scValToNative=hf,e.scvSortedMap=pf,e.sign=Kd,e.verify=Xd,e.walkInvocationTree=Of,e.xdr=tl});
|
|
198
|
+
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const Gl=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:jl,n:Wl,Gx:Zl,Gy:Kl,a:Xl,d:Yl,h:Jl}=Gl,Ql=32,ed=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,ed),t},td=(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 i=e?.length,s=void 0!==t;if(!r||s&&i!==t){const o=(n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e);throw r?new RangeError(o):new TypeError(o)}return e},nd=e=>new Uint8Array(e),rd=e=>Uint8Array.from(e),od=(e,t)=>e.toString(16).padStart(t,"0"),id=e=>Array.from(td(e)).map(e=>od(e,2)).join(""),sd=48,ad=57,cd=65,ud=70,ld=97,dd=102,hd=e=>e>=sd&&e<=ad?e-sd:e>=cd&&e<=ud?e-(cd-10):e>=ld&&e<=dd?e-(ld-10):void 0,pd=e=>{const t="hex invalid";if("string"!=typeof e)return ed(t);const n=e.length,r=n/2;if(n%2)return ed(t);const o=nd(r);for(let n=0,i=0;n<r;n++,i+=2){const r=hd(e.charCodeAt(i)),s=hd(e.charCodeAt(i+1));if(void 0===r||void 0===s)return ed(t);o[n]=16*r+s}return o},fd=()=>globalThis?.crypto,gd=(...e)=>{let t=0;for(const n of e)t+=td(n).length;const n=nd(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n},md=BigInt,yd=(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)},wd=(e,t=jl)=>{const n=e%t;return n>=0n?n:t+n},bd=(1n<<255n)-1n,vd=e=>{e<0n&&ed("negative coordinate");let t=19n*(e>>255n)+(e&bd);return t=19n*(t>>255n)+(t&bd),t%jl},Ad=e=>wd(e,Wl),Sd=e=>{const t=Hd[e];return"function"!=typeof t&&ed("hashes."+e+" not set"),t},Td=e=>td(e,64,"digest"),Ed=e=>e instanceof kd?e:ed("Point expected"),_d=2n**256n;class kd{static BASE;static ZERO;X;Y;Z;T;constructor(e,t,n,r){const o=_d;this.X=yd(e,0n,o),this.Y=yd(t,0n,o),this.Z=yd(n,1n,o),this.T=yd(r,0n,o),Object.freeze(this)}static CURVE(){return Gl}static fromAffine(e){return new kd(e.x,e.y,1n,vd(e.x*e.y))}static fromBytes(e,t=!1){const n=Yl,r=rd(td(e,Ql)),o=e[31];r[31]=-129&o;const i=Id(r);yd(i,0n,t?_d:jl);const s=vd(i*i),a=wd(s-1n),c=vd(n*s+1n);let{isValid:u,value:l}=Pd(a,c);u||ed("bad point: y not sqrt");const d=1n==(1n&l),h=!!(128&o);return!t&&0n===l&&h&&ed("bad point: x==0, isLastByteOdd"),h!==d&&(l=wd(-l)),new kd(l,i,1n,vd(l*i))}static fromHex(e,t){return kd.fromBytes(pd(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const e=Xl,t=Yl;if(this.is0())return ed("bad point: ZERO");const{X:n,Y:r,Z:o,T:i}=this,s=vd(n*n),a=vd(r*r),c=vd(o*o),u=vd(c*c),l=vd(s*e);if(vd(c*(l+a))!==wd(u+vd(t*vd(s*a))))return ed("bad point: equation left != right (1)");return vd(n*r)!==vd(o*i)?ed("bad point: equation left != right (2)"):this}equals(e){const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=Ed(e),a=vd(t*s),c=vd(o*r),u=vd(n*s),l=vd(i*r);return a===c&&u===l}is0(){return this.equals(Rd)}negate(){return new kd(wd(-this.X),this.Y,this.Z,wd(-this.T))}double(){const{X:e,Y:t,Z:n}=this,r=Xl,o=vd(e*e),i=vd(t*t),s=vd(2n*n*n),a=vd(r*o),c=wd(e+t),u=wd(vd(c*c)-o-i),l=wd(a+i),d=wd(l-s),h=wd(a-i),p=vd(u*d),f=vd(l*h),g=vd(u*h),m=vd(d*l);return new kd(p,f,m,g)}add(e){const{X:t,Y:n,Z:r,T:o}=this,{X:i,Y:s,Z:a,T:c}=Ed(e),u=Xl,l=Yl,d=vd(t*i),h=vd(n*s),p=vd(vd(o*l)*c),f=vd(r*a),g=wd(vd(wd(t+n)*wd(i+s))-d-h),m=wd(f-p),y=wd(f+p),w=wd(h-vd(u*d)),b=vd(g*m),v=vd(y*w),A=vd(g*w),S=vd(m*y);return new kd(b,v,S,A)}subtract(e){return this.add(Ed(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return Rd;if(yd(e,1n,Wl),!t&&this.is0())return Rd;if(1n===e)return this;if(this.equals(Cd))return Wd(e).p;let n=Rd,r=Cd;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(Rd))return{x:0n,y:1n};const r=((e,t)=>{(0n===e||t<=0n)&&ed("no inverse n="+e+" mod="+t);let n=wd(e,t),r=t,o=0n,i=1n;for(;0n!==n;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}return 1n===r?wd(o,t):ed("no inverse")})(n,jl);1n!==vd(n*r)&&ed("invalid inverse");return{x:vd(e*r),y:vd(t*r)}}toBytes(){const{x:e,y:t}=this.toAffine(),n=xd(t);return n[31]|=1n&e?128:0,n}toHex(){return id(this.toBytes())}clearCofactor(){return this.multiply(md(Jl),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.multiply(Wl/2n,!1).double();return Wl%2n&&(e=e.add(this)),e.is0()}}const Cd=new kd(Zl,Kl,1n,wd(Zl*Kl)),Rd=new kd(0n,1n,1n,0n);kd.BASE=Cd,kd.ZERO=Rd;const xd=e=>pd(od(yd(e,0n,_d),64)).reverse(),Id=e=>md("0x"+id(rd(td(e)).reverse())),Bd=(e,t)=>{let n=e;for(;t-- >0n;)n=vd(n*n);return n},Od=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Pd=(e,t)=>{const n=vd(t*vd(t*t)),r=vd(vd(n*n)*t),o=(e=>{const t=vd(e*e),n=vd(t*e),r=vd(Bd(n,2n)*n),o=vd(Bd(r,1n)*e),i=vd(Bd(o,5n)*o),s=vd(Bd(i,10n)*i),a=vd(Bd(s,20n)*s),c=vd(Bd(a,40n)*a),u=vd(Bd(c,80n)*c),l=vd(Bd(u,80n)*c),d=vd(Bd(l,10n)*i);return{pow_p_5_8:vd(Bd(d,2n)*e),b2:n}})(vd(e*r)).pow_p_5_8;let i=vd(e*vd(n*o));const s=vd(t*vd(i*i)),a=i,c=vd(i*Od),u=s===e,l=s===wd(-e),d=s===wd(-e*Od);return u&&(i=a),(l||d)&&(i=c),1n==(1n&wd(i))&&(i=wd(-i)),{isValid:u||l,value:i}},Ld=e=>Ad(Id(e)),Ud=(...e)=>Td(Sd("sha512")(gd(...e))),Nd=e=>{const t=rd(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;const r=t.slice(32,64),o=Ld(n),i=Cd.multiply(o),s=i.toBytes();return{head:n,prefix:r,scalar:o,point:i,pointBytes:s}},Fd=e=>Nd(Ud(td(e,Ql))),Dd=e=>e.finish(Ud(e.hashable)),Md=(e,t)=>{const n=td(e),r=Fd(t),o=Ud(r.prefix,n);return Dd(((e,t,n)=>{const{pointBytes:r,scalar:o}=e,i=Ld(t),s=Cd.multiply(i).toBytes();return{hashable:gd(s,r,n),finish:e=>{const t=Ad(i+Ld(e)*o);return td(gd(s,xd(t)),64)}}})(r,o,n))},Vd={zip215:!0},qd=(e,t,n,r=Vd)=>Dd(((e,t,n,r=Vd)=>{e=td(e,64),t=td(t),n=td(n,Ql);const{zip215:o=!0}=r,i=e.subarray(0,Ql),s=Id(e.subarray(Ql,64));let a,c,u,l=Uint8Array.of(),d=!1;try{a=kd.fromBytes(n,o),c=kd.fromBytes(i,o),u=Cd.multiply(s,!1),l=gd(i,n,t),d=!0}catch(e){}return{hashable:l,finish:e=>{if(!d)return!1;if(!o&&a.isSmallOrder())return!1;const t=Ld(e);return c.add(a.multiply(t,!1)).subtract(u).clearCofactor().is0()}}})(e,t,n,r)),Hd={sha512Async:async e=>{const t=fd()?.subtle??ed("crypto.subtle must be defined, consider polyfill"),n=gd(e);return nd(await t.digest("SHA-512",n.buffer))},sha512:void 0},zd=Object.freeze({getExtendedPublicKeyAsync:e=>((...e)=>Promise.resolve(Sd("sha512Async")(gd(...e))).then(Td))(td(e,Ql)).then(Nd),getExtendedPublicKey:Fd,randomSecretKey:e=>(e=void 0===e?((e=Ql)=>fd().getRandomValues(nd(e)))(Ql):e,td(e,Ql))}),$d=Math.ceil(32)+1;let Gd;const jd=(e,t)=>{const n=t.negate();return e?n:t},Wd=e=>{const t=Gd||(Gd=(()=>{const e=[];let t=Cd,n=t;for(let r=0;r<$d;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=Rd,r=Cd;const o=md(255),i=md(8);for(let s=0;s<$d;s++){let a=Number(e&o);e>>=i,a>128&&(a-=256,e+=1n);const c=128*s,u=c,l=c+Math.abs(a)-1,d=s%2!=0,h=a<0;0===a?r=r.add(jd(d,t[u])):n=n.add(jd(h,t[l]))}return 0n!==e&&ed("invalid wnaf"),{p:n,f:r}};function Zd(e){return oo.Buffer.from(Fd(e).pointBytes)}function Kd(e,t){return oo.Buffer.from(Md(oo.Buffer.from(e),t))}function Xd(e,t,n){return qd(oo.Buffer.from(t),oo.Buffer.from(e),oo.Buffer.from(n),{zip215:!1})}Hd.sha512=zl;const Yd=(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 Jd,Qd={};var eh=(Jd||(Jd=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 i(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 s(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),i.prototype.charmap=n.charmap,i.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 i=255&t[e];(r-=5)>0?o|=i<<r:r<0?(n.push(o|i>>-r),o=i<<(r+=8)&255):(n.push(o|i),r=8,o=0)}}),this.shift=r,this.carry=o,this},i.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},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,n,r,o=this.shift,i=this.carry;for(r=0;r<e.length;r++)t=i|(n=e[r])>>o,this.buf+=this.alphabet[31&t],o>5&&(t=n>>(o-=5),this.buf+=this.alphabet[31&t]),i=n<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.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 s(t).finalize(e)},e.decode=function(e,t){return new i(t).finalize(e)},e.Decoder=i,e.Encoder=s,e.charmap=t,e.crockford=r,e.rfc4648=n,e.base32hex=o}(Qd)),Qd),th=Bt(eh);const nh={ed25519PublicKey:48,ed25519SecretSeed:144,med25519PublicKey:96,preAuthTx:152,sha256Hash:184,signedPayload:120,contract:16,liquidityPool:88,claimableBalance:8},rh={G:"ed25519PublicKey",S:"ed25519SecretSeed",M:"med25519PublicKey",T:"preAuthTx",X:"sha256Hash",P:"signedPayload",C:"contract",L:"liquidityPool",B:"claimableBalance"};function oh(e){return Object.prototype.hasOwnProperty.call(nh,e)}class ih{static types=rh;static encodeEd25519PublicKey(e){return ch("ed25519PublicKey",e)}static decodeEd25519PublicKey(e){return ah("ed25519PublicKey",e)}static isValidEd25519PublicKey(e){return sh("ed25519PublicKey",e)}static encodeEd25519SecretSeed(e){return ch("ed25519SecretSeed",e)}static decodeEd25519SecretSeed(e){return ah("ed25519SecretSeed",e)}static isValidEd25519SecretSeed(e){return sh("ed25519SecretSeed",e)}static encodeMed25519PublicKey(e){return ch("med25519PublicKey",e)}static decodeMed25519PublicKey(e){return ah("med25519PublicKey",e)}static isValidMed25519PublicKey(e){return sh("med25519PublicKey",e)}static encodePreAuthTx(e){return ch("preAuthTx",e)}static decodePreAuthTx(e){return ah("preAuthTx",e)}static encodeSha256Hash(e){return ch("sha256Hash",e)}static decodeSha256Hash(e){return ah("sha256Hash",e)}static encodeSignedPayload(e){return ch("signedPayload",e)}static decodeSignedPayload(e){return ah("signedPayload",e)}static isValidSignedPayload(e){return sh("signedPayload",e)}static encodeContract(e){return ch("contract",e)}static decodeContract(e){return ah("contract",e)}static isValidContract(e){return sh("contract",e)}static encodeClaimableBalance(e){return ch("claimableBalance",e)}static decodeClaimableBalance(e){return ah("claimableBalance",e)}static isValidClaimableBalance(e){return sh("claimableBalance",e)}static encodeLiquidityPool(e){return ch("liquidityPool",e)}static decodeLiquidityPool(e){return ah("liquidityPool",e)}static isValidLiquidityPool(e){return sh("liquidityPool",e)}static getVersionByteForPrefix(e){if(e.length<1)return;const t=e[0];return rh[t]}}function sh(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=ah(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 ah(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");const n=th.decode(t),r=n[0],o=n.slice(0,-2),i=o.slice(1),s=n.slice(-2);if(t!==th.encode(n))throw new Error("invalid encoded string");if(!oh(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(nh).join(", ")}`);const a=nh[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}(uh(o),s))throw new Error("invalid checksum");return oo.Buffer.from(i)}function ch(e,t){if(null==t)throw new Error("cannot encode null data");if(!oh(e))throw new Error(`${e} is not a valid version byte name. Expected one of ${Object.keys(nh).join(", ")}`);const n=nh[e];t=oo.Buffer.from(t);const r=oo.Buffer.from([n]),o=oo.Buffer.concat([r,t]),i=oo.Buffer.from(uh(o)),s=oo.Buffer.concat([o,i]);return th.encode(s)}function uh(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}Hd.sha512=zl;class lh{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=oo.Buffer.from(e.secretKey),32!==e.secretKey.length)throw new Error("secretKey length is invalid");if(this._secretSeed=e.secretKey,this._publicKey=Zd(e.secretKey),this._secretKey=e.secretKey,e.publicKey&&!this._publicKey.equals(oo.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=oo.Buffer.from(e.publicKey),32!==this._publicKey.length)throw new Error("publicKey length is invalid")}}static fromSecret(e){const t=ih.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($l(e))}static fromPublicKey(e){const t=ih.decodeEd25519PublicKey(e);if(32!==t.length)throw new Error("Invalid Stellar public key");return new this({type:"ed25519",publicKey:t})}static random(){const e=zd.randomSecretKey();return this.fromRawEd25519Seed(oo.Buffer.from(e))}xdrAccountId(){return tl.PublicKey.publicKeyTypeEd25519(this._publicKey)}xdrPublicKey(){return tl.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 tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromString(e),ed25519:this._publicKey}))}return tl.MuxedAccount.keyTypeEd25519(this._publicKey)}rawPublicKey(){return this._publicKey}signatureHint(){const e=this.xdrAccountId().toXDR();return e.subarray(e.length-4)}publicKey(){return ih.encodeEd25519PublicKey(this._publicKey)}secret(){if(!this._secretSeed)throw new Error("no secret key available");if("ed25519"===this.type)return ih.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 Kd(e,this._secretKey)}verify(e,t){try{return Xd(e,t,this._publicKey)}catch{return!1}}signDecorated(e){const t=this.sign(e),n=this.signatureHint();return new tl.DecoratedSignature({hint:n,signature:t})}signPayloadDecorated(e){const t=oo.Buffer.isBuffer(e)?e:oo.Buffer.from(e),n=this.sign(t),r=this.signatureHint();let o=oo.Buffer.from(t.subarray(-4));o.length<4&&(o=oo.Buffer.concat([o,oo.Buffer.alloc(4-o.length,0)]));for(let e=0;e<o.length;e++)o[e]=o[e]^r[e];return new tl.DecoratedSignature({hint:o,signature:n})}}const dh={native:"native",credit4:"credit_alphanum4",credit12:"credit_alphanum12",liquidityPoolShares:"liquidity_pool_shares"};function hh(e,t){return oo.Buffer.compare(oo.Buffer.from(e,"ascii"),oo.Buffer.from(t,"ascii"))}class ph{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&&!ih.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 ph("XLM")}static fromOperation(e){let t,n,r;switch(e.switch()){case tl.AssetType.assetTypeNative():return this.native();case tl.AssetType.assetTypeCreditAlphanum4():return t=e.alphaNum4(),r=ih.encodeEd25519PublicKey(t.issuer().ed25519()),n=Yd(t.assetCode().toString(),"\0"),new this(n,r);case tl.AssetType.assetTypeCreditAlphanum12():return t=e.alphaNum12(),r=ih.encodeEd25519PublicKey(t.issuer().ed25519()),n=Yd(t.assetCode().toString(),"\0"),new this(n,r);default:throw new Error(`Invalid asset type: ${e.switch().name}`)}}toXDRObject(){return this._toXDRObject(tl.Asset)}toChangeTrustXDRObject(){return this._toXDRObject(tl.ChangeTrustAsset)}toTrustLineXDRObject(){return this._toXDRObject(tl.TrustLineAsset)}contractId(e){const t=$l(oo.Buffer.from(e)),n=tl.HashIdPreimage.envelopeTypeContractId(new tl.HashIdPreimageContractId({networkId:t,contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject())}));return ih.encodeContract($l(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=tl.AlphaNum4,n="assetTypeCreditAlphanum4"):(t=tl.AlphaNum12,n="assetTypeCreditAlphanum12");const r=this.code.length<=4?4:12;return new e(n,new t({assetCode:this.code.padEnd(r,"\0"),issuer:lh.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 tl.AssetType.assetTypeNative().value:return dh.native;case tl.AssetType.assetTypeCreditAlphanum4().value:return dh.credit4;case tl.AssetType.assetTypeCreditAlphanum12().value:return dh.credit12;default:throw new Error("Supported asset types are: native, credit_alphanum4, credit_alphanum12")}}getRawAssetType(){return this.isNative()?tl.AssetType.assetTypeNative():this.code.length<=4?tl.AssetType.assetTypeCreditAlphanum4():tl.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 ph))throw new Error("assetA is invalid");if(!(t&&t instanceof ph))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=hh(e.getCode(),t.getCode());if(0!==o)return o;const i=e.getIssuer(),s=t.getIssuer();if(void 0===i||void 0===s)throw new Error("Issuer is undefined for non-native asset");return hh(i,s)}}function fh(e,t){if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");const{assetA:n,assetB:r,fee:o}=t??{};if(!(n&&n instanceof ph))throw new Error("assetA is invalid");if(!(r&&r instanceof ph))throw new Error("assetB is invalid");if(!o||30!==o)throw new Error("fee is invalid");if(-1!==ph.compare(n,r))throw new Error("Assets are not in lexicographic order");return $l(tl.LiquidityPoolParameters.liquidityPoolConstantProduct(new tl.LiquidityPoolConstantProductParameters({assetA:n.toXDRObject(),assetB:r.toXDRObject(),fee:o})).toXDR())}class gh{_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 tl.Transaction)return tl.Transaction.fromXDR(e);if(this._tx instanceof tl.TransactionV0)return tl.TransactionV0.fromXDR(e);if(this._tx instanceof tl.FeeBumpTransaction)return tl.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=oo.Buffer.from(t,"base64");try{n=lh.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 tl.DecoratedSignature({hint:r,signature:o}))}addDecoratedSignature(e){this.signatures.push(e)}signHashX(e){if("string"==typeof e&&(e=oo.Buffer.from(e,"hex")),e.length>64)throw new Error("preimage cannot be longer than 64 bytes");const t=e,n=$l(e),r=n.subarray(n.length-4);this.signatures.push(new tl.DecoratedSignature({hint:r,signature:t}))}hash(){return $l(this.signatureBase())}signatureBase(){throw new Error("Implement in subclass")}toEnvelope(){throw new Error("Implement in subclass")}toXDR(){return this.toEnvelope().toXDR().toString("base64")}}class mh{assetA;assetB;fee;constructor(e,t,n){if(!(e&&e instanceof ph))throw new Error("assetA is invalid");if(!(t&&t instanceof ph))throw new Error("assetB is invalid");if(-1!==ph.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===tl.AssetType.assetTypePoolShare()){const t=e.liquidityPool().constantProduct();return new this(ph.fromOperation(t.assetA()),ph.fromOperation(t.assetB()),t.fee())}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=new tl.LiquidityPoolConstantProductParameters({assetA:this.assetA.toXDRObject(),assetB:this.assetB.toXDRObject(),fee:this.fee}),t=tl.LiquidityPoolParameters.liquidityPoolConstantProduct(e);return tl.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:${fh("constant_product",this.getLiquidityPoolParameters()).toString("hex")}`}}class yh{_destination;_predicate;constructor(e,t){if(!ih.isValidEd25519PublicKey(e))throw new Error("Destination is invalid");if(this._destination=e,t){if(!(t instanceof tl.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");this._predicate=t}else this._predicate=tl.ClaimPredicate.claimPredicateUnconditional()}static predicateUnconditional(){return tl.ClaimPredicate.claimPredicateUnconditional()}static predicateAnd(e,t){if(!(e instanceof tl.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof tl.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateAnd([e,t])}static predicateOr(e,t){if(!(e instanceof tl.ClaimPredicate))throw new Error("left Predicate should be an xdr.ClaimPredicate");if(!(t instanceof tl.ClaimPredicate))throw new Error("right Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateOr([e,t])}static predicateNot(e){if(!(e instanceof tl.ClaimPredicate))throw new Error("Predicate should be an xdr.ClaimPredicate");return tl.ClaimPredicate.claimPredicateNot(e)}static predicateBeforeAbsoluteTime(e){return tl.ClaimPredicate.claimPredicateBeforeAbsoluteTime(tl.Int64.fromString(e))}static predicateBeforeRelativeTime(e){return tl.ClaimPredicate.claimPredicateBeforeRelativeTime(tl.Int64.fromString(e))}static fromXDR(e){let t;if(e.switch()===tl.ClaimantType.claimantTypeV0())return t=e.v0(),new this(ih.encodeEd25519PublicKey(t.destination().ed25519()),t.predicate());throw new Error(`Invalid claimant type: ${e.switch().name}`)}toXDRObject(){const e=new tl.ClaimantV0({destination:lh.fromPublicKey(this._destination).xdrAccountId(),predicate:this._predicate});return tl.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 wh{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===tl.AssetType.assetTypePoolShare()){const t=e.liquidityPoolId().toString("hex");return new wh(t)}throw new Error(`Invalid asset type: ${t.name}`)}toXDRObject(){const e=oo.Buffer.from(this.liquidityPoolId,"hex");return tl.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 bh(e){return ih.isValidMed25519PublicKey(e)?function(e){const t=ih.decodeMed25519PublicKey(e);return tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):tl.MuxedAccount.keyTypeEd25519(ih.decodeEd25519PublicKey(e))}function vh(e){return e.switch().value===tl.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===tl.CryptoKeyType.keyTypeEd25519())return vh(e);const t=e.med25519();return ih.encodeMed25519PublicKey(oo.Buffer.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):ih.encodeEd25519PublicKey(e.ed25519())}function Ah(e,t){if(!ih.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 tl.MuxedAccount.keyTypeMuxedEd25519(new tl.MuxedAccountMed25519({id:tl.Uint64.fromString(t),ed25519:ih.decodeEd25519PublicKey(e)}))}function Sh(e){if(ih.isValidEd25519PublicKey(e))return e;if(!ih.isValidMed25519PublicKey(e))throw new TypeError(`expected muxed account (M...), got ${e}`);const t=bh(e);return ih.encodeEd25519PublicKey(t.med25519().ed25519())}var Th=function e(t){var n,r,o=/^(-?)0([xbo])(?=[^.])/i,i=/^-?(Infinity|NaN)$/,s=/^\s*\+(?!-)|^\s+|\s+$/g,a=A.prototype={constructor:A,toString:null,valueOf:null},c=new A(1),u=20,l=4,d=-7,h=21,p=-1e7,f=1e7,g=!1,m=!0,y=1,w=0,b={prefix:"",negativeSign:"-",positiveSign:"",groupSeparator:",",groupSize:3,secondaryGroupSize:0,decimalSeparator:".",fractionGroupSeparator:"",fractionGroupSize:0,suffix:""},v="0123456789abcdefghijklmnopqrstuvwxyz";function A(e,t){var n,r,a,c,u=this;if(!(u instanceof A))return new A(e,t);if(c=typeof e,null==t){if(_(e))return u.s=e.s,void(!e.c||e.e>f?u.c=u.e=null:e.e<p?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 S(u,String(e))}if("bigint"==c)return u.s=e<0?(e=-e,-1):1,S(u,String(e));if("string"==c)a=e;else{if(m)throw Error(Ch+"BigNumber, string, number, or BigInt expected: "+e);a=String(e)}if(Eh.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,S(u,a);if(a=a.replace(s,""),i.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"),Eh.test(a))return u.s=45==a.charCodeAt(0)?(a=a.slice(1),-1):1,S(u,a);if(m)throw Error(Ch+"Not a number: "+e);u.s=u.c=u.e=null}else{if("string"!=c){if(m)throw Error(Ch+"String expected: "+e);e=String(e)}Fh(t,2,v.length,"Base"),T(u,e.replace(s,""),t,e)}}function S(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<p)e.c=[e.e=0];else{if(e.e=n,e.c=[],r=(n+1)%xh,n<0&&(r+=xh),r<o){for(r&&e.c.push(+t.slice(0,r)),o-=xh;r<o;)e.c.push(+t.slice(r,r+=xh));r=xh-(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 i,s,a=v.slice(0,n),c=0,u="",l=!1,d=!1,h=!1;for(e.s=45===t.charCodeAt(0)?(t=t.slice(1),-1):1,s=t.length;c<s;c++){if(i=t.charAt(c),!(a.indexOf(i)>=0)){if("_"==i){if(d&&c+1<s){d=!1;continue}}else if("."==i){if(0==c||!l&&d){if(c+1==s)break;0==c&&(u="0"),u+=i,l=!0,d=!1;continue}}else if(!h&&(t==t.toUpperCase()&&a==a.toLowerCase()&&(t=t.toLowerCase())||t==t.toLowerCase()&&a==a.toUpperCase()&&(t=t.toUpperCase()))){c=-1,u="",h=!0,l=d=!1;continue}if(m)throw Error(Ch+"Not a base "+n+" number: "+o);return void(e.s=e.c=e.e=null)}u+=i,d=!0}S(e,r(u,n,10,e.s))}function E(e,t,n,r){var o,i,s,a,c;if(n=null==n?l:Fh(n,0,8),!e.c)return e.toString();if(o=e.c[0],s=e.e,null==t)c=Uh(e.c),c=1==r||2==r&&(s<=d||s>=h)?Vh(c,s):qh(c,s,"0");else if(i=(e=x(new A(e),t,n)).e,a=(c=Uh(e.c)).length,1==r||2==r&&(t<=i||i<=d)){for(;a<t;c+="0",a++);c=Vh(c,i)}else if(t-=s+(2===r&&i>s),c=qh(c,i,"0"),i+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=i-a)>0)for(i+1==a&&(c+=".");t--;c+="0");return e.s<0&&o?"-"+c:c}function _(e){return e instanceof A||!!e&&!0===e._isBigNumber}function k(e,t){for(var n,r,o=1,i=new A(e[0]);o<e.length;o++)(!(r=new A(e[o])).s||(n=Nh(i,r))===t||0===n&&i.s===t)&&(i=r);return i}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*xh-1)>f?e.c=e.e=null:n<p?e.c=[e.e=0]:(e.e=n,e.c=t),e}function R(e){var t,n={};for(t in b)b.hasOwnProperty(t)&&(n[t]=e.hasOwnProperty(t)?e[t]:b[t]);return n}function x(e,t,n,r){var o,i,s,a,c,u,l,d=e.c,h=Bh;if(d){e:{for(o=1,a=d[0];a>=10;a/=10,o++);if((i=t-o)<0)i+=xh,s=t,c=d[u=0],l=kh(c/h[o-s-1]%10);else if((u=_h((i+1)/xh))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,o=1,s=(i%=xh)-xh+1}else{for(c=a=d[u],o=1;a>=10;a/=10,o++);l=(s=(i%=xh)-xh+o)<0?0:kh(c/h[o-s-1]%10)}if(r=r||t<0||null!=d[u+1]||(s<0?c:c%h[o-s-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(i>0?s>0?c/h[o-s]: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]=h[(xh-t%xh)%xh],e.e=-t||0):d[0]=e.e=0,e;if(0==i?(d.length=u,a=1,u--):(d.length=u+1,a=h[xh-i],d[u]=s>0?kh(c/h[o-s]%h[s])*a:0),r)for(;;){if(0==u){for(i=1,s=d[0];s>=10;s/=10,i++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);i!=a&&(e.e++,d[0]==Rh&&(d[0]=1));break}if(d[u]+=a,d[u]!=Rh)break;d[u--]=0,a=1}for(i=d.length;0===d[--i];d.pop());}e.e>f?e.c=e.e=null:e.e<p&&(e.c=[e.e=0])}return e}function I(e){var t,n=e.e;return null===n?e.toString():(t=Uh(e.c),t=n<=d||n>=h?Vh(t,n):qh(t,n,"0"),e.s<0?"-"+t:t)}A.clone=e,A.ROUND_UP=0,A.ROUND_DOWN=1,A.ROUND_CEIL=2,A.ROUND_FLOOR=3,A.ROUND_HALF_UP=4,A.ROUND_HALF_DOWN=5,A.ROUND_HALF_EVEN=6,A.ROUND_HALF_CEIL=7,A.ROUND_HALF_FLOOR=8,A.EUCLID=9,A.config=A.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(Ch+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(u=Fh(e[t],0,Ph,t)),e.hasOwnProperty(t="ROUNDING_MODE")&&(l=Fh(e[t],0,8,t)),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(Dh(n=e[t])?(Fh(n[0],-Ph,0,t),Fh(n[1],0,Ph,t),d=n[0],h=n[1]):d=-(h=Fh(n,-Ph,Ph,t)<0?-n:n)),e.hasOwnProperty(t="RANGE")){if(!(n=e[t]))throw Error(Ch+t+" cannot be zero: "+n);Dh(n)?(Fh(n[0],-Ph,-1,t),Fh(n[1],1,Ph,t),p=n[0],f=n[1]):p=-(f=Fh(n,-Ph,Ph,t)<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(Ch+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw g=!n,Error(Ch+"crypto unavailable");g=n}else g=n}if(e.hasOwnProperty(t="STRICT")){if((n=e[t])!==!!n)throw Error(Ch+t+" not true or false: "+n);m=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(y=Fh(e[t],0,9,t)),e.hasOwnProperty(t="POW_PRECISION")&&(w=Fh(e[t],0,Ph,t)),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(Ch+t+" not an object: "+n);for(t in n)n.hasOwnProperty(t)&&b.hasOwnProperty(t)&&(b[t]=n[t])}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(Ch+t+" invalid: "+n);v=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,h],RANGE:[p,f],CRYPTO:g,STRICT:m,MODULO_MODE:y,POW_PRECISION:w,FORMAT:b,ALPHABET:v}},A.fromFormat=function(e,t){if("string"!=typeof e)throw Error(Ch+"Not a string: "+e);if(null==t)t=b;else{if("object"!=typeof t)throw Error(Ch+"Argument not an object: "+t);t=R(t)}var n,r,o,i,s=t.negativeSign||"-",a=t.positiveSign||"",c=t.prefix||"",u=t.suffix||"",l=t.groupSeparator||"",d=t.decimalSeparator||".",h=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(s)?(e=e.slice(s.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),i=e.slice(n+d.length),l)for(;o.indexOf(l)>-1;)o=o.replace(l,"");if(h)for(;i.indexOf(h)>-1;)i=i.replace(h,"");e=o+"."+i}return new A(r?"-"+e:e)},A.isBigNumber=function(e){if(!_(e))return!1;var t,n,r=e.c,o=e.e,i=e.s;if(!Dh(r))return null===r&&null===o&&(null===i||1===i||-1===i);if(1!==i&&-1!==i||o<-Ph||o>Ph||o!==kh(o))return!1;if(0===r[0])return 0===o&&1===r.length;if((t=(o+1)%xh)<1&&(t+=xh),String(r[0]).length!==t)return!1;for(t=0;t<r.length;t++)if((n=r[t])<0||n>=Rh||n!==kh(n))return!1;return 0!==n},A.maximum=A.max=function(){return k(arguments,-1)},A.minimum=A.min=function(){return k(arguments,1)},A.random=function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return kh(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var n,r,o,i,s,a=0,l=[],d=new A(c);if(e=null==e?u:Fh(e,0,Ph),i=_h(e/xh),g)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(i*=2));a<i;)(s=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(s%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw g=!1,Error(Ch+"crypto unavailable");for(n=crypto.randomBytes(i*=7);a<i;)(s=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(s%1e14),a+=7);a=i/7}if(!g)for(;a<i;)(s=t())<9e15&&(l[a++]=s%1e14);for(i=l[--a],e%=xh,i&&e&&(s=Bh[xh-e],l[a]=kh(i/s)*s);0===l[a];l.pop(),a--);if(a<0)l=[o=0];else{for(o=-1;0===l[0];l.splice(0,1),o-=xh);for(a=1,s=l[0];s>=10;s/=10,a++);a<xh&&(o-=xh-a)}return d.e=o,d.c=l,d}}(),A.sum=function(){for(var e=0,t=new A(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,i,s=[0],a=0,c=e.length;a<c;){for(i=s.length;i--;s[i]*=t);for(s[0]+=r.indexOf(e.charAt(a++)),o=0;o<s.length;o++)s[o]>n-1&&(null==s[o+1]&&(s[o+1]=0),s[o+1]+=s[o]/n|0,s[o]%=n)}return s.reverse()}return function(r,o,i,s,a){var c,d,h,p,f,g,m,y,b=r.indexOf("."),S=u,T=l;for(b>=0&&(p=w,w=0,r=r.replace(".",""),g=(y=new A(o)).pow(r.length-b),w=p,y.c=t(qh(Uh(g.c),g.e,"0"),10,i,e),y.e=y.c.length),h=p=(m=t(r,o,i,a?(c=v,e):(c=e,v))).length;0==m[--p];m.pop());if(!m[0])return c.charAt(0);if(b<0?--h:(g.c=m,g.e=h,g.s=s,m=(g=n(g,y,S,T,i)).c,f=g.r,h=g.e),b=m[d=h+S+1],p=i/2,f=f||d<0||null!=m[d+1],f=T<4?(null!=b||f)&&(0==T||T==(g.s<0?3:2)):b>p||b==p&&(4==T||f||6==T&&1&m[d-1]||T==(g.s<0?8:7)),d<1||!m[0])r=f?qh(c.charAt(1),-S,c.charAt(0)):c.charAt(0);else{if(d<m.length&&(m.length=d),f)for(--i;++m[--d]>i;)m[d]=0,d||(++h,m=[1].concat(m));for(p=m.length;!m[--p];);for(b=0,r="";b<=p;r+=c.charAt(m[b++]));r=qh(r,h,c.charAt(0))}return r}}(),n=function(){function e(e,t,n){var r,o,i,s,a=0,c=e.length,u=t%Oh,l=t/Oh|0;for(e=e.slice();c--;)a=((o=u*(i=e[c]%Oh)+(r=l*i+(s=e[c]/Oh|0)*u)%Oh*Oh+a)/n|0)+(r/Oh|0)+l*s,e[c]=o%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var o,i;if(n!=r)i=n>r?1:-1;else for(o=i=0;o<n;o++)if(e[o]!=t[o]){i=e[o]>t[o]?1:-1;break}return i}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,i,s,a){var c,u,l,d,h,p,f,g,m,y,w,b,v,S,T,E,_,k=r.s==o.s?1:-1,C=r.c,R=o.c;if(!(C&&C[0]&&R&&R[0]))return new A(r.s&&o.s&&(C?!R||C[0]!=R[0]:R)?C&&0==C[0]||!R?0*k:k/0:NaN);for(m=(g=new A(k)).c=[],k=i+(u=r.e-o.e)+1,a||(a=Rh,u=Lh(r.e/xh)-Lh(o.e/xh),k=k/xh|0),l=0;R[l]==(C[l]||0);l++);if(R[l]>(C[l]||0)&&u--,k<0)m.push(1),d=!0;else{for(S=C.length,E=R.length,l=0,k+=2,(h=kh(a/(R[0]+1)))>1&&(R=e(R,h,a),C=e(C,h,a),E=R.length,S=C.length),v=E,w=(y=C.slice(0,E)).length;w<E;y[w++]=0);_=R.slice(),_=[0].concat(_),T=R[0],R[1]>=a/2&&T++;do{if(h=0,(c=t(R,y,E,w))<0){if(b=y[0],E!=w&&(b=b*a+(y[1]||0)),(h=kh(b/T))>1)for(h>=a&&(h=a-1),f=(p=e(R,h,a)).length,w=y.length;1==t(p,y,f,w);)h--,n(p,E<f?_:R,f,a),f=p.length,c=1;else 0==h&&(c=h=1),f=(p=R.slice()).length;if(f<w&&(p=[0].concat(p)),n(y,p,w,a),w=y.length,-1==c)for(;t(R,y,E,w)<1;)h++,n(y,E<w?_:R,w,a),w=y.length}else 0===c&&(h++,y=[0]);m[l++]=h,y[0]?y[w++]=C[v]||0:(y=[C[v]],w=1)}while((v++<S||null!=y[0])&&k--);d=null!=y[0],m[0]||m.splice(0,1)}if(a==Rh){for(l=1,k=m[0];k>=10;k/=10,l++);x(g,i+(g.e=l+u*xh-1)+1,s,d)}else g.e=u,g.r=+d;return g}}(),a.absoluteValue=a.abs=function(){var e=new A(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return Nh(this,new A(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,o,i=this;if(null!=e)return x(new A(i),Fh(e,-Ph,Ph)+i.e+1,null==t?l:Fh(t,0,8));if(!(n=i.c))return null;if(r=((o=n.length-1)-Lh(this.e/xh))*xh,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 A(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new A(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,o,i,s,a,u,d,h=this;if((e=new A(e)).c&&!e.isInteger())throw Error(Ch+"Exponent not an integer: "+I(e));if(null!=t&&(t=new A(t)),s=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new A(Math.pow(+I(h),s?e.s*(2-Mh(e)):+I(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new A(NaN);(r=!a&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return i=h.s<0&&Mh(e)?-0:0,h.e>-1&&(i=1/i),new A(a?1/i:i);w&&(i=_h(w/xh+2))}for(s?(n=new A(.5),a&&(e.s=1),u=Mh(e)):u=(o=Math.abs(+I(e)))%2,d=new A(c);;){if(u){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):r&&(d=d.mod(t))}if(o){if(0===(o=kh(o/2)))break;u=o%2}else if(x(e=e.times(n),e.e+1,1),e.e>14)u=Mh(e);else{if(0===(o=+I(e)))break;u=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):r&&(h=h.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):i?x(d,w,l,void 0):d)},a.integerValue=function(e){var t=new A(this);return x(t,t.e+1,null==e?l:Fh(e,0,8))},a.isEqualTo=a.eq=function(e,t){return 0===Nh(this,new A(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return Nh(this,new A(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=Nh(this,new A(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Lh(this.e/xh)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return Nh(this,new A(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=Nh(this,new A(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,i,s=this,a=s.s;if(t=(e=new A(e,t)).s,!a||!t)return new A(NaN);if(a!=t)return e.s=-t,s.plus(e);var c=s.e/xh,u=e.e/xh,d=s.c,h=e.c;if(!c||!u){if(!d||!h)return d?(e.s=-t,e):new A(h?s:NaN);if(!d[0]||!h[0])return h[0]?(e.s=-t,e):new A(d[0]?s:3==l?-0:0)}if(c=Lh(c),u=Lh(u),d=d.slice(),a=c-u){for((i=a<0)?(a=-a,o=d):(u=c,o=h),o.reverse(),t=a;t--;o.push(0));o.reverse()}else for(r=(i=(a=d.length)<(t=h.length))?a:t,a=t=0;t<r;t++)if(d[t]!=h[t]){i=d[t]<h[t];break}if(i&&(o=d,d=h,h=o,e.s=-e.s),(t=(r=h.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=Rh-1;r>a;){if(d[--r]<h[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=Rh}d[r]-=h[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,i=this;return e=new A(e,t),!i.c||!e.s||e.c&&!e.c[0]?new A(NaN):!e.c||i.c&&!i.c[0]?new A(i):(9==y?(o=e.s,e.s=1,r=n(i,e,0,3),e.s=o,r.s*=o):r=n(i,e,0,y),(e=i.minus(r.times(e))).c[0]||1!=y||(e.s=i.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,o,i,s,a,c,u,l,d,h,p,f,g,m,y=this,w=y.c,b=(e=new A(e,t)).c;if(!(w&&b&&w[0]&&b[0]))return!y.s||!e.s||w&&!w[0]&&!b||b&&!b[0]&&!w?e.c=e.e=e.s=null:(e.s*=y.s,w&&b?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Lh(y.e/xh)+Lh(e.e/xh),e.s*=y.s,(c=w.length)<(d=b.length)&&(f=w,w=b,b=f,o=c,c=d,d=o),o=c+d,f=[];o--;f.push(0));for(g=Rh,m=Oh,o=d;--o>=0;){for(n=0,h=b[o]%m,p=b[o]/m|0,i=o+(s=c);i>o;)n=((u=h*(u=w[--s]%m)+(a=p*u+(l=w[s]/m|0)*h)%m*m+f[i]+n)/g|0)+(a/m|0)+p*l,f[i--]=u%g;f[i]=n}return n?++r:f.splice(0,1),C(e,f,r)},a.negated=function(){var e=new A(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,o=r.s;if(t=(e=new A(e,t)).s,!o||!t)return new A(NaN);if(o!=t)return e.s=-t,r.minus(e);var i=r.e/xh,s=e.e/xh,a=r.c,c=e.c;if(!i||!s){if(!a||!c)return new A(o/0);if(!a[0]||!c[0])return c[0]?e:new A(a[0]?r:0*o)}if(i=Lh(i),s=Lh(s),a=a.slice(),o=i-s){for(o>0?(s=i,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)/Rh|0,a[t]=Rh===a[t]?0:a[t]%Rh;return o&&(a=[o].concat(a),++s),C(e,a,s)},a.precision=a.sd=function(e,t){var n,r,o,i=this;if(null!=e&&e!==!!e)return x(new A(i),Fh(e,1,Ph),null==t?l:Fh(t,0,8));if(!(n=i.c))return null;if(r=(o=n.length-1)*xh+1,o=n[o]){for(;o%10==0;o/=10,r--);for(o=n[0];o>=10;o/=10,r++);}return e&&i.e+1>r&&(r=i.e+1),r},a.shiftedBy=function(e){return this.times("1e"+Fh(e,-Ih,Ih))},a.squareRoot=a.sqrt=function(){var e,t,r,o,i,s=this,a=s.c,c=s.s,d=s.e,h=u+4,p=new A("0.5");if(1!==c||!a||!a[0])return new A(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(c=Math.sqrt(+I(s)))||c==1/0?(((t=Uh(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Lh((d+1)/2)-(d<0||d%2),r=new A(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new A(c+""),r.c[0])for((c=(d=r.e)+h)<3&&(c=0);;)if(i=r,r=p.times(i.plus(n(s,i,h,1))),Uh(i.c).slice(0,c)===(t=Uh(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(s));break}if(!o&&(x(i,i.e+u+2,0),i.times(i).eq(s))){r=i;break}h+=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:Fh(e,0,Ph)+1,t,1)},a.toFixed=function(e,t){return E(this,null==e?e:Fh(e,-Ph,Ph)+this.e+1,t)},a.toFormat=function(e,t,n){var r,o,i,s=this;if(null==n)n=b,null!=e&&(null!=t?"object"==typeof t&&(n=R(t),t=null):"object"!=typeof e||Dh(e)||(n=R(e),e=t=null));else{if("object"!=typeof n)throw Error(Ch+"Argument not an object: "+n);n=R(n)}if(null!=e)if(Dh(e)&&e.length<=2){if(r=e[0],o=e[1],e=s.dp(),null!=o&&e>Fh(o,0,Ph)&&(e=o),null!=r&&0!==Fh(r,0,Ph)){if(null!=o&&r>o)throw Error(Ch+"Minimum must not exceed maximum");e<r&&(e=r)}}else Fh(e,-Ph,Ph);if(i=s.toFixed(e,t),s.s<0&&(i=i.slice(1)),s.c){var a,c=i.split("."),u=+n.groupSize,l=+n.secondaryGroupSize,d=n.groupSeparator||"",h=c[0],p=c[1],f=h.length;if(l&&(a=u,u=l,l=a,f-=a),u>0&&f>0){for(a=f%u||u,i=h.substr(0,a);a<f;a+=u)i+=d+h.substr(a,u);l>0&&(i+=d+h.slice(a))}p&&((a=+n.fractionGroupSize)&&(p=p.replace(new RegExp("\\d{"+a+"}\\B","g"),"$&"+(n.fractionGroupSeparator||""))),i+=(n.decimalSeparator||"")+p)}return(n.prefix||"")+(s.s<0?n.negativeSign||"":s.s>0&&n.positiveSign||"")+i+(n.suffix||"")},a.toFraction=function(e){var t,r,o,i,s,a,u,d,h,p,g,m,y=this,w=y.c;if(null!=e&&(!(u=new A(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(Ch+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+I(u));if(!w)return[new A(y.s||0),new A(0)];for(t=new A(c),h=r=new A(c),o=d=new A(c),m=Uh(w),s=t.e=m.length-y.e-1,t.c[0]=Bh[(a=s%xh)<0?xh+a:a],e=!e||u.comparedTo(t)>0?s>0?t:h:u,a=f,f=1/0,u=new A(m),d.c[0]=0;p=n(u,t,0,1),1!=(i=r.plus(p.times(o))).comparedTo(e);)r=o,o=i,h=d.plus(p.times(i=h)),d=i,t=u.minus(p.times(i=t)),u=i;return i=n(e.minus(r),o,0,1),d=d.plus(i.times(h)),r=r.plus(i.times(o)),d.s=h.s=y.s,g=n(h,o,s*=2,l).minus(y).abs().comparedTo(n(d,r,s,l).minus(y).abs())<1?[h,o]:[d,r],f=a,g},a.toNumber=function(){return+I(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:Fh(e,1,Ph),t,2)},a.toString=function(e){var t,n=this,o=n.s,i=n.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=d||i>=h?Vh(Uh(n.c),i):qh(Uh(n.c),i,"0"):(Fh(e,2,v.length,"Base"),t=r(qh(Uh(n.c),i,"0"),10,e,o,!0)),o<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return I(this)},a._isBigNumber=!0,null!=t&&A.set(t);return A}(),Eh=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,_h=Math.ceil,kh=Math.floor,Ch="[BigNumber Error] ",Rh=1e14,xh=14,Ih=9007199254740991,Bh=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Oh=1e7,Ph=1e9;function Lh(e){var t=0|e;return e>0||e===t?t:t-1}function Uh(e){for(var t,n,r=1,o=e.length,i=e[0]+"";r<o;){for(t=e[r++]+"",n=xh-t.length;n--;t="0"+t);i+=t}for(o=i.length;48===i.charCodeAt(--o););return i.slice(0,o+1||1)}function Nh(e,t){var n,r,o=e.c,i=t.c,s=e.s,a=t.s,c=e.e,u=t.e;if(!s||!a)return null;if(n=o&&!o[0],r=i&&!i[0],n||r)return n?r?0:-a:s;if(s!=a)return s;if(n=s<0,r=c==u,!o||!i)return r?0:!o^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=o.length)<(u=i.length)?c:u,s=0;s<a;s++)if(o[s]!=i[s])return o[s]>i[s]^n?1:-1;return c==u?0:c>u^n?1:-1}function Fh(e,t,n,r){if(e<t||e>n||e!==kh(e))throw Error(Ch+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e));return e}function Dh(e){return"[object Array]"=={}.toString.call(e)}function Mh(e){var t=e.c.length-1;return Lh(e.e/xh)==t&&e.c[t]%2!=0}function Vh(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function qh(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 Hh=Th.clone({STRICT:!0}),zh=2147483647,$h=new Hh(zh);const Gh=1e7;function jh(e,t){if(t.source)try{e.sourceAccount=bh(t.source)}catch{throw new Error("Source address is invalid")}}function Wh(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 Zh(e){const t=new Hh(e).times(Gh);return tl.Int64.fromString(t.toString())}function Kh(e){return new Hh(e.toString()).div(Gh).toFixed(7)}function Xh(e){return new Hh(e.n()).div(new Hh(e.d())).toString()}function Yh(e){let t;if("object"==typeof e&&"n"in e&&"d"in e)t=new tl.Price(e);else{const n=new Hh(e);if(!n.gt(0)||!n.isFinite())throw new Error("price must be positive");const r=function(e){let t,n,r=new Hh(e);const o=[[new Hh(0),new Hh(1)],[new Hh(1),new Hh(0)]];let i=2;for(;!r.gt(zh);){t=r.integerValue(Hh.ROUND_FLOOR),n=r.minus(t);const e=o[i-1],s=o[i-2];if(!e||!s)throw new Error(`Continued fraction approximation failed: missing fraction elements at indices ${i-1} and/or ${i-2}`);const a=t.times(e[0]).plus(s[0]),c=t.times(e[1]).plus(s[1]);if(a.gt(zh)||c.gt(zh))break;if(o.push([a,c]),n.eq(0))break;r=new Hh(1).div(n),i+=1}const s=o[o.length-1];if(!s)throw new Error("Missing last fraction element in continued fraction approximation");const[a,c]=s;if(a.isZero()||c.isZero()){if(new Hh(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=$h;if(t[0].gt(0)&&(e=Hh.min(e,$h.minus(n[0]).div(t[0]).integerValue(Hh.ROUND_FLOOR))),t[1].gt(0)&&(e=Hh.min(e,$h.minus(n[1]).div(t[1]).integerValue(Hh.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 tl.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 Jh(e,t=!1){if("string"!=typeof e)return!1;let n;try{n=new Hh(e)}catch{return!1}return!(!t&&n.isZero()||n.isNegative()||n.times(Gh).gt(new Hh("9223372036854775807").toString())||(n.decimalPlaces()??0)>7||n.isNaN()||!n.isFinite())}function Qh(e){return`${e} argument must be of type String, represent a positive number and have at most 7 digits after the decimal`}function ep(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.amount,!0))throw new TypeError(Qh("amount"));const r=Zh(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=void 0!==e.offerId?e.offerId.toString():"0",s=tl.Int64.fromString(i),a=new tl.ManageSellOfferOp({selling:t,buying:n,amount:r,price:o,offerId:s}),c={sourceAccount:null,body:tl.OperationBody.manageSellOffer(a)};return jh(c,e),new tl.Operation(c)}function tp(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.amount))throw new TypeError(Qh("amount"));const r=Zh(e.amount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=new tl.CreatePassiveSellOfferOp({selling:t,buying:n,amount:r,price:o}),s={sourceAccount:null,body:tl.OperationBody.createPassiveSellOffer(i)};return jh(s,e),new tl.Operation(s)}function np(e){let t;try{t=tl.OperationBody.accountMerge(bh(e.destination))}catch{throw new Error("destination is invalid")}const n={sourceAccount:null,body:t};return jh(n,e),new tl.Operation(n)}function rp(e){if(!ih.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");const t=lh.fromPublicKey(e.trustor).xdrAccountId();let n,r;if(e.assetCode.length<=4){const t=oo.Buffer.from(e.assetCode.padEnd(4,"\0"));n=tl.AssetCode.assetTypeCreditAlphanum4(t)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");{const t=oo.Buffer.from(e.assetCode.padEnd(12,"\0"));n=tl.AssetCode.assetTypeCreditAlphanum12(t)}}if("boolean"==typeof e.authorize)r=e.authorize?tl.TrustLineFlags.authorizedFlag().value:0;else{if(null==e.authorize)throw new Error("authorize is required");r=e.authorize}const o=new tl.AllowTrustOp({trustor:t,asset:n,authorize:r}),i={sourceAccount:null,body:tl.OperationBody.allowTrust(o)};return jh(i,e),new tl.Operation(i)}function op(e){if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new Hh(e.bumpTo)}catch{throw new Error("bumpTo must be a stringified number")}const t=tl.Int64.fromString(e.bumpTo),n=new tl.BumpSequenceOp({bumpTo:t}),r={sourceAccount:null,body:tl.OperationBody.bumpSequence(n)};return jh(r,e),new tl.Operation(r)}function ip(e){const t=e.asset??e.line;let n;if(t instanceof ph)n=t.toChangeTrustXDRObject();else{if(!(t instanceof mh))throw new TypeError("asset must be Asset or LiquidityPoolAsset");n=t.toXDRObject()}if(void 0!==e.limit&&!Jh(e.limit,!0))throw new TypeError(Qh("limit"));const r=e.limit?Zh(e.limit):tl.Int64.fromString("9223372036854775807"),o=new tl.ChangeTrustOp({line:n,limit:r}),i={sourceAccount:null,body:tl.OperationBody.changeTrust(o)};return jh(i,e),new tl.Operation(i)}function sp(e){if(!ih.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!Jh(e.startingBalance,!0))throw new TypeError(Qh("startingBalance"));const t=new tl.CreateAccountOp({destination:lh.fromPublicKey(e.destination).xdrAccountId(),startingBalance:Zh(e.startingBalance)}),n={sourceAccount:null,body:tl.OperationBody.createAccount(t)};return jh(n,e),new tl.Operation(n)}function ap(e){if(!(e.asset instanceof ph))throw new Error("must provide an asset for create claimable balance operation");if(!Jh(e.amount))throw new TypeError(Qh("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=Zh(e.amount),r=e.claimants.map(e=>e.toXDRObject()),o=new tl.CreateClaimableBalanceOp({asset:t,amount:n,claimants:r}),i={sourceAccount:null,body:tl.OperationBody.createClaimableBalance(o)};return jh(i,e),new tl.Operation(i)}function cp(e={}){up(e.balanceId);const t=tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n=new tl.ClaimClaimableBalanceOp({balanceId:t}),r={sourceAccount:null,body:tl.OperationBody.claimClaimableBalance(n)};return jh(r,e),new tl.Operation(r)}function up(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}function lp(e={}){up(e.balanceId);const t=tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex"),n={sourceAccount:null,body:tl.OperationBody.clawbackClaimableBalance(new tl.ClawbackClaimableBalanceOp({balanceId:t}))};return jh(n,e),new tl.Operation(n)}function dp(e={}){const t={sourceAccount:null,body:tl.OperationBody.inflation()};return jh(t,e),new tl.Operation(t)}function hp(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&&!oo.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?oo.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 tl.ManageDataOp({dataName:e.name,dataValue:t}),r={sourceAccount:null,body:tl.OperationBody.manageData(n)};return jh(r,e),new tl.Operation(r)}function pp(e){const t=e.selling.toXDRObject(),n=e.buying.toXDRObject();if(!Jh(e.buyAmount,!0))throw new TypeError(Qh("buyAmount"));const r=Zh(e.buyAmount);if(void 0===e.price)throw new TypeError("price argument is required");const o=Yh(e.price),i=void 0!==e.offerId?e.offerId.toString():"0",s=tl.Int64.fromString(i),a=new tl.ManageBuyOfferOp({selling:t,buying:n,buyAmount:r,price:o,offerId:s}),c={sourceAccount:null,body:tl.OperationBody.manageBuyOffer(a)};return jh(c,e),new tl.Operation(c)}function fp(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!Jh(e.sendMax))throw new TypeError(Qh("sendMax"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!Jh(e.destAmount))throw new TypeError(Qh("destAmount"));let t;try{t=bh(e.destination)}catch{throw new Error("destination is invalid")}const n=e.path?e.path:[],r=new tl.PathPaymentStrictReceiveOp({sendAsset:e.sendAsset.toXDRObject(),sendMax:Zh(e.sendMax),destination:t,destAsset:e.destAsset.toXDRObject(),destAmount:Zh(e.destAmount),path:n.map(e=>e.toXDRObject())}),o={sourceAccount:null,body:tl.OperationBody.pathPaymentStrictReceive(r)};return jh(o,e),new tl.Operation(o)}function gp(e){if(!e.sendAsset)throw new Error("Must specify a send asset");if(!Jh(e.sendAmount))throw new TypeError(Qh("sendAmount"));if(!e.destAsset)throw new Error("Must provide a destAsset for a payment operation");if(!Jh(e.destMin))throw new TypeError(Qh("destMin"));const t=e.sendAsset.toXDRObject(),n=Zh(e.sendAmount);let r;try{r=bh(e.destination)}catch{throw new Error("destination is invalid")}const o=e.destAsset.toXDRObject(),i=Zh(e.destMin),s=(e.path??[]).map(e=>e.toXDRObject()),a=new tl.PathPaymentStrictSendOp({sendAsset:t,sendAmount:n,destination:r,destAsset:o,destMin:i,path:s}),c={sourceAccount:null,body:tl.OperationBody.pathPaymentStrictSend(a)};return jh(c,e),new tl.Operation(c)}function mp(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!Jh(e.amount))throw new TypeError(Qh("amount"));let t;try{t=bh(e.destination)}catch{throw new Error("destination is invalid")}const n=new tl.PaymentOp({destination:t,asset:e.asset.toXDRObject(),amount:Zh(e.amount)}),r={sourceAccount:null,body:tl.OperationBody.payment(n)};return jh(r,e),new tl.Operation(r)}function yp(e,t){if(e>=0&&e<=255)return!0;throw new Error(`${t} value must be between 0 and 255`)}function wp(e){let t=null;if(e.inflationDest){if(!ih.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t=lh.fromPublicKey(e.inflationDest).xdrAccountId()}const n=Wh("clearFlags",e.clearFlags)??null,r=Wh("setFlags",e.setFlags)??null,o=Wh("masterWeight",e.masterWeight,yp)??null,i=Wh("lowThreshold",e.lowThreshold,yp)??null,s=Wh("medThreshold",e.medThreshold,yp)??null,a=Wh("highThreshold",e.highThreshold,yp)??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=Wh("signer.weight",e.signer.weight,yp);let n,r=0;if(e.signer.ed25519PublicKey){if(!ih.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const t=ih.decodeEd25519PublicKey(e.signer.ed25519PublicKey);n=tl.SignerKey.signerKeyTypeEd25519(t),r+=1}if(e.signer.preAuthTx){let t;if(t="string"==typeof e.signer.preAuthTx?oo.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!oo.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");n=tl.SignerKey.signerKeyTypePreAuthTx(t),r+=1}if(e.signer.sha256Hash){let t;if(t="string"==typeof e.signer.sha256Hash?oo.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!oo.Buffer.isBuffer(t)||32!==t.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");n=tl.SignerKey.signerKeyTypeHashX(t),r+=1}if(e.signer.ed25519SignedPayload){if(!ih.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const t=ih.decodeSignedPayload(e.signer.ed25519SignedPayload),o=tl.SignerKeyEd25519SignedPayload.fromXDR(t);n=tl.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 tl.Signer({key:n,weight:t})}const l=new tl.SetOptionsOp({inflationDest:t,clearFlags:n,setFlags:r,masterWeight:o,lowThreshold:i,medThreshold:s,highThreshold:a,homeDomain:c,signer:u}),d={sourceAccount:null,body:tl.OperationBody.setOptions(l)};return jh(d,e),new tl.Operation(d)}function bp(e){if(!ih.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");const t=new tl.BeginSponsoringFutureReservesOp({sponsoredId:lh.fromPublicKey(e.sponsoredId).xdrAccountId()}),n={sourceAccount:null,body:tl.OperationBody.beginSponsoringFutureReserves(t)};return jh(n,e),new tl.Operation(n)}function vp(e={}){const t={sourceAccount:null,body:tl.OperationBody.endSponsoringFutureReserves()};return jh(t,e),new tl.Operation(t)}function Ap(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");const t=tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(e.account).xdrAccountId()})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Sp(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.asset instanceof ph)t=e.asset.toTrustLineXDRObject();else{if(!(e.asset instanceof wh))throw new TypeError("asset must be an Asset or LiquidityPoolId");t=e.asset.toXDRObject()}const n=tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(e.account).xdrAccountId(),asset:t})),r=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(n),o={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(r)};return jh(o,e),new tl.Operation(o)}function Tp(e={}){if(!ih.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");const t=tl.LedgerKey.offer(new tl.LedgerKeyOffer({sellerId:lh.fromPublicKey(e.seller).xdrAccountId(),offerId:tl.Int64.fromString(e.offerId)})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Ep(e={}){if(!ih.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=tl.LedgerKey.data(new tl.LedgerKeyData({accountId:lh.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function _p(e={}){if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");const t=tl.LedgerKey.claimableBalance(new tl.LedgerKeyClaimableBalance({balanceId:tl.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function kp(e={}){if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");const t=tl.LedgerKey.liquidityPool(new tl.LedgerKeyLiquidityPool({liquidityPoolId:oo.Buffer.from(e.liquidityPoolId,"hex")})),n=tl.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),r={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(n)};return jh(r,e),new tl.Operation(r)}function Cp(e={}){if(!ih.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");let t;if(e.signer.ed25519PublicKey){if(!ih.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");const n=ih.decodeEd25519PublicKey(e.signer.ed25519PublicKey);t=tl.SignerKey.signerKeyTypeEd25519(n)}else if(e.signer.preAuthTx){let n;if(n="string"==typeof e.signer.preAuthTx?oo.Buffer.from(e.signer.preAuthTx,"hex"):e.signer.preAuthTx,!oo.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");t=tl.SignerKey.signerKeyTypePreAuthTx(n)}else if(e.signer.sha256Hash){let n;if(n="string"==typeof e.signer.sha256Hash?oo.Buffer.from(e.signer.sha256Hash,"hex"):e.signer.sha256Hash,!oo.Buffer.isBuffer(n)||32!==n.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");t=tl.SignerKey.signerKeyTypeHashX(n)}else{if(!e.signer.ed25519SignedPayload)throw new Error("signer is invalid");{if(!ih.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");const n=ih.decodeSignedPayload(e.signer.ed25519SignedPayload),r=tl.SignerKeyEd25519SignedPayload.fromXDR(n);t=tl.SignerKey.signerKeyTypeEd25519SignedPayload(r)}}const n=new tl.RevokeSponsorshipOpSigner({accountId:lh.fromPublicKey(e.account).xdrAccountId(),signerKey:t}),r=tl.RevokeSponsorshipOp.revokeSponsorshipSigner(n),o={sourceAccount:null,body:tl.OperationBody.revokeSponsorship(r)};return jh(o,e),new tl.Operation(o)}function Rp(e){if(!Jh(e.amount))throw new TypeError(Qh("amount"));let t;try{t=bh(e.from)}catch{throw new Error("from address is invalid")}const n=new tl.ClawbackOp({amount:Zh(e.amount),asset:e.asset.toXDRObject(),from:t}),r={sourceAccount:null,body:tl.OperationBody.clawback(n)};return jh(r,e),new tl.Operation(r)}function xp(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:tl.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:tl.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:tl.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 i=e.flags[o],s=t[o];if(!s)throw new Error(`Invalid flag name: ${o}`);if("boolean"!=typeof i&&void 0!==i)throw new TypeError(`opts.flags.${o} must be a boolean (got ${typeof i})`);!0===i?r|=s.value:!1===i&&(n|=s.value)});const o=lh.fromPublicKey(e.trustor).xdrAccountId(),i=e.asset.toXDRObject(),s={sourceAccount:null,body:tl.OperationBody.setTrustLineFlags(new tl.SetTrustLineFlagsOp({trustor:o,asset:i,clearFlags:n,setFlags:r}))};return jh(s,e),new tl.Operation(s)}function Ip(e={}){const{liquidityPoolId:t,maxAmountA:n,maxAmountB:r,minPrice:o,maxPrice:i}=e;if(!t)throw new TypeError("liquidityPoolId argument is required");const s=oo.Buffer.from(t,"hex");if(!Jh(n,!0))throw new TypeError(Qh("maxAmountA"));const a=Zh(n);if(!Jh(r,!0))throw new TypeError(Qh("maxAmountB"));const c=Zh(r);if(void 0===o)throw new TypeError("minPrice argument is required");const u=Yh(o);if(void 0===i)throw new TypeError("maxPrice argument is required");const l=Yh(i),d=new tl.LiquidityPoolDepositOp({liquidityPoolId:s,maxAmountA:a,maxAmountB:c,minPrice:u,maxPrice:l}),h={sourceAccount:null,body:tl.OperationBody.liquidityPoolDeposit(d)};return jh(h,e),new tl.Operation(h)}function Bp(e={}){if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");const t=oo.Buffer.from(e.liquidityPoolId,"hex");if(!Jh(e.amount))throw new TypeError(Qh("amount"));const n=Zh(e.amount);if(!Jh(e.minAmountA,!0))throw new TypeError(Qh("minAmountA"));const r=Zh(e.minAmountA);if(!Jh(e.minAmountB,!0))throw new TypeError(Qh("minAmountB"));const o=Zh(e.minAmountB),i=new tl.LiquidityPoolWithdrawOp({liquidityPoolId:t,amount:n,minAmountA:r,minAmountB:o}),s={sourceAccount:null,body:tl.OperationBody.liquidityPoolWithdraw(i)};return jh(s,e),new tl.Operation(s)}class Op{_type;_key;constructor(e){if(ih.isValidEd25519PublicKey(e))this._type="account",this._key=ih.decodeEd25519PublicKey(e);else if(ih.isValidContract(e))this._type="contract",this._key=ih.decodeContract(e);else if(ih.isValidMed25519PublicKey(e))this._type="muxedAccount",this._key=ih.decodeMed25519PublicKey(e);else if(ih.isValidClaimableBalance(e))this._type="claimableBalance",this._key=ih.decodeClaimableBalance(e);else{if(!ih.isValidLiquidityPool(e))throw new Error(`Unsupported address type: ${e}`);this._type="liquidityPool",this._key=ih.decodeLiquidityPool(e)}}static fromString(e){return new Op(e)}static account(e){return new Op(ih.encodeEd25519PublicKey(e))}static contract(e){return new Op(ih.encodeContract(e))}static claimableBalance(e){return new Op(ih.encodeClaimableBalance(e))}static liquidityPool(e){return new Op(ih.encodeLiquidityPool(e))}static muxedAccount(e){return new Op(ih.encodeMed25519PublicKey(e))}static fromScVal(e){return Op.fromScAddress(e.address())}static fromScAddress(e){switch(e.switch().value){case tl.ScAddressType.scAddressTypeAccount().value:return Op.account(e.accountId().ed25519());case tl.ScAddressType.scAddressTypeContract().value:return Op.contract(e.contractId());case tl.ScAddressType.scAddressTypeMuxedAccount().value:{const t=oo.Buffer.concat([e.muxedAccount().ed25519(),e.muxedAccount().id().toXDR("raw")]);return Op.muxedAccount(t)}case tl.ScAddressType.scAddressTypeClaimableBalance().value:{const t=e.claimableBalanceId();return Op.claimableBalance(oo.Buffer.concat([oo.Buffer.from([t.switch().value]),t.v0()]))}case tl.ScAddressType.scAddressTypeLiquidityPool().value:return Op.liquidityPool(e.liquidityPoolId());default:throw new Error(`Unsupported address type: ${e.switch().name}`)}}toString(){switch(this._type){case"account":return ih.encodeEd25519PublicKey(this._key);case"contract":return ih.encodeContract(this._key);case"claimableBalance":return ih.encodeClaimableBalance(this._key);case"liquidityPool":return ih.encodeLiquidityPool(this._key);case"muxedAccount":return ih.encodeMed25519PublicKey(this._key);default:throw new Error("Unsupported address type")}}toScVal(){return tl.ScVal.scvAddress(this.toScAddress())}toScAddress(){switch(this._type){case"account":return tl.ScAddress.scAddressTypeAccount(tl.PublicKey.publicKeyTypeEd25519(this._key));case"contract":return tl.ScAddress.scAddressTypeContract(this._key);case"liquidityPool":return tl.ScAddress.scAddressTypeLiquidityPool(this._key);case"claimableBalance":return tl.ScAddress.scAddressTypeClaimableBalance(tl.ClaimableBalanceId.claimableBalanceIdTypeV0(this._key.subarray(1)));case"muxedAccount":return tl.ScAddress.scAddressTypeMuxedAccount(new tl.MuxedEd25519Account({ed25519:this._key.subarray(0,32),id:tl.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 Pp(e){if(!e.func)throw new TypeError(`host function invocation ('func') required (got ${JSON.stringify(e)})`);e.func.switch().value===tl.HostFunctionType.hostFunctionTypeInvokeContract().value&&e.func.invokeContract().args().forEach(e=>{let t;try{t=Op.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 tl.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),n={sourceAccount:null,body:tl.OperationBody.invokeHostFunction(t)};return jh(n,e),new tl.Operation(n)}function Lp(e){const t=new Op(e.contract);if("contract"!==t.type)throw new TypeError(`expected contract strkey instance, got ${t.toString()}`);return Pp({func:tl.HostFunction.hostFunctionTypeInvokeContract(new tl.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 Up(e){const t=oo.Buffer.from(e.salt||lh.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 Pp({func:tl.HostFunction.hostFunctionTypeCreateContractV2(new tl.CreateContractArgsV2({executable:tl.ContractExecutable.contractExecutableWasm(oo.Buffer.from(e.wasmHash)),contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAddress(new tl.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 Np(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 ph(r,n[1])}if(!(t instanceof ph))throw new TypeError(`expected Asset in 'opts.asset', got ${String(e.asset)}`);return Pp({func:tl.HostFunction.hostFunctionTypeCreateContract(new tl.CreateContractArgs({executable:tl.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:tl.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())})),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Fp(e){return Pp({func:tl.HostFunction.hostFunctionTypeUploadContractWasm(oo.Buffer.from(e.wasm)),auth:e.auth||[],...void 0!==e.source&&{source:e.source}})}function Dp(e){if((e.extendTo??-1)<=0)throw new RangeError("extendTo has to be positive");const t=new tl.ExtendFootprintTtlOp({ext:new tl.ExtensionPoint(0),extendTo:e.extendTo}),n={sourceAccount:null,body:tl.OperationBody.extendFootprintTtl(t)};return jh(n,e),new tl.Operation(n)}function Mp(e={}){const t=new tl.RestoreFootprintOp({ext:new tl.ExtensionPoint(0)}),n={sourceAccount:null,body:tl.OperationBody.restoreFootprint(t)};return jh(n,e),new tl.Operation(n)}class Vp{static fromXDRObject(e){const t={},n=e.sourceAccount();n&&(t.source=vh(n));const r=e.body().value(),o=e.body().switch().name;switch(o){case"createAccount":t.type="createAccount",t.destination=qp(r.destination()),t.startingBalance=Kh(r.startingBalance());break;case"payment":t.type="payment",t.destination=vh(r.destination()),t.asset=ph.fromOperation(r.asset()),t.amount=Kh(r.amount());break;case"pathPaymentStrictReceive":{t.type="pathPaymentStrictReceive",t.sendAsset=ph.fromOperation(r.sendAsset()),t.sendMax=Kh(r.sendMax()),t.destination=vh(r.destination()),t.destAsset=ph.fromOperation(r.destAsset()),t.destAmount=Kh(r.destAmount()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(ph.fromOperation(e[n]))});break}case"pathPaymentStrictSend":{t.type="pathPaymentStrictSend",t.sendAsset=ph.fromOperation(r.sendAsset()),t.sendAmount=Kh(r.sendAmount()),t.destination=vh(r.destination()),t.destAsset=ph.fromOperation(r.destAsset()),t.destMin=Kh(r.destMin()),t.path=[];const e=r.path();Object.keys(e).forEach(n=>{t.path.push(ph.fromOperation(e[n]))});break}case"changeTrust":if(t.type="changeTrust",r.line().switch()===tl.AssetType.assetTypePoolShare())t.line=mh.fromOperation(r.line());else t.line=ph.fromOperation(r.line());t.limit=Kh(r.limit());break;case"allowTrust":t.type="allowTrust",t.trustor=qp(r.trustor()),t.assetCode=r.asset().value().toString(),t.assetCode=Yd(t.assetCode,"\0"),t.authorize=r.authorize();break;case"setOptions":if(t.type="setOptions",r.inflationDest()&&(t.inflationDest=qp(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=qp(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=ih.encodeSignedPayload(t.toXDR())}e.weight=r.signer().weight(),t.signer=e}break;case"manageOffer":case"manageSellOffer":t.type="manageSellOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.amount=Kh(r.amount()),t.price=Xh(r.price()),t.offerId=r.offerId().toString();break;case"manageBuyOffer":t.type="manageBuyOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.buyAmount=Kh(r.buyAmount()),t.price=Xh(r.price()),t.offerId=r.offerId().toString();break;case"createPassiveOffer":case"createPassiveSellOffer":t.type="createPassiveSellOffer",t.selling=ph.fromOperation(r.selling()),t.buying=ph.fromOperation(r.buying()),t.amount=Kh(r.amount()),t.price=Xh(r.price());break;case"accountMerge":t.type="accountMerge",t.destination=vh(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=ph.fromOperation(r.asset()),t.amount=Kh(r.amount()),t.claimants=[],r.claimants().forEach(e=>{t.claimants.push(yh.fromXDR(e))});break;case"claimClaimableBalance":t.type="claimClaimableBalance",t.balanceId=r.toXDR("hex");break;case"beginSponsoringFutureReserves":t.type="beginSponsoringFutureReserves",t.sponsoredId=qp(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 tl.LedgerEntryType.account().name:t.type="revokeAccountSponsorship",t.account=qp(n.account().accountId());break;case tl.LedgerEntryType.trustline().name:{t.type="revokeTrustlineSponsorship",t.account=qp(n.trustLine().accountId());const e=n.trustLine().asset();if(e.switch()===tl.AssetType.assetTypePoolShare())t.asset=wh.fromOperation(e);else t.asset=ph.fromOperation(e);break}case tl.LedgerEntryType.offer().name:t.type="revokeOfferSponsorship",t.seller=qp(n.offer().sellerId()),t.offerId=n.offer().offerId().toString();break;case tl.LedgerEntryType.data().name:t.type="revokeDataSponsorship",t.account=qp(n.data().accountId()),t.name=n.data().dataName().toString("ascii");break;case tl.LedgerEntryType.claimableBalance().name:t.type="revokeClaimableBalanceSponsorship",t.balanceId=n.claimableBalance().balanceId().toXDR("hex");break;case tl.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=qp(e.signer().accountId()),t.signer=function(e){const t={};switch(e.switch().name){case tl.SignerKeyType.signerKeyTypeEd25519().name:t.ed25519PublicKey=ih.encodeEd25519PublicKey(e.ed25519());break;case tl.SignerKeyType.signerKeyTypePreAuthTx().name:t.preAuthTx=e.preAuthTx().toString("hex");break;case tl.SignerKeyType.signerKeyTypeHashX().name:t.sha256Hash=e.hashX().toString("hex");break;case tl.SignerKeyType.signerKeyTypeEd25519SignedPayload().name:{const n=e.ed25519SignedPayload();t.ed25519SignedPayload=ih.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=Kh(r.amount()),t.from=vh(r.from()),t.asset=ph.fromOperation(r.asset());break;case"clawbackClaimableBalance":t.type="clawbackClaimableBalance",t.balanceId=r.toXDR("hex");break;case"setTrustLineFlags":{t.type="setTrustLineFlags",t.asset=ph.fromOperation(r.asset()),t.trustor=qp(r.trustor());const e=r.clearFlags(),n=r.setFlags(),o={authorized:tl.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:tl.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:tl.TrustLineFlags.trustlineClawbackEnabledFlag()},i=t=>{const r=o[t]?.value??0;return!!(n&r)||!(e&r)&&void 0},s={};Object.keys(o).forEach(e=>{s[e]=i(e)}),t.flags=s;break}case"liquidityPoolDeposit":t.type="liquidityPoolDeposit",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.maxAmountA=Kh(r.maxAmountA()),t.maxAmountB=Kh(r.maxAmountB()),t.minPrice=Xh(r.minPrice()),t.maxPrice=Xh(r.maxPrice());break;case"liquidityPoolWithdraw":t.type="liquidityPoolWithdraw",t.liquidityPoolId=r.liquidityPoolId().toString("hex"),t.amount=Kh(r.amount()),t.minAmountA=Kh(r.minAmountA()),t.minAmountB=Kh(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=np;static allowTrust=rp;static bumpSequence=op;static changeTrust=ip;static createAccount=sp;static createClaimableBalance=ap;static claimClaimableBalance=cp;static clawbackClaimableBalance=lp;static createPassiveSellOffer=tp;static inflation=dp;static manageData=hp;static manageSellOffer=ep;static manageBuyOffer=pp;static pathPaymentStrictReceive=fp;static pathPaymentStrictSend=gp;static payment=mp;static setOptions=wp;static beginSponsoringFutureReserves=bp;static endSponsoringFutureReserves=vp;static revokeAccountSponsorship=Ap;static revokeTrustlineSponsorship=Sp;static revokeOfferSponsorship=Tp;static revokeDataSponsorship=Ep;static revokeClaimableBalanceSponsorship=_p;static revokeLiquidityPoolSponsorship=kp;static revokeSignerSponsorship=Cp;static clawback=Rp;static setTrustLineFlags=xp;static liquidityPoolDeposit=Ip;static liquidityPoolWithdraw=Bp;static invokeHostFunction=Pp;static extendFootprintTtl=Dp;static restoreFootprint=Mp;static createStellarAssetContract=Np;static invokeContractFunction=Lp;static createCustomContract=Up;static uploadContractWasm=Fp}function qp(e){return ih.encodeEd25519PublicKey(e.ed25519())}const Hp="none",zp="id",$p="text",Gp="hash",jp="return";class Wp{_type;_value;constructor(e,t=null){switch(this._type=e,this._value=t,this._type){case Hp:break;case zp:Wp._validateIdValue(t);break;case $p:Wp._validateTextValue(t);break;case Gp:case jp:Wp._validateHashValue(t),"string"==typeof t&&(this._value=oo.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 Hp:return null;case zp:case $p:return this._value;case Gp:case jp:return oo.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 Hh(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(oo.Buffer.byteLength(e,"utf8")>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(oo.Buffer.isBuffer(e)){if(e.length>28)throw new Error("Expects string, array or buffer, max 28 bytes")}else if(!tl.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=oo.Buffer.from(e,"hex")}else{if(!oo.Buffer.isBuffer(e))throw t;n=oo.Buffer.from(e)}if(!n.length||32!==n.length)throw t}static none(){return new Wp(Hp)}static text(e){return new Wp($p,e)}static id(e){return new Wp(zp,e)}static hash(e){return new Wp(Gp,e)}static return(e){return new Wp(jp,e)}toXDRObject(){switch(this._type){case Hp:return tl.Memo.memoNone();case zp:return tl.Memo.memoId(tl.Uint64.fromString(el.UnsignedHyper.fromString(this._value).toString()));case $p:return tl.Memo.memoText(this._value);case Gp:return tl.Memo.memoHash(this._value);case jp:return tl.Memo.memoReturn(this._value);default:throw new Error("Invalid memo type")}}static fromXDRObject(e){switch(e.switch()){case tl.MemoType.memoId():return Wp.id(e.id().toString());case tl.MemoType.memoText():return Wp.text(e.value());case tl.MemoType.memoHash():return Wp.hash(e.hash());case tl.MemoType.memoReturn():return Wp.return(e.retHash())}if(void 0===e.value())return Wp.none();throw new Error("Unknown type")}}class Zp extends gh{_envelopeType;_source="";_memo;_sequence;_operations;_timeBounds;_ledgerBounds;_minAccountSequence;_minAccountSequenceAge;_minAccountSequenceLedgerGap;_extraSigners;constructor(e,t){if("string"==typeof e){const t=oo.Buffer.from(e,"base64");e=tl.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==tl.EnvelopeType.envelopeTypeTxV0()&&n!==tl.EnvelopeType.envelopeTypeTx())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ${n.name}.`);const r=e.value(),o=r.tx(),i=o.fee().toString();if(super(o,(r.signatures()||[]).slice(),i,t),this._envelopeType=n,this._memo=o.memo(),this._sequence=o.seqNum().toString(),this._envelopeType===tl.EnvelopeType.envelopeTypeTxV0())this._source=ih.encodeEd25519PublicKey(o.sourceAccountEd25519());else this._source=vh(o.sourceAccount());let s=null,a=null;switch(this._envelopeType){case tl.EnvelopeType.envelopeTypeTxV0():a=o.timeBounds();break;case tl.EnvelopeType.envelopeTypeTx():switch(o.cond().switch()){case tl.PreconditionType.precondTime():a=o.cond().timeBounds();break;case tl.PreconditionType.precondV2():s=o.cond().v2(),a=s.timeBounds()}}if(a&&(this._timeBounds={minTime:a.minTime().toString(),maxTime:a.maxTime().toString()}),s){const e=s.ledgerBounds();e&&(this._ledgerBounds={minLedger:e.minLedger(),maxLedger:e.maxLedger()});const t=s.minSeqNum();t&&(this._minAccountSequence=t.toString()),this._minAccountSequenceAge=s.minSeqAge().toBigInt(),this._minAccountSequenceLedgerGap=s.minSeqLedgerGap(),this._extraSigners=s.extraSigners()}const c=o.operations()||[];this._operations=c.map(e=>Vp.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 Wp.fromXDRObject(this._memo)}set memo(e){throw new Error("Transaction is immutable")}signatureBase(){let e=this.tx;this._envelopeType===tl.EnvelopeType.envelopeTypeTxV0()&&(e=tl.Transaction.fromXDR(oo.Buffer.concat([oo.Buffer.alloc(4),e.toXDR()])));const t=tl.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(e);return new tl.TransactionSignaturePayload({networkId:tl.Hash.fromXDR($l(this.networkPassphrase)),taggedTransaction:t}).toXDR()}toEnvelope(){const e=this.tx.toXDR(),t=this.signatures.slice();let n;switch(this._envelopeType){case tl.EnvelopeType.envelopeTypeTxV0():n=tl.TransactionEnvelope.envelopeTypeTxV0(new tl.TransactionV0Envelope({tx:tl.TransactionV0.fromXDR(e),signatures:t}));break;case tl.EnvelopeType.envelopeTypeTx():n=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:tl.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{Vp.createClaimableBalance(t)}catch(e){throw new TypeError(`expected createClaimableBalance, got ${t.type}: ${String(e)}`)}const n=ih.decodeEd25519PublicKey(Sh(this.source)),r=$l(tl.HashIdPreimage.envelopeTypeOpId(new tl.HashIdPreimageOperationId({sourceAccount:tl.PublicKey.publicKeyTypeEd25519(n),seqNum:tl.Int64.fromString(this.sequence),opNum:e})).toXDR("raw"));return tl.ClaimableBalanceId.claimableBalanceIdTypeV0(r).toXDR("hex")}}class Kp extends gh{_feeSource;_innerTransaction;constructor(e,t){if("string"==typeof e){const t=oo.Buffer.from(e,"base64");e=tl.TransactionEnvelope.fromXDR(t)}const n=e.switch();if(n!==tl.EnvelopeType.envelopeTypeTxFeeBump())throw new Error(`Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ${n.name}.`);const r=e.value(),o=r.tx(),i=o.fee().toString();super(o,(r.signatures()||[]).slice(),i,t);const s=tl.TransactionEnvelope.envelopeTypeTx(o.innerTx().v1());this._feeSource=vh(this.tx.feeSource()),this._innerTransaction=new Zp(s,t)}get innerTransaction(){return this._innerTransaction}get operations(){return this._innerTransaction.operations}get feeSource(){return this._feeSource}signatureBase(){const e=tl.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx);return new tl.TransactionSignaturePayload({networkId:tl.Hash.fromXDR($l(this.networkPassphrase)),taggedTransaction:e}).toXDR()}toEnvelope(){const e=new tl.FeeBumpTransactionEnvelope({tx:tl.FeeBumpTransaction.fromXDR(this.tx.toXDR()),signatures:this.signatures.slice()});return tl.TransactionEnvelope.envelopeTypeTxFeeBump(e)}}class Xp{_accountId;sequence;constructor(e,t){if(ih.isValidMed25519PublicKey(e))throw new Error("accountId is an M-address; use MuxedAccount instead");if(!ih.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 Hh(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 Yp=BigInt("18446744073709551615");function Jp(e){let t;try{t=BigInt(e)}catch{throw new Error(`id is not a valid uint64 string: ${e}`)}if(t<BigInt(0)||t>Yp)throw new Error(`id value out of range for uint64 [0, ${Yp}]: ${e}`)}class Qp{account;_muxedXdr;_mAddress;_id;constructor(e,t){const n=e.accountId();if(!ih.isValidEd25519PublicKey(n))throw new Error("accountId is invalid");Jp(t),this.account=e,this._muxedXdr=Ah(n,t),this._mAddress=vh(this._muxedXdr),this._id=t}static fromAddress(e,t){const n=bh(e),r=Sh(e),o=n.med25519().id().toString();return new Qp(new Xp(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 Jp(e),this._muxedXdr.med25519().id(tl.Uint64.fromString(e)),this._mAddress=vh(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 ef{_data;constructor(e){let t;t=e?"string"==typeof e||ArrayBuffer.isView(e)?ef.fromXDR(e):ef.fromXDR(e.toXDR()):new tl.SorobanTransactionData({resources:new tl.SorobanResources({footprint:new tl.LedgerFootprint({readOnly:[],readWrite:[]}),instructions:0,diskReadBytes:0,writeBytes:0}),ext:new tl.SorobanTransactionDataExt(0),resourceFee:new tl.Int64(0)}),this._data=t}static fromXDR(e){return"string"==typeof e?tl.SorobanTransactionData.fromXDR(e,"base64"):tl.SorobanTransactionData.fromXDR(oo.Buffer.from(e),"raw")}setResourceFee(e){return this._data.resourceFee(new tl.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 tl.SorobanTransactionData.fromXDR(this._data.toXDR())}getReadOnly(){return this.getFootprint().readOnly()}getReadWrite(){return this.getFootprint().readWrite()}getFootprint(){return this._data.resources().footprint()}}class tf{static decodeAddress(e){const t=ih.getVersionByteForPrefix(e);if(void 0===t)throw new Error(`invalid signer key type (${t})`);const n=ah(t,e);switch(t){case"signedPayload":return tl.SignerKey.signerKeyTypeEd25519SignedPayload(new tl.SignerKeyEd25519SignedPayload({ed25519:n.subarray(0,32),payload:n.subarray(36,36+n.readUInt32BE(32))}));case"ed25519PublicKey":return tl.SignerKey.signerKeyTypeEd25519(n);case"preAuthTx":return tl.SignerKey.signerKeyTypePreAuthTx(n);case"sha256Hash":return tl.SignerKey.signerKeyTypeHashX(n);default:throw new Error(`invalid signer key type (${t})`)}}static encodeSignerKey(e){let t,n;switch(e.switch()){case tl.SignerKeyType.signerKeyTypeEd25519():t="ed25519PublicKey",n=e.value();break;case tl.SignerKeyType.signerKeyTypePreAuthTx():t="preAuthTx",n=e.value();break;case tl.SignerKeyType.signerKeyTypeHashX():t="sha256Hash",n=e.value();break;case tl.SignerKeyType.signerKeyTypeEd25519SignedPayload():t="signedPayload",n=e.ed25519SignedPayload().toXDR("raw");break;default:throw new Error(`invalid SignerKey (type: ${e.switch().name})`)}return ch(t,n)}}class nf{_id;constructor(e){try{this._id=ih.decodeContract(e)}catch{throw new Error(`Invalid contract ID: ${e}`)}}contractId(){return ih.encodeContract(this._id)}toString(){return this.contractId()}address(){return Op.contract(this._id)}call(e,...t){return Vp.invokeContractFunction({contract:this.address().toString(),function:e,args:t})}getFootprint(){return tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:this.address().toScAddress(),key:tl.ScVal.scvLedgerKeyContractInstance(),durability:tl.ContractDataDurability.persistent()}))}}class rf extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 128}}rf.defineIntBoundaries();class of extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!0}get size(){return 256}}of.defineIntBoundaries();class sf extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 128}}sf.defineIntBoundaries();class af extends el.LargeInt{constructor(...e){super(e)}get unsigned(){return!1}get size(){return 256}}af.defineIntBoundaries();class cf{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 el.Hyper(n);break;case"i128":this.int=new sf(...n);break;case"i256":this.int=new af(...n);break;case"u64":case"timepoint":case"duration":this.int=new el.UnsignedHyper(n);break;case"u128":this.int=new rf(...n);break;case"u256":this.int=new of(...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 tl.ScVal.scvI64(new tl.Int64(e))}toU64(){return this._sizeCheck(64),tl.ScVal.scvU64(new tl.Uint64(BigInt.asUintN(64,this.toBigInt())))}toTimepoint(){return this._sizeCheck(64),tl.ScVal.scvTimepoint(new tl.Uint64(BigInt.asUintN(64,this.toBigInt())))}toDuration(){return this._sizeCheck(64),tl.ScVal.scvDuration(new tl.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 tl.ScVal.scvI128(new tl.Int128Parts({hi:new tl.Int64(t),lo:new tl.Uint64(n)}))}toU128(){this._sizeCheck(128);const e=this.int.toBigInt();return tl.ScVal.scvU128(new tl.UInt128Parts({hi:new tl.Uint64(BigInt.asUintN(64,e>>64n)),lo:new tl.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 tl.ScVal.scvI256(new tl.Int256Parts({hiHi:new tl.Int64(t),hiLo:new tl.Uint64(n),loHi:new tl.Uint64(r),loLo:new tl.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 tl.ScVal.scvU256(new tl.UInt256Parts({hiHi:new tl.Uint64(t),hiLo:new tl.Uint64(n),loHi:new tl.Uint64(r),loLo:new tl.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 uf extends cf{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 lf(e){const t=e.switch().name,n=cf.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 cf(n,r).toBigInt();case"scvU128":case"scvI128":{if(void 0===n)throw TypeError(`invalid integer type for ${t}`);const e=r;return new cf(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 cf(n,[e.loLo(),e.loHi(),e.hiLo(),e.hiHi()]).toBigInt()}default:throw TypeError(`expected integer type, got ${t}`)}}function df(e,t={}){switch(typeof e){case"object":{if(null===e)return tl.ScVal.scvVoid();if(e instanceof tl.ScVal)return e;if(e instanceof Op)return e.toScVal();if(e instanceof lh)return df(e.publicKey(),{type:"address"});if(e instanceof nf)return e.address().toScVal();if(e instanceof Uint8Array||oo.Buffer.isBuffer(e)){const n=oo.Buffer.from(e);switch(t?.type??"bytes"){case"bytes":return tl.ScVal.scvBytes(n);case"symbol":return tl.ScVal.scvSymbol(n);case"string":return tl.ScVal.scvString(n);default:throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for bytes-like value`)}}if(Array.isArray(e))return tl.ScVal.scvVec(e.map((e,n)=>Array.isArray(t.type)?df(e,{...t.type.length>n&&{type:t.type[n]}}):df(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 tl.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],i=r?{type:r}:{},s=o?{type:o}:{};return new tl.ScMapEntry({key:df(e,i),val:df(t,s)})}))}case"number":case"bigint":{const n=BigInt(e);switch(t?.type){case"u32":if(n<BigInt(tl.Uint32.MIN_VALUE)||n>BigInt(tl.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return tl.ScVal.scvU32(Number(e));case"i32":if(n<-BigInt(tl.Int32.MIN_VALUE)||n>BigInt(tl.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return tl.ScVal.scvI32(Number(e))}return new uf(e,{type:t?.type}).toScVal()}case"string":{const n=t?.type??"string";switch(n){case"string":return tl.ScVal.scvString(e);case"symbol":return tl.ScVal.scvSymbol(e);case"address":return new Op(e).toScVal();case"u32":{const t=BigInt(e);if(t<BigInt(tl.Uint32.MIN_VALUE)||t>BigInt(tl.Uint32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type u32`);return tl.ScVal.scvU32(Number(t))}case"i32":{const t=BigInt(e);if(t<-BigInt(tl.Int32.MIN_VALUE)||t>BigInt(tl.Int32.MAX_VALUE))throw new TypeError(`invalid value (${e}) for type i32`);return tl.ScVal.scvI32(Number(t))}default:if(cf.isType(n))return new cf(n,e).toScVal();throw new TypeError(`invalid type (${JSON.stringify(t.type)}) specified for string value`)}}case"boolean":return tl.ScVal.scvBool(e);case"undefined":return tl.ScVal.scvVoid();case"function":return df(e());default:throw new TypeError(`failed to convert typeof ${typeof e} (${JSON.stringify(e)})`)}}function hf(e){switch(e.switch().value){case tl.ScValType.scvVoid().value:return null;case tl.ScValType.scvU64().value:case tl.ScValType.scvI64().value:return e.value().toBigInt();case tl.ScValType.scvU128().value:case tl.ScValType.scvI128().value:case tl.ScValType.scvU256().value:case tl.ScValType.scvI256().value:return lf(e);case tl.ScValType.scvVec().value:return(e.vec()??[]).map(hf);case tl.ScValType.scvAddress().value:return Op.fromScVal(e).toString();case tl.ScValType.scvMap().value:return Object.fromEntries((e.map()??[]).map(e=>[hf(e.key()),hf(e.val())]));case tl.ScValType.scvBool().value:case tl.ScValType.scvU32().value:case tl.ScValType.scvI32().value:case tl.ScValType.scvBytes().value:return e.value();case tl.ScValType.scvSymbol().value:{const t=e.sym();if(oo.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case tl.ScValType.scvString().value:{const t=e.str();if(oo.Buffer.isBuffer(t)||ArrayBuffer.isView(t)&&"string"!=typeof t)try{return(new TextDecoder).decode(t)}catch{return new Uint8Array(t.buffer)}return t}case tl.ScValType.scvTimepoint().value:case tl.ScValType.scvDuration().value:return e.value().toBigInt();case tl.ScValType.scvError().value:if(e.error().switch().value===tl.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 pf(e){const t=Array.from(e).sort((e,t)=>{const n=hf(e.key()),r=hf(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 tl.ScVal.scvMap(t)}tl.scvSortedMap=pf;const ff=el.Hyper.MAX_VALUE,gf=4294967295,mf="100";class yf{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=bf(t.timebounds.minTime),n=bf(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||Wp.none(),this.networkPassphrase=t.networkPassphrase||null,this.sorobanData=t.sorobanData?new ef(t.sorobanData).build():null}static cloneFrom(e,t={}){if(!(e instanceof Zp))throw new TypeError(`expected a 'Transaction', got: ${String(e)}`);const n=(BigInt(e.sequence)-1n).toString();let r,o;if(ih.isValidMed25519PublicKey(e.source))r=Qp.fromAddress(e.source,n);else{if(!ih.isValidEd25519PublicKey(e.source))throw new TypeError(`unsupported tx source account: ${e.source}`);r=new Xp(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 i=e.toEnvelope();i.switch()===tl.EnvelopeType.envelopeTypeTx()&&(o=i.v1().tx().ext().value()??void 0);let s=parseInt(e.fee,10);if(o){const e=Number(o.resourceFee().toBigInt());s-e>0&&(s-=e)}const a={fee:(Math.floor(s/e.operations.length)||mf).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=>tf.encodeSignerKey(e))),Object.assign(a,t);const c=new yf(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 ef(e).build(),this}addSacTransferOperation(e,t,n,r){if(BigInt(n)<=0n)throw new Error("Amount must be a positive integer");if(BigInt(n)>ff)throw new Error("Amount exceeds maximum value for i64");if(r){const{instructions:e,readBytes:t,writeBytes:n,resourceFee:o}=r,i=4294967295;if(e<=0||e>i)throw new Error(`instructions must be greater than 0 and at most ${i}`);if(t<=0||t>i)throw new Error(`readBytes must be greater than 0 and at most ${i}`);if(n<=0||n>i)throw new Error(`writeBytes must be greater than 0 and at most ${i}`);if(o<=0n||o>ff)throw new Error("resourceFee must be greater than 0 and at most i64 max")}const o=ih.isValidContract(e);if(!o&&!ih.isValidEd25519PublicKey(e)&&!ih.isValidMed25519PublicKey(e))throw new Error("Invalid destination address. Must be a valid Stellar address or contract ID.");const i=o?e:Sh(e);if(i===Sh(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 s=t.contractId(this.networkPassphrase),a="transfer",c=this.source.accountId(),u=Sh(c),l=[df(c,{type:"address"}),df(e,{type:"address"}),df(n,{type:"i128"})],d=t.isNative(),h=new tl.SorobanAuthorizationEntry({credentials:tl.SorobanCredentials.sorobanCredentialsSourceAccount(),rootInvocation:new tl.SorobanAuthorizedInvocation({function:tl.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(new tl.InvokeContractArgs({contractAddress:Op.fromString(s).toScAddress(),functionName:a,args:l})),subInvocations:[]})}),p=new tl.LedgerFootprint({readOnly:[tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:Op.fromString(s).toScAddress(),key:tl.ScVal.scvLedgerKeyContractInstance(),durability:tl.ContractDataDurability.persistent()}))],readWrite:[]});if(o){if(p.readWrite().push(tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:Op.fromString(s).toScAddress(),key:tl.ScVal.scvVec([df("Balance",{type:"symbol"}),df(e,{type:"address"})]),durability:tl.ContractDataDurability.persistent()}))),!d){const e=t.getIssuer();if(!e)throw new Error("Asset issuer must be set for non-native assets.");p.readOnly().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(e).xdrPublicKey()})))}}else d?p.readWrite().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(i).xdrPublicKey()}))):t.getIssuer()!==i&&p.readWrite().push(tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(i).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));t.isNative()?p.readWrite().push(tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.fromPublicKey(u).xdrPublicKey()}))):t.getIssuer()!==u&&p.readWrite().push(tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.fromPublicKey(u).xdrPublicKey(),asset:t.toTrustLineXDRObject()})));const f={instructions:4e5,readBytes:1e3,writeBytes:1e3,resourceFee:BigInt(5e6)},g=new tl.SorobanTransactionData({resources:new tl.SorobanResources({footprint:p,instructions:r?r.instructions:f.instructions,diskReadBytes:r?r.readBytes:f.readBytes,writeBytes:r?r.writeBytes:f.writeBytes}),ext:new tl.SorobanTransactionDataExt(0),resourceFee:new tl.Int64(r?r.resourceFee:f.resourceFee)}),m=Vp.invokeContractFunction({contract:s,function:a,args:l,auth:[h]});return this.setSorobanData(g),this.addOperation(m)}build(){const e=new Hh(this.source.sequenceNumber()).plus(1),t=new Hh(this.baseFee).times(this.operations.length).toNumber();if(t>gf)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:tl.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).");wf(this.timebounds.minTime)&&(this.timebounds.minTime=Math.floor(this.timebounds.minTime.getTime()/1e3)),wf(this.timebounds.maxTime)&&(this.timebounds.maxTime=Math.floor(this.timebounds.maxTime.getTime()/1e3));const r=tl.Uint64.fromString(this.timebounds.minTime.toString()),o=tl.Uint64.fromString(this.timebounds.maxTime.toString()),i=new tl.TimeBounds({minTime:r,maxTime:o});if(this.hasV2Preconditions()){let e=null;null!==this.ledgerbounds&&(e=new tl.LedgerBounds({minLedger:this.ledgerbounds.minLedger??0,maxLedger:this.ledgerbounds.maxLedger??0}));const t=this.minAccountSequence?tl.Int64.fromString(this.minAccountSequence):null,r=tl.Uint64.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),o=this.minAccountSequenceLedgerGap||0,s=null!==this.extraSigners?this.extraSigners.map(e=>tf.decodeAddress(e)):[];n.cond=tl.Preconditions.precondV2(new tl.PreconditionsV2({timeBounds:i,ledgerBounds:e,minSeqNum:t,minSeqAge:r,minSeqLedgerGap:o,extraSigners:s}))}else n.cond=tl.Preconditions.precondTime(i);if(n.sourceAccount=bh(this.source.accountId()),this.sorobanData){if(n.ext=new tl.TransactionExt(1,this.sorobanData),n.fee=new Hh(n.fee).plus(this.sorobanData.resourceFee().toString()).toNumber(),n.fee>gf)throw new Error(`Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (4294967295). Got ${n.fee}.`)}else n.ext=new tl.TransactionExt(0);const s=new tl.Transaction(n);s.operations(this.operations);const a=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:s,signatures:[]}));if(null===this.networkPassphrase)throw new Error("networkPassphrase must be set to build a transaction");const c=new Zp(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,i=new Hh(mf);let s=new Hh(0);const a=n.toEnvelope();switch(a.switch().value){case tl.EnvelopeType.envelopeTypeTx().value:{const e=a.v1().tx().ext().value();s=new Hh(e?.resourceFee().toString()??0);break}}const c=new Hh(n.fee).minus(s).div(o),u=new Hh(t);if(u.lt(c))throw new Error(`Invalid baseFee, it should be at least ${c.toString()} stroops.`);if(u.lt(i))throw new Error(`Invalid baseFee, it should be at least ${i.toString()} stroops.`);let l,d=n.toEnvelope();if(d.switch()===tl.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 tl.Transaction({sourceAccount:tl.MuxedAccount.keyTypeEd25519(e.sourceAccountEd25519()),fee:e.fee(),seqNum:e.seqNum(),cond:tl.Preconditions.precondTime(t),memo:e.memo(),operations:e.operations(),ext:new tl.TransactionExt(0)});d=tl.TransactionEnvelope.envelopeTypeTx(new tl.TransactionV1Envelope({tx:n,signatures:d.v0().signatures()}))}l="string"==typeof e?bh(e):e.xdrMuxedAccount();const h=new tl.FeeBumpTransaction({feeSource:l,fee:tl.Int64.fromString(u.times(o+1).plus(s).toString()),innerTx:tl.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new tl.FeeBumpTransactionExt(0)}),p=new tl.FeeBumpTransactionEnvelope({tx:h,signatures:[]}),f=tl.TransactionEnvelope.envelopeTypeTxFeeBump(p);return new Kp(f,r)}static fromXDR(e,t){return"string"==typeof e&&(e=tl.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===tl.EnvelopeType.envelopeTypeTxFeeBump()?new Kp(e,t):new Zp(e,t)}}function wf(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function bf(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 vf=(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))(vf||{});class Af{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 Sf(e){const t="function"==typeof e.contractId?e.contractId():null;return{...null!=t&&{contractId:ih.encodeContract(t)},type:e.type().name,topics:e.body().value().topics().map(e=>hf(e)),data:hf(e.body().value().data())}}function Tf(e){return e.map(e=>Sf("inSuccessfulContractCall"in e?e.event():e))}function Ef(e){return e instanceof ArrayBuffer?oo.Buffer.from(new Uint8Array(e)):oo.Buffer.from(e)}async function _f(e,t,n,r,o){if(e.credentials().switch().value===tl.SorobanCredentialsType.sorobanCredentialsSourceAccount().value)return e;const i=tl.SorobanAuthorizationEntry.fromXDR(e.toXDR()),s=i.credentials(),a=If(s);if(null===a)throw new Error(`unsupported credential type ${s.switch().name}`);a.signatureExpirationLedger(n);const c=Cf(i,n,r),u=$l(c.toXDR());let l,d;if("function"==typeof t){const e=await t(c);null!==e&&"object"==typeof e&&"signature"in e?(l=Ef(e.signature),d=e.publicKey):(l=Ef(e),d=Op.fromScAddress(a.address()).toString())}else l=Ef(t.sign(u)),d=t.publicKey();if(!lh.fromPublicKey(d).verify(u,l))throw new Error("signature doesn't match payload");const h=df({public_key:ih.decodeEd25519PublicKey(d),signature:l},{type:{public_key:["symbol",null],signature:["symbol",null]}}),p=tl.ScVal.scvVec([h]),f=void 0===o?[a]:function(e){switch(e.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return[e.address()];case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return[e.addressV2()];case tl.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[]}}(s).filter(e=>Op.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(p)),i}function kf(e){const{signer:t,validUntilLedgerSeq:n,invocation:r,networkPassphrase:o,publicKey:i="",authV2:s=!1}=e,a=lh.random().rawPublicKey(),c=new tl.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=i||(t instanceof lh?t.publicKey():null);if(!u)throw new Error("authorizeInvocation requires publicKey parameter");const l=new tl.SorobanAddressCredentials({address:new Op(u).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:tl.ScVal.scvVec([])});return _f(new tl.SorobanAuthorizationEntry({rootInvocation:r,credentials:s?tl.SorobanCredentials.sorobanCredentialsAddressV2(l):tl.SorobanCredentials.sorobanCredentialsAddress(l)}),t,n,o)}function Cf(e,t,n){const r=e.credentials(),o=If(r);if(null===o)throw new Error(`cannot build a signature payload for credential type ${r.switch().name}`);const i=$l(oo.Buffer.from(n));switch(r.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return tl.HashIdPreimage.envelopeTypeSorobanAuthorization(new tl.HashIdPreimageSorobanAuthorization({networkId:i,nonce:o.nonce(),invocation:e.rootInvocation(),signatureExpirationLedger:t}));case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:case tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return tl.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(new tl.HashIdPreimageSorobanAuthorizationWithAddress({networkId:i,nonce:o.nonce(),invocation:e.rootInvocation(),address:o.address(),signatureExpirationLedger:t}));default:throw new Error(`unsupported credential type ${r.switch().name}`)}}function Rf(e){const{entry:t,validUntilLedgerSeq:n,delegates:r,signature:o}=e,i=t.credentials(),s=If(i);if(null===s||i.switch().value===tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value)throw new Error(`buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${i.switch().name}`);return new tl.SorobanAuthorizationEntry({rootInvocation:t.rootInvocation(),credentials:tl.SorobanCredentials.sorobanCredentialsAddressWithDelegates(new tl.SorobanAddressCredentialsWithDelegates({addressCredentials:new tl.SorobanAddressCredentials({address:s.address(),nonce:s.nonce(),signatureExpirationLedger:n,signature:o??tl.ScVal.scvVoid()}),delegates:xf(r)}))})}function xf(e){const t=e.map(e=>new tl.SorobanDelegateSignature({address:new Op(e.address).toScAddress(),signature:e.signature??tl.ScVal.scvVoid(),nestedDelegates:xf(e.nestedDelegates??[])}));t.sort((e,t)=>oo.Buffer.compare(e.address().toXDR(),t.address().toXDR()));for(let e=1;e<t.length;e++)if(0===oo.Buffer.compare(t[e-1].address().toXDR(),t[e].address().toXDR()))throw new Error(`duplicate delegate address ${Op.fromScAddress(t[e].address()).toString()}`);return t}function If(e){switch(e.switch().value){case tl.SorobanCredentialsType.sorobanCredentialsAddress().value:return e.address();case tl.SorobanCredentialsType.sorobanCredentialsAddressV2().value:return e.addressV2();case tl.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:return e.addressWithDelegates().addressCredentials();default:return null}}function Bf(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:Op.fromScAddress(e.contractAddress()).toString(),function:e.functionName().toString(),args:e.args().map(e=>hf(e))};break}case 1:case 2:{const e=r,o=2===t.switch().value;n.type="create";const i={},[s,a]=[e.executable(),e.contractIdPreimage()];if(!!s.switch().value!=!!a.switch().value)throw new Error(`creation function appears invalid: ${JSON.stringify(r)} (should be wasm+address or token+asset)`);switch(s.switch().value){case 0:{const e=a.fromAddress();i.type="wasm",i.wasm={salt:oo.Buffer.from(e.salt()).toString("hex"),hash:s.wasmHash().toString("hex"),address:Op.fromScAddress(e.address()).toString(),...o&&{constructorArgs:r.constructorArgs().map(e=>hf(e))}};break}case 1:i.type="sac",i.asset=ph.fromOperation(a.fromAsset()).toString();break;default:throw new Error(`unknown creation type: ${JSON.stringify(s)}`)}n.args=i;break}default:throw new Error(`unknown invocation type (${t.switch().value}): ${JSON.stringify(t)}`)}return n.invocations=e.subInvocations().map(e=>Bf(e)),n}function Of(e,t){Pf(e,1,t)}function Pf(e,t,n,r){!1!==n(e,t,r)&&e.subInvocations().forEach(r=>Pf(r,t+1,n,e))}var Lf=Object.freeze({__proto__:null,Account:Xp,Address:Op,Asset:ph,AssetType:dh,AuthClawbackEnabledFlag:8,AuthImmutableFlag:4,AuthRequiredFlag:1,AuthRevocableFlag:2,BASE_FEE:mf,Claimant:yh,Contract:nf,FeeBumpTransaction:Kp,Hyper:el.Hyper,Int128:sf,Int256:af,Keypair:lh,LiquidityPoolAsset:mh,LiquidityPoolFeeV18:30,LiquidityPoolId:wh,Memo:Wp,MemoHash:Gp,MemoID:zp,MemoNone:Hp,MemoReturn:jp,MemoText:$p,MuxedAccount:Qp,Networks:vf,Operation:Vp,ScInt:uf,SignerKey:tf,Soroban:Af,SorobanDataBuilder:ef,StrKey:ih,TimeoutInfinite:0,Transaction:Zp,TransactionBase:gh,TransactionBuilder:yf,Uint128:rf,Uint256:of,UnsignedHyper:el.UnsignedHyper,XdrLargeInt:cf,authorizeEntry:_f,authorizeInvocation:kf,buildAuthorizationEntryPreimage:Cf,buildInvocationTree:Bf,buildWithDelegatesEntry:Rf,cereal:nl,decodeAddressToMuxedAccount:bh,encodeMuxedAccount:Ah,encodeMuxedAccountToAddress:vh,extractBaseAddress:Sh,getLiquidityPoolId:fh,hash:$l,humanizeEvents:Tf,nativeToScVal:df,scValToBigInt:lf,scValToNative:hf,scvSortedMap:pf,sign:Kd,verify:Xd,walkInvocationTree:Of,xdr:tl});function Uf(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 Nf=102400;class Ff{serverURL;domain;timeout;static async resolve(e,t={}){if(e.indexOf("*")<0)return ih.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 Ff.createForDomain(r,t)).resolveAddress(e)}static async createForDomain(e,t={}){Uf(e);const n=await Xu.resolve(e,t);return n.FEDERATION_SERVER?new Ff(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,Uf(t);const r=void 0===n.allowHttp?Ru.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?Ru.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 bu.get(e.toString(),{maxContentLength:Nf,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 Eu(`Server query failed. Server responded: ${e.status} ${e.statusText}`,e.data))})}}var Df=Object.freeze({__proto__:null,FEDERATION_RESPONSE_MAX_SIZE:Nf,Server:Ff});class Mf extends Error{}function Vf(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=lh.fromPublicKey(e)}catch(e){throw new Mf(`Signer is not a valid address: ${e.message}`)}for(let i=0;i<r.length;i++){const s=r[i];if(s.hint().equals(t.signatureHint())&&t.verify(n,s.signature())){o.add(e),r.splice(i,1);break}}}return Array.from(o)}function qf(e,t){return 0!==Vf(e,[t]).length}const Hf=Object.prototype.toString;function zf(e){return function(e,t,n){return!!e&&(e.constructor===t||Hf.call(e)===n)}(e,Uint8Array,"[object Uint8Array]")}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder;function $f(e,{urlSafe:t=!1}={}){!function(e){if(!zf(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 Gf(e,t,n,r,o){if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");let i;try{i=new Zp(e,n)}catch{try{i=new Kp(e,n)}catch{throw new Mf("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new Mf("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(i.sequence,10))throw new Mf("The transaction sequence number should be zero");if(i.source!==t)throw new Mf("The transaction source account is not equal to the server's account");if(i.operations.length<1)throw new Mf("The transaction should contain at least one operation");const[s,...a]=i.operations;if(!s.source)throw new Mf("The transaction's operation should contain a source account");const c=s.source;let u,l=null;if(i.memo.type!==Hp){if(c.startsWith("M"))throw new Mf("The transaction has a memo but the client account ID is a muxed account");if(i.memo.type!==zp)throw new Mf("The transaction's memo must be of type `id`");l=i.memo.value}if("manageData"!==s.type)throw new Mf("The transaction's operation type should be 'manageData'");if(i.timeBounds&&0===Number.parseInt(i.timeBounds?.maxTime,10))throw new Mf("The transaction requires non-infinite timebounds");if(!xu.validateTimebounds(i,300))throw new Mf("The transaction has expired");if(void 0===s.value)throw new Mf("The transaction's operation values should not be null");if(!s.value)throw new Mf("The transaction's operation value should not be null");if(48!==oo.Buffer.from(s.value.toString(),"base64").length)throw new Mf("The transaction's operation value should be a 64 bytes base64 random string");if(!r)throw new Mf("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof r)`${r} auth`===s.name&&(u=r);else{if(!Array.isArray(r))throw new Mf(`Invalid homeDomains: homeDomains type is ${typeof r} but should be a string or an array`);u=r.find(e=>`${e} auth`===s.name)}if(!u)throw new Mf("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 Mf("The transaction has operations that are not of type 'manageData'");if(e.source!==t&&"client_domain"!==e.name)throw new Mf("The transaction has operations that are unrecognized");if("web_auth_domain"===e.name){if(void 0===e.value)throw new Mf("'web_auth_domain' operation value should not be null");if(e.value.compare(oo.Buffer.from(o)))throw new Mf(`'web_auth_domain' operation value does not match ${o}`)}}if(!qf(i,t))throw new Mf(`Transaction not signed by server: '${t}'`);return{tx:i,clientAccountID:c,matchedHomeDomain:u,memo:l}}function jf(e,t,n,r,o,i){const{tx:s}=Gf(e,t,n,o,i);let a;try{a=lh.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 Mf("No verifiable client signers provided, at least one G... address must be provided");let u;for(const e of s.operations)if("manageData"===e.type&&"client_domain"===e.name){if(u)throw new Mf("Found more than one client_domain operation");u=e.source}const l=[a.publicKey(),...Array.from(c)];u&&l.push(u);const d=Vf(s,l);let h=!1,p=!1;for(const e of d)e===a.publicKey()&&(h=!0),e===u&&(p=!0);if(!h)throw new Mf(`Transaction not signed by server: '${a.publicKey()}'`);if(u&&!p)throw new Mf("Transaction not signed by the source account of the 'client_domain' ManageData operation");if(1===d.length)throw new Mf("None of the given signers match the transaction signatures");if(d.length!==s.signatures.length)throw new Mf("Transaction has unrecognized signatures");if(d.splice(d.indexOf(a.publicKey()),1),u&&d.splice(d.indexOf(u),1),0===d.length)throw new Mf("None of the given signers match the transaction signatures");return d}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var Wf,Zf,Kf,Xf,Yf,Jf=Object.freeze({__proto__:null,InvalidChallengeError:Mf,buildChallengeTx:function(e,t,n,r=300,o,i,s=null,a=null,c=null){if(t.startsWith("M")&&s)throw Error("memo cannot be used if clientAccountID is a muxed account");const u=new Xp(e.publicKey(),"-1"),l=Math.floor(Date.now()/1e3),d=$f(crypto.getRandomValues(new Uint8Array(48))),h=new yf(u,{fee:mf,networkPassphrase:o,timebounds:{minTime:l,maxTime:l+r}}).addOperation(Vp.manageData({name:`${n} auth`,value:d,source:t})).addOperation(Vp.manageData({name:"web_auth_domain",value:i,source:u.accountId()}));if(a){if(!c)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(Vp.manageData({name:"client_domain",value:a,source:c}))}s&&h.addMemo(Wp.id(s));const p=h.build();return p.sign(e),p.toEnvelope().toXDR("base64").toString()},gatherTxSigners:Vf,readChallengeTx:Gf,verifyChallengeTxSigners:jf,verifyChallengeTxThreshold:function(e,t,n,r,o,i,s){const a=jf(e,t,n,o.map(e=>e.key),i,s);let c=0;for(const e of a){c+=o.find(t=>t.key===e)?.weight||0}if(c<r)throw new Mf(`signers with weight ${c} do not meet threshold ${r}"`);return a},verifyTxSignedBy:qf}),Qf=Object.freeze({__proto__:null});((Zf=Wf||(Wf={})).LiquidityPoolType||(Zf.LiquidityPoolType={})).constantProduct="constant_product",(Kf=Zf.OperationResponseType||(Zf.OperationResponseType={})).createAccount="create_account",Kf.payment="payment",Kf.pathPayment="path_payment_strict_receive",Kf.createPassiveOffer="create_passive_sell_offer",Kf.manageOffer="manage_sell_offer",Kf.setOptions="set_options",Kf.changeTrust="change_trust",Kf.allowTrust="allow_trust",Kf.accountMerge="account_merge",Kf.inflation="inflation",Kf.manageData="manage_data",Kf.bumpSequence="bump_sequence",Kf.manageBuyOffer="manage_buy_offer",Kf.pathPaymentStrictSend="path_payment_strict_send",Kf.createClaimableBalance="create_claimable_balance",Kf.claimClaimableBalance="claim_claimable_balance",Kf.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",Kf.endSponsoringFutureReserves="end_sponsoring_future_reserves",Kf.revokeSponsorship="revoke_sponsorship",Kf.clawback="clawback",Kf.clawbackClaimableBalance="clawback_claimable_balance",Kf.setTrustLineFlags="set_trust_line_flags",Kf.liquidityPoolDeposit="liquidity_pool_deposit",Kf.liquidityPoolWithdraw="liquidity_pool_withdraw",Kf.invokeHostFunction="invoke_host_function",Kf.bumpFootprintExpiration="bump_footprint_expiration",Kf.restoreFootprint="restore_footprint",(Xf=Zf.OperationResponseTypeI||(Zf.OperationResponseTypeI={}))[Xf.createAccount=0]="createAccount",Xf[Xf.payment=1]="payment",Xf[Xf.pathPayment=2]="pathPayment",Xf[Xf.createPassiveOffer=3]="createPassiveOffer",Xf[Xf.manageOffer=4]="manageOffer",Xf[Xf.setOptions=5]="setOptions",Xf[Xf.changeTrust=6]="changeTrust",Xf[Xf.allowTrust=7]="allowTrust",Xf[Xf.accountMerge=8]="accountMerge",Xf[Xf.inflation=9]="inflation",Xf[Xf.manageData=10]="manageData",Xf[Xf.bumpSequence=11]="bumpSequence",Xf[Xf.manageBuyOffer=12]="manageBuyOffer",Xf[Xf.pathPaymentStrictSend=13]="pathPaymentStrictSend",Xf[Xf.createClaimableBalance=14]="createClaimableBalance",Xf[Xf.claimClaimableBalance=15]="claimClaimableBalance",Xf[Xf.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",Xf[Xf.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",Xf[Xf.revokeSponsorship=18]="revokeSponsorship",Xf[Xf.clawback=19]="clawback",Xf[Xf.clawbackClaimableBalance=20]="clawbackClaimableBalance",Xf[Xf.setTrustLineFlags=21]="setTrustLineFlags",Xf[Xf.liquidityPoolDeposit=22]="liquidityPoolDeposit",Xf[Xf.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",Xf[Xf.invokeHostFunction=24]="invokeHostFunction",Xf[Xf.bumpFootprintExpiration=25]="bumpFootprintExpiration",Xf[Xf.restoreFootprint=26]="restoreFootprint",(Yf=Zf.TransactionFailedResultCodes||(Zf.TransactionFailedResultCodes={})).TX_FAILED="tx_failed",Yf.TX_BAD_SEQ="tx_bad_seq",Yf.TX_BAD_AUTH="tx_bad_auth",Yf.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",Yf.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",Yf.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",Yf.TX_NOT_SUPPORTED="tx_not_supported",Yf.TX_SUCCESS="tx_success",Yf.TX_TOO_EARLY="tx_too_early",Yf.TX_TOO_LATE="tx_too_late",Yf.TX_MISSING_OPERATION="tx_missing_operation",Yf.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",Yf.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",Yf.TX_INSUFFICIENT_FEE="tx_insufficient_fee",Yf.TX_INTERNAL_ERROR="tx_internal_error";var eg,tg,ng,rg=(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))(rg||{});(tg=eg||(eg={})).EffectType=rg,(ng=tg.TradeType||(tg.TradeType={})).all="all",ng.liquidityPools="liquidity_pool",ng.orderbook="orderbook",Wf.OperationResponseType,Wf.OperationResponseTypeI;class og{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 Xp(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 ig 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 sg=32;function ag(e){}function cg(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=ag,onError:n=ag,onRetry:r=ag,onComment:o}=e,i=[];let s,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:s,event:a,data:u}),s=void 0,u="",l=0,a=void 0,n=r+1,r=e.indexOf("\n",n);continue}const o=e.charCodeAt(n);if(ug(e,n,o)){const o=e.charCodeAt(n+5)===sg?n+6:n+5,i=e.slice(o,r);if(0===l&&10===e.charCodeAt(r+1)){t({id:s,event:a,data:i}),s=void 0,u="",a=void 0,n=r+2,r=e.indexOf("\n",n);continue}u=0===l?i:`${u}\n${i}`,l++}else lg(e,n,o)?a=e.slice(e.charCodeAt(n+6)===sg?n+7:n+6,r)||void 0:h(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;h(e,n,o),n=o+1,13===e.charCodeAt(n-1)&&10===e.charCodeAt(n)&&n++}return e.slice(n)}function h(e,n,r){if(n===r)return l>0&&t({id:s,event:a,data:u}),s=void 0,u="",l=0,void(a=void 0);const i=e.charCodeAt(n);if(ug(e,n,i)){const t=e.charCodeAt(n+5)===sg?n+6:n+5,o=e.slice(t,r);return u=0===l?o:`${u}\n${o}`,void l++}if(lg(e,n,i))return void(a=e.slice(e.charCodeAt(n+6)===sg?n+7:n+6,r)||void 0);if(105===i&&100===e.charCodeAt(n+1)&&58===e.charCodeAt(n+2)){const t=e.slice(e.charCodeAt(n+3)===sg?n+4:n+3,r);return void(s=t.includes("\0")?void 0:t)}if(58===i){if(o){const t=e.slice(n,r);o(t.slice(e.charCodeAt(n+1)===sg?2:1))}return}const c=e.slice(n,r),d=c.indexOf(":");if(-1===d)return void p(c,"",c);const h=c.slice(0,d),f=c.charCodeAt(d+1)===sg?2:1;p(h,c.slice(d+f),c)}function p(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":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new ig(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new ig(`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===i.length){const t=d(e);return void(""!==t&&i.push(t))}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return void i.push(e);i.push(e);const t=i.join("");i.length=0;const n=d(t);""!==n&&i.push(n)},reset:function(e={}){if(e.consume&&i.length>0){const e=i.join("");h(e,0,e.length)}c=!0,s=void 0,u="",l=0,a=void 0,i.length=0}}}function ug(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 lg(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 dg 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(pg(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(pg(this),t)}}function hg(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(hg).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${hg(e.cause)}`:e.message:`${e}`}function pg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var fg,gg,mg,yg,wg,bg,vg,Ag,Sg,Tg,Eg,_g,kg,Cg,Rg,xg,Ig,Bg,Og,Pg,Lg,Ug,Ng,Fg=e=>{throw TypeError(e)},Dg=(e,t,n)=>t.has(e)||Fg("Cannot "+n),Mg=(e,t,n)=>(Dg(e,t,"read from private field"),n?n.call(e):t.get(e)),Vg=(e,t,n)=>t.has(e)?Fg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),qg=(e,t,n,r)=>(Dg(e,t,"write to private field"),t.set(e,n),n),Hg=(e,t,n)=>(Dg(e,t,"access private method"),n);class zg extends EventTarget{constructor(e,t){var n,r;super(),Vg(this,Cg),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Vg(this,fg),Vg(this,gg),Vg(this,mg),Vg(this,yg),Vg(this,wg),Vg(this,bg),Vg(this,vg),Vg(this,Ag,null),Vg(this,Sg),Vg(this,Tg),Vg(this,Eg,null),Vg(this,_g,null),Vg(this,kg,null),Vg(this,xg,async e=>{var t;Mg(this,Tg).reset();const{body:n,redirected:r,status:o,headers:i}=e;if(204===o)return Hg(this,Cg,Lg).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(qg(this,mg,r?new URL(e.url):void 0),200!==o)return void Hg(this,Cg,Lg).call(this,`Non-200 status code (${o})`,o);if(!(i.get("content-type")||"").startsWith("text/event-stream"))return void Hg(this,Cg,Lg).call(this,'Invalid content type, expected "text/event-stream"',o);if(Mg(this,fg)===this.CLOSED)return;qg(this,fg,this.OPEN);const s=new Event("open");if(null==(t=Mg(this,kg))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof n||!n||!("getReader"in n))return Hg(this,Cg,Lg).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&&Mg(this,Tg).feed(a.decode(t,{stream:!e})),e&&(u=!1,Mg(this,Tg).reset(),Hg(this,Cg,Ug).call(this))}while(u)}),Vg(this,Ig,e=>{qg(this,Sg,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&Hg(this,Cg,Ug).call(this,hg(e))}),Vg(this,Og,e=>{"string"==typeof e.id&&qg(this,Ag,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:Mg(this,mg)?Mg(this,mg).origin:Mg(this,gg).origin,lastEventId:e.id||""});Mg(this,_g)&&(!e.event||"message"===e.event)&&Mg(this,_g).call(this,t),this.dispatchEvent(t)}),Vg(this,Pg,e=>{qg(this,bg,e)}),Vg(this,Ng,()=>{qg(this,vg,void 0),Mg(this,fg)===this.CONNECTING&&Hg(this,Cg,Rg).call(this)});try{if(e instanceof URL)qg(this,gg,e);else{if("string"!=typeof e)throw new Error("Invalid URL");qg(this,gg,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")}qg(this,Tg,cg({onEvent:Mg(this,Og),onRetry:Mg(this,Pg)})),qg(this,fg,this.CONNECTING),qg(this,bg,3e3),qg(this,wg,null!=(n=null==t?void 0:t.fetch)?n:globalThis.fetch),qg(this,yg,null!=(r=null==t?void 0:t.withCredentials)&&r),Hg(this,Cg,Rg).call(this)}get readyState(){return Mg(this,fg)}get url(){return Mg(this,gg).href}get withCredentials(){return Mg(this,yg)}get onerror(){return Mg(this,Eg)}set onerror(e){qg(this,Eg,e)}get onmessage(){return Mg(this,_g)}set onmessage(e){qg(this,_g,e)}get onopen(){return Mg(this,kg)}set onopen(e){qg(this,kg,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(){Mg(this,vg)&&clearTimeout(Mg(this,vg)),Mg(this,fg)!==this.CLOSED&&(Mg(this,Sg)&&Mg(this,Sg).abort(),qg(this,fg,this.CLOSED),qg(this,Sg,void 0))}}fg=new WeakMap,gg=new WeakMap,mg=new WeakMap,yg=new WeakMap,wg=new WeakMap,bg=new WeakMap,vg=new WeakMap,Ag=new WeakMap,Sg=new WeakMap,Tg=new WeakMap,Eg=new WeakMap,_g=new WeakMap,kg=new WeakMap,Cg=new WeakSet,Rg=function(){qg(this,fg,this.CONNECTING),qg(this,Sg,new AbortController),Mg(this,wg)(Mg(this,gg),Hg(this,Cg,Bg).call(this)).then(Mg(this,xg)).catch(Mg(this,Ig))},xg=new WeakMap,Ig=new WeakMap,Bg=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Mg(this,Ag)?{"Last-Event-ID":Mg(this,Ag)}:void 0},cache:"no-store",signal:null==(e=Mg(this,Sg))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Og=new WeakMap,Pg=new WeakMap,Lg=function(e,t){var n;Mg(this,fg)!==this.CLOSED&&qg(this,fg,this.CLOSED);const r=new dg("error",{code:t,message:e});null==(n=Mg(this,Eg))||n.call(this,r),this.dispatchEvent(r)},Ug=function(e,t){var n;if(Mg(this,fg)===this.CLOSED)return;qg(this,fg,this.CONNECTING);const r=new dg("error",{code:t,message:e});null==(n=Mg(this,Eg))||n.call(this,r),this.dispatchEvent(r),qg(this,vg,setTimeout(Mg(this,Ng),Mg(this,bg)))},Ng=new WeakMap,zg.CONNECTING=0,zg.OPEN=1,zg.CLOSED=2,Object.defineProperty(zg,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});const $g="16.0.1",Gg={};function jg(e){return Math.floor(e/1e3)}function Wg(e){const t=Gg[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;const{serverTime:n,localTimeRecorded:r}=t,o=jg((new Date).getTime());return o-r>300?null:o-r+n}function Zg(e){return Array.isArray(e)?e.join(","):e.toString()}const Kg=["transaction"];class Xg{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",$g);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 i=()=>{o=setTimeout(()=>{r?.close(),r=s()},e.reconnectTimeout||15e3)},s=()=>{try{r=new zg(t.toString())}catch(t){e.onerror&&e.onerror(t)}if(i(),!r)return r;let n=!1;const a=()=>{n||(clearTimeout(o),r.close(),s(),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),i(),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 s(),()=>{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 Tu("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(Zg(r))}),i=new URL(o,n);return r.forEach(e=>{const n=t[e];void 0!==n&&i.searchParams.set(e,Zg(n))}),i.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&&Kg.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 Su(e.response.statusText??"Not Found",e.response.data)):Promise.reject(new Au(e.response.statusText??"Unknown",e.response.data)):Promise.reject(new Error(e.message))}}class Yg extends Xg{constructor(e,t){super(e,t),this.setPath("accounts")}accountId(e){const t=new Xg(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 Jg extends Xg{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 Qg extends Xg{constructor(e,t){super(e,t),this.setPath("claimable_balances")}claimableBalance(e){const t=new Xg(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 em extends Xg{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 tm extends Xg{constructor(e,t,n){super(e,t),this.setPath("friendbot"),this.url.searchParams.set("addr",n)}}class nm extends Xg{constructor(e,t){super(e,t),this.setPath("ledgers")}ledger(e){return this.filter.push(["ledgers",e.toString()]),this}}class rm extends Xg{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 Xg(new URL(this.url),this.httpClient);return t.filter.push([e.toLowerCase()]),t}}class om extends Xg{constructor(e,t){super(e,t,"offers"),this.setPath("offers")}offer(e){const t=new Xg(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 im extends Xg{constructor(e,t){super(e,t,"operations"),this.setPath("operations")}operation(e){const t=new Xg(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 sm extends Xg{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 i=r.getIssuer();r.isNative()||void 0===i?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",i))}}class am extends Xg{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 cm extends Xg{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 i=r.getIssuer();r.isNative()||void 0===i?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",i))}}class um extends Xg{constructor(e,t,n,r,o){super(e,t),this.setPath("paths/strict-send");const i=n.getIssuer();if(n.isNative()?this.url.searchParams.set("source_asset_type","native"):void 0!==i&&(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",i)),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 lm=[6e4,3e5,9e5,36e5,864e5,6048e5];class dm extends Xg{constructor(e,t,n,r,o,i,s,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 i)throw new Tu("Invalid time bounds",[o,i]);if(this.url.searchParams.set("start_time",o.toString()),this.url.searchParams.set("end_time",i.toString()),!this.isValidResolution(s))throw new Tu("Invalid resolution",s);if(this.url.searchParams.set("resolution",s.toString()),!this.isValidOffset(a,s))throw new Tu("Invalid offset",a);this.url.searchParams.set("offset",a.toString())}isValidResolution(e){return lm.some(t=>t===e)}isValidOffset(e,t){const n=36e5;return!(e>t||e>=24*n||e%n!==0)}}class hm extends Xg{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 pm extends Xg{constructor(e,t){super(e,t,"transactions"),this.setPath("transactions")}transaction(e){const t=new Xg(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 fm(e){return new Hh(e).div(1e7).toString()}var gm,mm=Object.freeze({__proto__:null,AccountResponse:og,get HorizonApi(){return Wf},SERVER_TIME_MAP:Gg,Server:class{serverURL;httpClient;constructor(e,t={}){this.serverURL=new URL(e);const n=void 0===t.allowHttp?Ru.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=vu({headers:{...e,"X-Client-Name":"js-stellar-sdk","X-Client-Version":$g}});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 i=0;if(e.headers instanceof Headers){const t=e.headers.get("date");t&&(i=jg(Date.parse(t)))}else if("object"==typeof e.headers&&"date"in e.headers){const t=e.headers;"string"==typeof t.date&&(i=jg(Date.parse(t.date)))}const s=jg((new Date).getTime());return Number.isNaN(i)||(Gg[o]={serverTime:i,localTimeRecorded:s}),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=Wg(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 Xg(this.serverURL,this.httpClient);return e.filter.push(["fee_stats"]),e.call()}async root(){return new Xg(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=tl.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 Hh(0),o=new Hh(0);const i=e.value().value().success(),s=i.offersClaimed().map(e=>{const t=e.value();let r="";switch(e.switch()){case tl.ClaimAtomType.claimAtomTypeV0():r=ih.encodeEd25519PublicKey(t.sellerEd25519());break;case tl.ClaimAtomType.claimAtomTypeOrderBook():r=ih.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error(`Invalid offer result type: ${e.switch()}`)}const i=new Hh(t.amountBought().toString()),s=new Hh(t.amountSold().toString());n=n.plus(s),o=o.plus(i);const a=ph.fromOperation(t.assetSold()),c=ph.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:fm(s),assetBought:l,amountBought:fm(i)}}),a=i.offer().switch().name;let c;if("function"==typeof i.offer().value&&i.offer().value()){const e=i.offer().value();c={offerId:e.offerId().toString(),selling:{},buying:{},amount:fm(e.amount().toString()),price:{n:e.price().n(),d:e.price().d()}};const t=ph.fromOperation(e.selling());c.selling={type:t.getAssetType(),assetCode:t.getCode(),issuer:t.getIssuer()};const n=ph.fromOperation(e.buying());c.buying={type:n.getAssetType(),assetCode:n.getCode(),issuer:n.getIssuer()}}return{offersClaimed:s,effect:a,operationIndex:t,currentOffer:c,amountBought:fm(n),amountSold:fm(o),isFullyOpen:!s.length&&"manageOfferDeleted"!==a,wasPartiallyFilled:!!s.length&&"manageOfferDeleted"!==a,wasImmediatelyFilled:!!s.length&&"manageOfferDeleted"===a,wasImmediatelyDeleted:!s.length&&"manageOfferDeleted"===a}}).filter(e=>!!e)),{...e.data,offerResults:r?n:void 0}}).catch(e=>e instanceof Error?Promise.reject(e):Promise.reject(new Eu(`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 Eu(`Transaction submission failed. Server responded: ${e.status} ${e.statusText}`,e.data)))}accounts(){return new Yg(this.serverURL,this.httpClient)}claimableBalances(){return new Qg(this.serverURL,this.httpClient)}ledgers(){return new nm(this.serverURL,this.httpClient)}transactions(){return new pm(this.serverURL,this.httpClient)}offers(){return new om(this.serverURL,this.httpClient)}orderbook(e,t){return new sm(this.serverURL,this.httpClient,e,t)}trades(){return new hm(this.serverURL,this.httpClient)}operations(){return new im(this.serverURL,this.httpClient)}liquidityPools(){return new rm(this.serverURL,this.httpClient)}strictReceivePaths(e,t,n){return new cm(this.serverURL,this.httpClient,e,t,n)}strictSendPaths(e,t,n){return new um(this.serverURL,this.httpClient,e,t,n)}payments(){return new am(this.serverURL,this.httpClient)}effects(){return new em(this.serverURL,this.httpClient)}friendbot(e){return new tm(this.serverURL,this.httpClient,e)}assets(){return new Jg(this.serverURL,this.httpClient)}async loadAccount(e){const t=await this.accounts().accountId(e).call();return new og(t)}tradeAggregation(e,t,n,r,o,i){return new dm(this.serverURL,this.httpClient,e,t,n,r,o,i)}async checkMemoRequired(e){if(e instanceof Kp&&(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 _u("account requires memo",o,n)}catch(e){if(e instanceof _u)throw e;if(!(e instanceof Su))throw e;continue}}}},get ServerApi(){return eg},getCurrentServerTime:Wg});(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}})(gm||(gm={}));async function ym(e,t,n,r=null){const o=await e.post(t,{jsonrpc:"2.0",id:1,method:n,params:r});if(i=o.data,s="error",Object.prototype.hasOwnProperty.call(i,s))throw o.data.error;return o.data?.result;var i,s}function wm(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=>tl.DiagnosticEvent.fromXDR(e,"base64"))},errorResult:tl.TransactionResult.fromXDR(t,"base64")}:{...e}}function bm(e){const t=tl.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),n={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:tl.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:tl.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:t,events:{contractEventsXdr:(e.events?.contractEventsXdr??[]).map(e=>e.map(e=>tl.ContractEvent.fromXDR(e,"base64"))),transactionEventsXdr:(e.events?.transactionEventsXdr??[]).map(e=>tl.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=>tl.DiagnosticEvent.fromXDR(e,"base64"))),n}function vm(e){return{status:e.status,txHash:e.txHash,...bm(e)}}function Am(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 nf(e.contractId)},topic:(e.topic??[]).map(e=>tl.ScVal.fromXDR(e,"base64")),value:tl.ScVal.fromXDR(e.value,"base64")}})}}function Sm(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:tl.LedgerKey.fromXDR(e.key,"base64"),val:tl.LedgerEntryData.fromXDR(e.xdr,"base64"),...void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq}}})}}function Tm(e){if(!gm.isSimulationRaw(e))return e;const t={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:e.events?.map(e=>tl.DiagnosticEvent.fromXDR(e,"base64"))??[]};return"string"==typeof e.error?{...t,error:e.error}:function(e,t){const n={...t,transactionData:new ef(e.transactionData),minResourceFee:e.minResourceFee,...(e.results?.length??0)>0&&{result:e.results.map(e=>({auth:(e.auth??[]).map(e=>tl.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:e.xdr?tl.ScVal.fromXDR(e.xdr,"base64"):tl.ScVal.scvVoid()}))[0]},...(e.stateChanges?.length??0)>0&&{stateChanges:e.stateChanges?.map(e=>({type:e.type,key:tl.LedgerKey.fromXDR(e.key,"base64"),before:e.before?tl.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?tl.LedgerEntry.fromXDR(e.after,"base64"):null}))}};return e.restorePreamble&&""!==e.restorePreamble.transactionData?{...n,restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new ef(e.restorePreamble.transactionData)}}:n}(e,t)}function Em(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=tl.LedgerCloseMeta.fromXDR(e.metadataXdr,"base64"),n=tl.LedgerHeaderHistoryEntry.fromXDR(e.headerXdr,"base64");return{hash:e.hash,sequence:e.sequence,ledgerCloseTime:e.ledgerCloseTime,metadataXdr:t,headerXdr:n}}function _m(e){const t=tl.LedgerHeader.fromXDR(e.headerXdr,"base64"),n=tl.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 km(e,t){if("innerTransaction"in e)return km(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=Tm(t);if(!gm.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 i=yf.cloneFrom(e,{fee:r.toString(),sorobanData:n.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){i.clearOperations();const t=e.operations[0],r=t.auth??[];i.addOperation(Vp.invokeHostFunction({source:t.source,func:t.func,auth:r.length>0?r:n.result.auth}))}return i}var Cm=(e=>(e.Temporary="temporary",e.Persistent="persistent",e))(Cm||{});const Rm=e=>1e3;class xm{serverURL;httpClient;constructor(e,t={}){var n;if(this.serverURL=new URL(e),this.httpClient=(n=t.headers,vu({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 Xp(e,t.seqNum().toString())}async getAccountEntry(e){const t=tl.LedgerKey.account(new tl.LedgerKeyAccount({accountId:lh.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=tl.LedgerKey.trustline(new tl.LedgerKeyTrustLine({accountId:lh.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(ih.isValidClaimableBalance(e)){const n=ih.decodeClaimableBalance(e),r=oo.Buffer.concat([oo.Buffer.from("\0\0\0"),n.subarray(0,1)]);t=tl.ClaimableBalanceId.fromXDR(oo.Buffer.concat([r,n.subarray(1)]))}else if(e.match(/[a-f0-9]{72}/i))t=tl.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=tl.ClaimableBalanceId.fromXDR(e.padStart(72,"0"),"hex")}const n=tl.LedgerKey.claimableBalance(new tl.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 Op)r=e.toString();else{if(!(e instanceof nf))throw new TypeError(`invalid address: ${e}`);r=e.toString()}if(ih.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(ih.isValidContract(r))return this.getSACBalance(r,t,n);throw new Error(`invalid address: ${e}`)}async getHealth(){return ym(this.httpClient,this.serverURL.toString(),"getHealth")}async getContractData(e,t,n="persistent"){let r,o;if("string"==typeof e)r=new nf(e).address().toScAddress();else if(e instanceof Op)r=e.toScAddress();else{if(!(e instanceof nf))throw new TypeError(`unknown contract type: ${e}`);r=e.address().toScAddress()}switch(n){case"temporary":o=tl.ContractDataDurability.temporary();break;case"persistent":o=tl.ContractDataDurability.persistent();break;default:throw new TypeError(`invalid durability: ${n}`)}const i=tl.LedgerKey.contractData(new tl.LedgerKeyContractData({key:t,contract:r,durability:o}));try{return await this.getLedgerEntry(i)}catch{throw{code:404,message:`Contract data not found for ${Op.fromScAddress(r).toString()} with key ${t.toXDR("base64")} and durability: ${n}`}}}async getContractWasmByContractId(e){const t=new nf(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?oo.Buffer.from(e,t):e,r=tl.LedgerKey.contractCode(new tl.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(Sm)}_getLedgerEntries(...e){return ym(this.httpClient,this.serverURL.toString(),"getLedgerEntries",{keys:e.map(e=>e.toXDR("base64"))})}async getLedgerEntry(e){const t=await this._getLedgerEntries(e).then(Sm);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!==gm.GetTransactionStatus.NOT_FOUND)return r;await xu.sleep((t?.sleepStrategy??Rm)(o))}return r}async getTransaction(e){return this._getTransaction(e).then(t=>{const n={};t.status!==gm.GetTransactionStatus.NOT_FOUND&&Object.assign(n,bm(t));return{status:t.status,txHash:e,latestLedger:t.latestLedger,latestLedgerCloseTime:t.latestLedgerCloseTime,oldestLedger:t.oldestLedger,oldestLedgerCloseTime:t.oldestLedgerCloseTime,...n}})}async _getTransaction(e){return ym(this.httpClient,this.serverURL.toString(),"getTransaction",{hash:e})}async getTransactions(e){return this._getTransactions(e).then(e=>({transactions:(e.transactions||[]).map(vm),latestLedger:e.latestLedger,latestLedgerCloseTimestamp:e.latestLedgerCloseTimestamp,oldestLedger:e.oldestLedger,oldestLedgerCloseTimestamp:e.oldestLedgerCloseTimestamp,cursor:e.cursor}))}async _getTransactions(e){return ym(this.httpClient,this.serverURL.toString(),"getTransactions",e)}async getEvents(e){return this._getEvents(e).then(Am)}async _getEvents(e){return ym(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 ym(this.httpClient,this.serverURL.toString(),"getNetwork")}async getLatestLedger(){return this._getLatestLedger().then(_m)}async _getLatestLedger(){return ym(this.httpClient,this.serverURL.toString(),"getLatestLedger")}async simulateTransaction(e,t,n){return this._simulateTransaction(e,t,n).then(Tm)}async _simulateTransaction(e,t,n){return ym(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(gm.isSimulationError(t))throw new Error(t.error);return km(e,t).build()}async sendTransaction(e){return this._sendTransaction(e).then(wm)}async _sendTransaction(e){return ym(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=tl.TransactionMeta.fromXDR(r.data.result_meta_xdr,"base64");else{const t=await this.getTransaction(r.data.hash);if(t.status!==gm.GetTransactionStatus.SUCCESS)throw new Error(`Funding account ${e} failed`);o=t.resultMetaXdr}const i=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()===tl.LedgerEntryChangeType.ledgerEntryCreated()&&e.created().data().switch()===tl.LedgerEntryType.account())?.created()?.data()?.account()?.seqNum()?.toString();if(n)return n;throw new Error("No account created in transaction")}(o);return new Xp(n,i)}catch(e){if(400===e.response?.status&&e.response.data?.detail?.includes("createAccountAlreadyExist"))return this.getAccount(n);throw e}}async fundAddress(e,t){if(!ih.isValidEd25519PublicKey(e)&&!ih.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!==gm.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 ym(this.httpClient,this.serverURL.toString(),"getFeeStats")}async getVersionInfo(){return ym(this.httpClient,this.serverURL.toString(),"getVersionInfo")}async getSACBalance(e,t,n){const r=e instanceof Op?e.toString():e;if(!ih.isValidContract(r))throw new TypeError(`expected contract ID, got ${r}`);const o=n??await this.getNetwork().then(e=>e.passphrase),i=t.contractId(o),s=df(["Balance",r],{type:["symbol","address"]}),a=tl.LedgerKey.contractData(new tl.LedgerKeyContractData({contract:new Op(i).toScAddress(),durability:tl.ContractDataDurability.persistent(),key:s})),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!==tl.LedgerEntryType.contractData().value)return{latestLedger:c.latestLedger};const h=hf(d.contractData().val());return{latestLedger:c.latestLedger,balanceEntry:{liveUntilLedgerSeq:l,lastModifiedLedgerSeq:u,amount:h.amount.toString(),authorized:h.authorized,clawback:h.clawback}}}async getLedgers(e){return this._getLedgers(e).then(e=>({ledgers:(e.ledgers||[]).map(Em),latestLedger:e.latestLedger,latestLedgerCloseTime:e.latestLedgerCloseTime,oldestLedger:e.oldestLedger,oldestLedgerCloseTime:e.oldestLedgerCloseTime,cursor:e.cursor}))}async _getLedgers(e){return ym(this.httpClient,this.serverURL.toString(),"getLedgers",e)}}var Im=Object.freeze({__proto__:null,get Api(){return gm},BasicSleepStrategy:Rm,Durability:Cm,LinearSleepStrategy:e=>1e3*e,Server:xm,assembleTransaction:km,parseRawEvents:Am,parseRawSimulation:Tm});class Bm{constructor(e){this.value=e}value;unwrapErr(){throw new Error("No error")}unwrap(){return this.value}isOk(){return!0}isErr(){return!1}}class Om{constructor(e){this.error=e}error;unwrapErr(){return this.error}unwrap(){throw new Error(this.error.message)}isOk(){return!1}isErr(){return!0}}const Pm=300,Lm="GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";const Um=/Error\(Contract, #(\d+)\)/;function Nm(e){const t=new nl.XdrReader(e),n=[];for(;!t.eof;)n.push(tl.ScSpecEntry.read(t));return n}async function Fm(e,t){return e.publicKey?t.getAccount(e.publicKey):new Xp(Lm,"0")}class Dm{constructor(e){this.assembled=e;const{server:t,allowHttp:n,headers:r,rpcUrl:o}=this.assembled.options;this.server=t??new xm(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 Dm(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 Dm.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??Pm;if(this.getTransactionResponseAll=await async function(e,t,n,r=1.5,o=!1){const i=[];let s=0;if(i.push(await e()),!t(i[i.length-1]))return i;const a=new Date(Date.now()+1e3*n).valueOf();let c=1e3,u=c;for(;Date.now()<a&&t(i[i.length-1]);)s+=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,i.push(await e(i[i.length-1])),o&&t(i[i.length-1])&&console.info(`${s}. Called ${e}; ${i.length} prev attempts. Most recent: ${JSON.stringify(i[i.length-1],null,2)}`);return i}(async()=>{const n=await this.server.getTransaction(t);return e?.onProgress&&e.onProgress(n),n},e=>e.status===gm.GetTransactionStatus.NOT_FOUND,n),this.getTransactionResponse=this.getTransactionResponseAll[this.getTransactionResponseAll.length-1],this.getTransactionResponse.status===gm.GetTransactionStatus.NOT_FOUND)throw new Dm.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 Dm.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 Dm.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 Mm extends Error{}class Vm extends Error{}class qm extends Error{}class Hm extends Error{}class zm extends Error{}class $m extends Error{}class Gm extends Error{}class jm extends Error{}class Wm extends Error{}class Zm extends Error{}class Km extends Error{}class Xm extends Error{}class Ym extends Error{}class Jm{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 xm(o,{allowHttp:n,headers:r})}options;raw;originalOp;built;simulation;simulationResult;simulationTransactionData;server;signed;static Errors={ExpiredState:Mm,RestorationFailure:Vm,NeedsMoreSignatures:qm,NoSignatureNeeded:Hm,NoUnsignedNonInvokerAuthEntries:zm,NoSigner:$m,NotYetSimulated:Gm,FakeAccount:jm,SimulationFailed:Wm,InternalWalletError:Zm,ExternalServiceError:Km,InvalidClientRequest:Xm,UserRejected:Ym};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 i,s;try{i=o.contractAddress(),s=o.functionName().toString("utf-8")}catch{throw new Error("Could not extract contract address or method name from the transaction envelope.")}if(!i||!s)throw new Error("Could not extract contract address or method name from the transaction envelope.");const a=Op.fromScAddress(i).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 Jm(e);o.built=yf.fromXDR(t,e.networkPassphrase);const i=Jm.validateInvokeContractOp(o.built,e.contractId).functionName().toString("utf-8");if(i!==e.method)throw new Error(`Transaction envelope calls method '${i}', but the provided method is '${e.method}'.`);return o.simulationResult={auth:n.auth.map(e=>tl.SorobanAuthorizationEntry.fromXDR(e,"base64")),retval:tl.ScVal.fromXDR(n.retval,"base64")},o.simulationTransactionData=tl.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=tl.TransactionEnvelope.fromXDR(t,"base64"),o=yf.fromXDR(r,e.networkPassphrase),i=Jm.validateInvokeContractOp(o,e.contractId).functionName().toString("utf-8"),s=new Jm({...e,method:i,parseResultXdr:e=>n.funcResToNative(i,e)});return s.built=o,s}handleWalletError(e){if(!e)return;const{message:t,code:n}=e,r=`${t}${e.ext?` (${e.ext.join(", ")})`:""}`;switch(n){case-1:throw new Jm.Errors.InternalWalletError(r);case-2:throw new Jm.Errors.ExternalServiceError(r);case-3:throw new Jm.Errors.InvalidClientRequest(r);case-4:throw new Jm.Errors.UserRejected(r);default:throw new Error(`Unhandled error: ${r}`)}}static build(e){const t=new nf(e.contractId);return Jm.buildWithOp(t.call(e.method,...e.args??[]),e)}static async buildWithOp(e,t){const n=new Jm(t);n.originalOp=e;const r=await Fm(t,n.server);return n.raw=new yf(r,{fee:t.fee??mf,networkPassphrase:t.networkPassphrase}).setTimeout(t.timeoutInSeconds??Pm).addOperation(e),t.simulate&&await n.simulate(),n}static async buildFootprintRestoreTransaction(e,t,n,r){const o=new Jm(e);return o.raw=new yf(n,{fee:r,networkPassphrase:e.networkPassphrase}).setSorobanData(t instanceof ef?t.build():t).addOperation(Vp.restoreFootprint({})).setTimeout(e.timeoutInSeconds??Pm),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&&gm.isSimulationRestore(this.simulation)){const e=await Fm(this.options,this.server),t=await this.restoreFootprint(this.simulation.restorePreamble,e);if(t.status===gm.GetTransactionStatus.SUCCESS){const t=this.originalOp?this.originalOp:new nf(this.options.contractId).call(this.options.method,...this.options.args??[]);return this.raw=new yf(e,{fee:this.options.fee??mf,networkPassphrase:this.options.networkPassphrase}).addOperation(t).setTimeout(this.options.timeoutInSeconds??Pm),delete this.built,await this.simulate(),this}throw new Jm.Errors.RestorationFailure(`Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n${JSON.stringify(t)}`)}return gm.isSimulationSuccess(this.simulation)&&(this.built=km(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 Jm.Errors.NotYetSimulated("Transaction has not yet been simulated");if(gm.isSimulationError(e))throw new Jm.Errors.SimulationFailed(`Transaction simulation failed: "${e.error}"`);if(gm.isSimulationRestore(e))throw new Jm.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:tl.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(Um);if(!t)return;const n=parseInt(t[1],10),r=this.options.errorTypes[n];return r?new Om(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 Jm.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 Jm.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");if(!this.options.publicKey)throw new Jm.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 Jm.Errors.NeedsMoreSignatures(`Transaction requires signatures from ${n}. See \`needsNonInvokerSigningBy\` for details.`);const r=this.options.timeoutInSeconds??Pm;this.built=yf.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:i,error:s}=await t(this.built.toXDR(),o);this.handleWalletError(s),this.signed=yf.fromXDR(i,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 Dm.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=>If(e.credentials())).filter(t=>null!==t&&(e||"scvVoid"===t.signature().switch().name)).map(e=>Op.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=_f}={})=>{if(!this.built)throw new Error("Transaction has not yet been assembled or simulated");if(r===_f){const e=this.needsNonInvokerSigningBy();if(0===e.length)throw new Jm.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");if(-1===e.indexOf(n??""))throw new Jm.Errors.NoSignatureNeeded(`No auth entries for public key "${n}"`);if(!t)throw new Jm.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`")}const o=this.built.operations[0].auth??[];for(const[i,s]of o.entries()){const a=If(tl.SorobanCredentials.fromXDR(s.credentials().toXDR()));if(null===a)continue;if(Op.fromScAddress(a.address()).toString()!==n)continue;const c=t??Promise.resolve;o[i]=await r(s,async e=>{const{signedAuthEntry:t,error:r}=await c(e.toXDR("base64"),{address:n});return this.handleWalletError(r),oo.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 Fm(this.options,this.server);const n=await Jm.buildFootprintRestoreTransaction({...this.options},e.transactionData,t,e.minResourceFee),r=await n.signAndSend();if(!r.getTransactionResponse)throw new Jm.Errors.RestorationFailure(`The attempt at automatic restore failed. \n${JSON.stringify(r)}`);return r.getTransactionResponse}}function Qm(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 i(){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=i(),s=r;if(0===e){const e=i();if(e>0&&r+e<=s+n){const i=o(e),a=o(n-(r-s));try{const e=new TextDecoder("utf-8",{fatal:!0}).decode(i);a.length>0&&t.set(e,(t.get(e)||[]).concat(a))}catch{}}}r=s+n}return t}(e),n=t.get("contractspecv0");if(!n||0===n.length)throw new Error("Could not obtain contract spec from wasm");return oo.Buffer.from(n[0])}function ey(e){return/^\d+$/.test(e.name().toString())}const ty={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 ny(e){let t;switch(e.switch().value){case tl.ScSpecType.scSpecTypeVal().value:t="Val";break;case tl.ScSpecType.scSpecTypeBool().value:return{type:"boolean"};case tl.ScSpecType.scSpecTypeVoid().value:return{type:"null"};case tl.ScSpecType.scSpecTypeError().value:t="Error";break;case tl.ScSpecType.scSpecTypeU32().value:t="U32";break;case tl.ScSpecType.scSpecTypeI32().value:t="I32";break;case tl.ScSpecType.scSpecTypeU64().value:t="U64";break;case tl.ScSpecType.scSpecTypeI64().value:t="I64";break;case tl.ScSpecType.scSpecTypeTimepoint().value:t="Timepoint";break;case tl.ScSpecType.scSpecTypeDuration().value:t="Duration";break;case tl.ScSpecType.scSpecTypeU128().value:t="U128";break;case tl.ScSpecType.scSpecTypeI128().value:t="I128";break;case tl.ScSpecType.scSpecTypeU256().value:t="U256";break;case tl.ScSpecType.scSpecTypeI256().value:t="I256";break;case tl.ScSpecType.scSpecTypeBytes().value:t="DataUrl";break;case tl.ScSpecType.scSpecTypeString().value:t="ScString";break;case tl.ScSpecType.scSpecTypeSymbol().value:t="ScSymbol";break;case tl.ScSpecType.scSpecTypeAddress().value:t="Address";break;case tl.ScSpecType.scSpecTypeMuxedAddress().value:t="MuxedAddress";break;case tl.ScSpecType.scSpecTypeOption().value:return ny(e.option().valueType());case tl.ScSpecType.scSpecTypeResult().value:return ny(e.result().okType());case tl.ScSpecType.scSpecTypeVec().value:return{type:"array",items:ny(e.vec().elementType())};case tl.ScSpecType.scSpecTypeMap().value:{const t=e.map();return{type:"array",items:{type:"array",items:[ny(t.keyType()),ny(t.valueType())],minItems:2,maxItems:2}}}case tl.ScSpecType.scSpecTypeTuple().value:{const t=e.tuple(),n=t.valueTypes().length,r=n;return{type:"array",items:t.valueTypes().map(ny),minItems:n,maxItems:r}}case tl.ScSpecType.scSpecTypeBytesN().value:return{$ref:"#/definitions/DataUrl",maxLength:e.bytesN().n()};case tl.ScSpecType.scSpecTypeUdt().value:t=e.udt().name().toString();break}return{$ref:`#/definitions/${t}`}}function ry(e){const t={},n=[];e.forEach(e=>{const r=e.type(),o=e.name().toString();t[o]=ny(r),r.switch().value!==tl.ScSpecType.scSpecTypeOption().value&&n.push(o)});const r={properties:t};return n.length>0&&(r.required=n),r}class oy{entries=[];static fromWasm(e){const t=Qm(e);return new oy(t)}constructor(e){if(oo.Buffer.isBuffer(e))this.entries=Nm(e);else if("string"==typeof e)this.entries=Nm(oo.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=>tl.ScSpecEntry.fromXDR(e,"base64")):e}}funcs(){return this.entries.filter(e=>e.switch().value===tl.ScSpecEntryKind.scSpecEntryFunctionV0().value).map(e=>e.functionV0())}getFunc(e){const t=this.findEntry(e);if(t.switch().value!==tl.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?tl.ScVal.fromXDR(t,"base64"):t,r=this.getFunc(e).outputs();if(0===r.length){const e=n.switch();if(e.value!==tl.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===tl.ScSpecType.scSpecTypeResult().value?n.switch().value===tl.ScValType.scvError().value?new Om({message:n.error().toXDR("base64")}):new Bm(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===tl.ScSpecType.scSpecTypeUdt().value){const n=t.udt();return this.nativeToUdt(e,n.name().toString())}if(r===tl.ScSpecType.scSpecTypeOption().value){const n=t.option();return null==e?tl.ScVal.scvVoid():this.nativeToScVal(e,n.valueType())}switch(typeof e){case"object":if(null===e){if(r===tl.ScSpecType.scSpecTypeVoid().value)return tl.ScVal.scvVoid();throw new TypeError(`Type ${t} was not void, but value was null`)}if(e instanceof tl.ScVal)return e;if(e instanceof Op){if(t.switch().value!==tl.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.toScVal()}if(e instanceof nf){if(t.switch().value!==tl.ScSpecType.scSpecTypeAddress().value)throw new TypeError(`Type ${t} was not address, but value was Address`);return e.address().toScVal()}if(e instanceof Uint8Array||oo.Buffer.isBuffer(e)){const n=Uint8Array.from(e);switch(r){case tl.ScSpecType.scSpecTypeBytesN().value:{const e=t.bytesN();if(n.length!==e.n())throw new TypeError(`expected ${e.n()} bytes, but got ${n.length}`);return tl.ScVal.scvBytes(n)}case tl.ScSpecType.scSpecTypeBytes().value:return tl.ScVal.scvBytes(n);default:throw new TypeError(`invalid type (${t}) specified for Bytes and BytesN`)}}if(Array.isArray(e))switch(r){case tl.ScSpecType.scSpecTypeVec().value:{const n=t.vec().elementType();return tl.ScVal.scvVec(e.map(e=>this.nativeToScVal(e,n)))}case tl.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 tl.ScVal.scvVec(e.map((e,t)=>this.nativeToScVal(e,n[t])))}case tl.ScSpecType.scSpecTypeMap().value:{const n=t.map(),r=n.keyType(),o=n.valueType();return tl.ScVal.scvMap(e.map(e=>{const t=this.nativeToScVal(e[0],r),n=this.nativeToScVal(e[1],o);return new tl.ScMapEntry({key:t,val:n})}))}default:throw new TypeError(`Type ${t} was not vec, but value was Array`)}if(e.constructor===Map){if(r!==tl.ScSpecType.scSpecTypeMap().value)throw new TypeError(`Type ${t} was not map, but value was Map`);const n=t.map(),o=[],i=e.entries();let s=i.next();for(;!s.done;){const[e,t]=s.value,r=this.nativeToScVal(e,n.keyType()),a=this.nativeToScVal(t,n.valueType());o.push(new tl.ScMapEntry({key:r,val:a})),s=i.next()}return tl.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 tl.ScSpecType.scSpecTypeU32().value:if(BigInt(e)<BigInt(tl.Uint32.MIN_VALUE)||BigInt(e)>BigInt(tl.Uint32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for U32`);return tl.ScVal.scvU32(Number(e));case tl.ScSpecType.scSpecTypeI32().value:if(BigInt(e)<-BigInt(tl.Int32.MIN_VALUE)||BigInt(e)>BigInt(tl.Int32.MAX_VALUE))throw new RangeError(`Value ${e} is out of range for I32`);return tl.ScVal.scvI32(Number(e));case tl.ScSpecType.scSpecTypeU64().value:case tl.ScSpecType.scSpecTypeI64().value:case tl.ScSpecType.scSpecTypeU128().value:case tl.ScSpecType.scSpecTypeI128().value:case tl.ScSpecType.scSpecTypeU256().value:case tl.ScSpecType.scSpecTypeI256().value:case tl.ScSpecType.scSpecTypeTimepoint().value:case tl.ScSpecType.scSpecTypeDuration().value:{const t=n.name.substring(10).toLowerCase();return new cf(t,e).toScVal()}default:throw new TypeError(`invalid type (${t}) specified for integer`)}case"string":return function(e,t){switch(t.value){case tl.ScSpecType.scSpecTypeString().value:return tl.ScVal.scvString(e);case tl.ScSpecType.scSpecTypeSymbol().value:return tl.ScVal.scvSymbol(e);case tl.ScSpecType.scSpecTypeAddress().value:case tl.ScSpecType.scSpecTypeMuxedAddress().value:return Op.fromString(e).toScVal();case tl.ScSpecType.scSpecTypeU64().value:return new cf("u64",e).toScVal();case tl.ScSpecType.scSpecTypeI64().value:return new cf("i64",e).toScVal();case tl.ScSpecType.scSpecTypeU128().value:return new cf("u128",e).toScVal();case tl.ScSpecType.scSpecTypeI128().value:return new cf("i128",e).toScVal();case tl.ScSpecType.scSpecTypeU256().value:return new cf("u256",e).toScVal();case tl.ScSpecType.scSpecTypeI256().value:return new cf("i256",e).toScVal();case tl.ScSpecType.scSpecTypeBytes().value:case tl.ScSpecType.scSpecTypeBytesN().value:return tl.ScVal.scvBytes(oo.Buffer.from(e,"base64"));case tl.ScSpecType.scSpecTypeTimepoint().value:return tl.ScVal.scvTimepoint(new tl.Uint64(e));case tl.ScSpecType.scSpecTypeDuration().value:return tl.ScVal.scvDuration(new tl.Uint64(e));default:throw new TypeError(`invalid type ${t.name} specified for string value`)}}(e,n);case"boolean":if(r!==tl.ScSpecType.scSpecTypeBool().value)throw TypeError(`Type ${t} was not bool, but value was bool`);return tl.ScVal.scvBool(e);case"undefined":if(!t)return tl.ScVal.scvVoid();switch(r){case tl.ScSpecType.scSpecTypeVoid().value:case tl.ScSpecType.scSpecTypeOption().value:return tl.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 tl.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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,n.udtStructV0());case tl.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=tl.ScVal.scvSymbol(n);switch(r.switch()){case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return tl.ScVal.scvVec([o]);case tl.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),tl.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(ey)){if(!n.every(ey))throw new Error("mixed numeric and non-numeric field names are not allowed");return tl.ScVal.scvVec(n.map((t,r)=>this.nativeToScVal(e[r],n[r].type())))}return tl.ScVal.scvMap(n.map(t=>{const n=t.name().toString();return new tl.ScMapEntry({key:this.nativeToScVal(n,tl.ScSpecTypeDef.scSpecTypeSymbol()),val:this.nativeToScVal(e[n],t.type())})}))}nativeToEnum(e,t){if(t.cases().some(t=>t.value()===e))return tl.ScVal.scvU32(e);throw new TypeError(`no such enum entry: ${e} in ${t}`)}scValStrToNative(e,t){return this.scValToNative(tl.ScVal.fromXDR(e,"base64"),t)}scValToNative(e,t){const n=t.switch(),r=n.value;if(r===tl.ScSpecType.scSpecTypeOption().value)return e.switch().value===tl.ScValType.scvVoid().value?null:this.scValToNative(e,t.option().valueType());if(r===tl.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case tl.ScValType.scvVoid().value:return null;case tl.ScValType.scvU64().value:case tl.ScValType.scvI64().value:case tl.ScValType.scvTimepoint().value:case tl.ScValType.scvDuration().value:case tl.ScValType.scvU128().value:case tl.ScValType.scvI128().value:case tl.ScValType.scvU256().value:case tl.ScValType.scvI256().value:return lf(e);case tl.ScValType.scvVec().value:if(r===tl.ScSpecType.scSpecTypeVec().value){const n=t.vec();return(e.vec()??[]).map(e=>this.scValToNative(e,n.elementType()))}if(r===tl.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 tl.ScValType.scvAddress().value:return Op.fromScVal(e).toString();case tl.ScValType.scvMap().value:{const o=e.map()??[];if(r===tl.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 tl.ScValType.scvBool().value:case tl.ScValType.scvU32().value:case tl.ScValType.scvI32().value:case tl.ScValType.scvBytes().value:return e.value();case tl.ScValType.scvString().value:case tl.ScValType.scvSymbol().value:if(r!==tl.ScSpecType.scSpecTypeString().value&&r!==tl.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 tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,n.udtStructV0());case tl.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!==tl.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 tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case tl.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 i={tag:r};if(o.switch().value===tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){const e=o.tupleCase().type().map((e,t)=>this.scValToNative(n[t+1],e));i.values=e}return i}structToNative(e,t){const n={},r=t.fields();if(r.some(ey)){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!==tl.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}errorCases(){return this.entries.filter(e=>e.switch().value===tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value).flatMap(e=>e.value().cases())}jsonSchema(e){const t={};this.entries.forEach(e=>{switch(e.switch().value){case tl.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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0().value:{const n=e.udtStructV0();t[n.name().toString()]=function(e){const t=e.fields();if(t.some(ey)){if(!t.every(ey))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((e,n)=>ny(t[n].type())),minItems:t.length,maxItems:t.length}}const n=e.doc().toString(),{properties:r,required:o}=ry(t);return{description:n,properties:r,required:o,additionalProperties:!1,type:"object"}}(n);break}case tl.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 tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:{const t=e.voidCase().name().toString();r.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break}case tl.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(ny)}},required:["tag","values"],additionalProperties:!1})}}});const o={oneOf:r};return t.length>0&&(o.description=t),o}(n);break}case tl.ScSpecEntryKind.scSpecEntryFunctionV0().value:{const n=e.functionV0(),r=n.name().toString(),{input:o}=function(e){const{properties:t,required:n}=ry(e.inputs()),r={additionalProperties:!1,properties:t,type:"object"};n?.length>0&&(r.required=n);const o={properties:{args:r}},i=e.outputs(),s=i.length>0?ny(i[0]):ny(tl.ScSpecTypeDef.scSpecTypeVoid()),a=e.doc().toString();return a.length>0&&(o.description=a),o.additionalProperties=!1,s.additionalProperties=!1,{input:o,output:s}}(n);t[r]=o;break}case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}});const n={$schema:"http://json-schema.org/draft-07/schema#",definitions:{...ty,...t}};return e&&(n.$ref=`#/definitions/${e}`),n}}function iy(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 sy(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ay(e,t=!1){switch(e.switch()){case tl.ScSpecType.scSpecTypeVal():return"any";case tl.ScSpecType.scSpecTypeBool():return"boolean";case tl.ScSpecType.scSpecTypeVoid():return"null";case tl.ScSpecType.scSpecTypeError():return"Error";case tl.ScSpecType.scSpecTypeU32():case tl.ScSpecType.scSpecTypeI32():return"number";case tl.ScSpecType.scSpecTypeU64():case tl.ScSpecType.scSpecTypeI64():case tl.ScSpecType.scSpecTypeTimepoint():case tl.ScSpecType.scSpecTypeDuration():case tl.ScSpecType.scSpecTypeU128():case tl.ScSpecType.scSpecTypeI128():case tl.ScSpecType.scSpecTypeU256():case tl.ScSpecType.scSpecTypeI256():return"bigint";case tl.ScSpecType.scSpecTypeBytes():case tl.ScSpecType.scSpecTypeBytesN():return"Buffer";case tl.ScSpecType.scSpecTypeString():case tl.ScSpecType.scSpecTypeSymbol():return"string";case tl.ScSpecType.scSpecTypeAddress():case tl.ScSpecType.scSpecTypeMuxedAddress():return t?"string | Address":"string";case tl.ScSpecType.scSpecTypeVec():return`Array<${ay(e.vec().elementType(),t)}>`;case tl.ScSpecType.scSpecTypeMap():return`Map<${ay(e.map().keyType(),t)}, ${ay(e.map().valueType(),t)}>`;case tl.ScSpecType.scSpecTypeTuple():return`[${e.tuple().valueTypes().map(e=>ay(e,t)).join(", ")}]`;case tl.ScSpecType.scSpecTypeOption():for(;e.option().valueType().switch()===tl.ScSpecType.scSpecTypeOption();)e=e.option().valueType();return`${ay(e.option().valueType(),t)} | null`;case tl.ScSpecType.scSpecTypeResult():return`Result<${ay(e.result().okType(),t)}, ${ay(e.result().errorType(),t)}>`;case tl.ScSpecType.scSpecTypeUdt():return iy(e.udt().name().toString());default:return"unknown"}}function cy(e,t){switch(e.switch()){case tl.ScSpecType.scSpecTypeUdt():return void t.typeFileImports.add(iy(e.udt().name().toString()));case tl.ScSpecType.scSpecTypeAddress():case tl.ScSpecType.scSpecTypeMuxedAddress():return void t.stellarImports.add("Address");case tl.ScSpecType.scSpecTypeBytes():case tl.ScSpecType.scSpecTypeBytesN():return void(t.needsBufferImport=!0);case tl.ScSpecType.scSpecTypeVal():return void t.stellarImports.add("xdr");case tl.ScSpecType.scSpecTypeResult():t.stellarContractImports.add("Result");break;case tl.ScSpecType.scSpecTypeBool():case tl.ScSpecType.scSpecTypeVoid():case tl.ScSpecType.scSpecTypeError():case tl.ScSpecType.scSpecTypeU32():case tl.ScSpecType.scSpecTypeI32():case tl.ScSpecType.scSpecTypeU64():case tl.ScSpecType.scSpecTypeI64():case tl.ScSpecType.scSpecTypeTimepoint():case tl.ScSpecType.scSpecTypeDuration():case tl.ScSpecType.scSpecTypeU128():case tl.ScSpecType.scSpecTypeI128():case tl.ScSpecType.scSpecTypeU256():case tl.ScSpecType.scSpecTypeI256():case tl.ScSpecType.scSpecTypeString():case tl.ScSpecType.scSpecTypeSymbol():return}const n=function(e){switch(e.switch()){case tl.ScSpecType.scSpecTypeVec():return[e.vec().elementType()];case tl.ScSpecType.scSpecTypeMap():return[e.map().keyType(),e.map().valueType()];case tl.ScSpecType.scSpecTypeTuple():return e.tuple().valueTypes();case tl.ScSpecType.scSpecTypeOption():return[e.option().valueType()];case tl.ScSpecType.scSpecTypeResult():return[e.result().okType(),e.result().errorType()];default:return[]}}(e);n.forEach(e=>cy(e,t))}function uy(e){const t={typeFileImports:new Set,stellarContractImports:new Set,stellarImports:new Set,needsBufferImport:!1};return e.forEach(e=>cy(e,t)),t}function ly(e,t){const n=[],r=e.typeFileImports,o=[...e.stellarContractImports,...t?.additionalStellarContractImports||[]],i=[...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(i.length>0){const e=Array.from(new Set(i));n.push(`import {${e.join(", ")}} from '@stellar/stellar-sdk';`)}return e.needsBufferImport&&n.push("import { Buffer } from 'buffer';"),n.join("\n")}function dy(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 hy="__constructor";class py{constructor(e,t){if(this.spec=e,this.options=t,void 0===t.server){const{allowHttp:e,headers:n}=t;t.server=new xm(t.rpcUrl,{allowHttp:e,headers:n})}this.spec.funcs().forEach(n=>{const r=n.name().toString();if(r===hy)return;const o=(n,o)=>Jm.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[iy(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:i,timeoutInSeconds:s,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:i}=t,s=new xm(r,{allowHttp:o,headers:i}),a=await s.getContractWasmByHash(e,n);return oy.fromWasm(a)}(n,c,o),l=Vp.createCustomContract({address:new Op(t.address||t.publicKey),wasmHash:"string"==typeof n?oo.Buffer.from(n,o??"hex"):n,salt:r,constructorArgs:e?u.funcArgsToScVals(hy,e):[]});return Jm.buildWithOp(l,{fee:i,timeoutInSeconds:s,simulate:a,...c,contractId:"ignored",method:hy,parseResultXdr:e=>new py(u,{...c,contractId:Op.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:i}=t,s=t.server??new xm(r,{allowHttp:o,headers:i}),a=await s.getContractWasmByHash(e,n);return py.fromWasm(a,t)}static async fromWasm(e,t){const n=await oy.fromWasm(e);return new py(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,i=new xm(t,{allowHttp:r,headers:o}),s=await i.getContractWasmByContractId(n);return py.fromWasm(s,e)}txFromJSON=e=>{const{method:t,...n}=JSON.parse(e);return Jm.fromJSON({...this.options,method:t,parseResultXdr:e=>this.spec.funcResToNative(t,e)},n)};txFromXDR=e=>Jm.fromXDR(this.options,e,this.spec)}var fy=Object.freeze({__proto__:null,AssembledTransaction:Jm,Client:py,DEFAULT_TIMEOUT:Pm,Err:Om,NULL_ACCOUNT:Lm,Ok:Bm,SentTransaction:Dm,Spec:oy,Watcher:class{},basicNodeSigner:(e,t)=>({signTransaction:async(n,r)=>{const o=yf.fromXDR(n,r?.networkPassphrase||t);return o.sign(e),{signedTxXdr:o.toXDR(),signerAddress:e.publicKey()}},signAuthEntry:async t=>({signedAuthEntry:e.sign($l(oo.Buffer.from(t,"base64"))).toString("base64"),signerAddress:e.publicKey()})})});class gy{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 my{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 tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().every((e,t)=>e.name().toString().trim()===t.toString())?this.generateTupleStruct(e.udtStructV0()):this.generateStruct(e.udtStructV0());case tl.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.generateUnion(e.udtUnionV0());case tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.generateEnum(e.udtEnumV0());case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():return this.generateErrorEnum(e.udtErrorEnumV0());default:return null}}generateImports(){return ly(uy(this.spec.entries.flatMap(e=>{switch(e.switch()){case tl.ScSpecEntryKind.scSpecEntryUdtStructV0():return e.udtStructV0().fields().map(e=>e.type());case tl.ScSpecEntryKind.scSpecEntryUdtUnionV0():return e.udtUnionV0().cases().flatMap(e=>e.switch()===tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0()?e.tupleCase().type():[]);case tl.ScSpecEntryKind.scSpecEntryUdtEnumV0():case tl.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0():default:return[]}})),{includeTypeFileImports:!1})}generateStruct(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Struct: ${t}`,0)}export interface ${t} {\n${e.fields().map(e=>{const t=iy(e.name().toString()),n=ay(e.type());return`${dy(e.doc().toString(),2)} ${t}: ${n};`}).join("\n")}\n}`}generateUnion(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Union: ${t}`,0)} export type ${t} =\n${e.cases().map(e=>this.generateUnionCase(e)).map(e=>e.types.length>0?`${dy(e.doc,2)} { tag: "${sy(e.name)}"; values: readonly [${e.types.join(", ")}] }`:`${dy(e.doc,2)} { tag: "${sy(e.name)}"; values: void }`).join(" |\n")};`}generateEnum(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Enum: ${t}`,0)}export enum ${t} {\n${e.cases().map(e=>{const t=iy(e.name().toString()),n=e.value();return`${dy(e.doc().toString()||`Enum Case: ${t}`,2)} ${t} = ${n}`}).join(",\n")}\n}`}generateErrorEnum(e){const t=iy(e.name().toString());return`${dy(e.doc().toString()||`Error Enum: ${t}`,0)}export const ${t} = {\n${e.cases().map(e=>this.generateEnumCase(e)).map(e=>`${dy(e.doc,2)} ${e.value} : { message: "${sy(e.name)}" }`).join(",\n")}\n}`}generateUnionCase(e){switch(e.switch()){case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():{const t=e.voidCase();return{doc:t.doc().toString(),name:t.name().toString(),types:[]}}case tl.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():{const t=e.tupleCase();return{doc:t.doc().toString(),name:t.name().toString(),types:t.type().map(e=>ay(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=iy(e.name().toString());return`${dy(e.doc().toString()||`Tuple Struct: ${t}`,0)}export type ${t} = readonly [${e.fields().map(e=>ay(e.type())).join(", ")}];`}}class yy{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 ly(uy(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=iy(e.name().toString()),n=e.inputs().map(e=>({name:iy(e.name().toString()),type:ay(e.type(),!0)})),r=e.outputs().length>0?ay(e.outputs()[0]):"void";return`${dy(e.doc().toString(),2)} ${t}(${this.formatMethodParameters(n)}): Promise<AssembledTransaction<${r}>>;`}generateFromJSONMethod(e){return` ${iy(e.name().toString())} : this.txFromJSON<${e.outputs().length>0?ay(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:iy(e.name().toString()),type:ay(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 wy extends Error{constructor(e,t){super(e),this.cause=t,this.name="WasmFetchError"}cause}async function by(e,t){try{const n=tl.LedgerKey.contractCode(new tl.LedgerKeyContractCode({hash:tl.Hash.fromXDR(t,"raw")})),r=await e.getLedgerEntries(n);if(!r.entries||0===r.entries.length)throw new wy("WASM not found for the given hash");const o=r.entries[0];if(o.key.switch()!==tl.LedgerEntryType.contractCode())throw new wy("Invalid ledger entry type returned");const i=o.val.contractCode();return oo.Buffer.from(i.code())}catch(e){if(e instanceof wy)throw e;throw new wy("Failed to fetch WASM from hash",e)}}async function vy(e,t){try{const n=new nf(t.toString()),r=await e.getLedgerEntries(n.getFootprint());if(!r.entries||0===r.entries.length)throw new wy("Contract instance not found");const o=r.entries[0];if(o.key.switch()!==tl.LedgerEntryType.contractData())throw new wy("Invalid ledger entry type returned");const i=o.val.contractData().val().instance();if(function(e){return e.executable().switch()===tl.ContractExecutableType.contractExecutableStellarAsset()}(i))return{type:"stellar-asset-contract"};const s=i.executable().wasmHash();return{type:"wasm",wasmBytes:await by(e,s)}}catch(e){if(e instanceof wy)throw e;throw new wy("Failed to fetch WASM from contract",e)}}class Ay{spec;constructor(e){this.spec=e}static fromSpec(e){return new Ay(e)}static fromWasm(e){const t=new oy(Qm(e));return new Ay(t)}static async fromWasmHash(e,t){const n=await async function(e,t){try{const n=oo.Buffer.from(e,"hex");if(32!==n.length)throw new wy(`Invalid WASM hash length: expected 32 bytes, got ${n.length}`);return{type:"wasm",wasmBytes:await by(t,n)}}catch(t){throw new wy(`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 Ay.fromWasm(n.wasmBytes)}static async fromContractId(e,t){const n=await async function(e,t){try{if(!ih.isValidContract(e))throw new wy(`Invalid contract ID: ${e}`);const n=Op.fromString(e);return await vy(t,n)}catch(t){throw new wy(`Failed to fetch WASM from contract ${e}`,t)}}(e,t);if("wasm"===n.type)return Ay.fromWasm(n.wasmBytes);const r=new oy("AAAAAAAAAYpSZXR1cm5zIHRoZSBhbGxvd2FuY2UgZm9yIGBzcGVuZGVyYCB0byB0cmFuc2ZlciBmcm9tIGBmcm9tYC4KClRoZSBhbW91bnQgcmV0dXJuZWQgaXMgdGhlIGFtb3VudCB0aGF0IHNwZW5kZXIgaXMgYWxsb3dlZCB0byB0cmFuc2ZlcgpvdXQgb2YgZnJvbSdzIGJhbGFuY2UuIFdoZW4gdGhlIHNwZW5kZXIgdHJhbnNmZXJzIGFtb3VudHMsIHRoZSBhbGxvd2FuY2UKd2lsbCBiZSByZWR1Y2VkIGJ5IHRoZSBhbW91bnQgdHJhbnNmZXJyZWQuCgojIEFyZ3VtZW50cwoKKiBgZnJvbWAgLSBUaGUgYWRkcmVzcyBob2xkaW5nIHRoZSBiYWxhbmNlIG9mIHRva2VucyB0byBiZSBkcmF3biBmcm9tLgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIHNwZW5kaW5nIHRoZSB0b2tlbnMgaGVsZCBieSBgZnJvbWAuAAAAAAAJYWxsb3dhbmNlAAAAAAAAAgAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAEAAAALAAAAAAAAAIlSZXR1cm5zIHRydWUgaWYgYGlkYCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBpZGAgLSBUaGUgYWRkcmVzcyBmb3Igd2hpY2ggdG9rZW4gYXV0aG9yaXphdGlvbiBpcyBiZWluZyBjaGVja2VkLgAAAAAAAAphdXRob3JpemVkAAAAAAABAAAAAAAAAAJpZAAAAAAAEwAAAAEAAAABAAAAAAAAA59TZXQgdGhlIGFsbG93YW5jZSBieSBgYW1vdW50YCBmb3IgYHNwZW5kZXJgIHRvIHRyYW5zZmVyL2J1cm4gZnJvbQpgZnJvbWAuCgpUaGUgYW1vdW50IHNldCBpcyB0aGUgYW1vdW50IHRoYXQgc3BlbmRlciBpcyBhcHByb3ZlZCB0byB0cmFuc2ZlciBvdXQgb2YKZnJvbSdzIGJhbGFuY2UuIFRoZSBzcGVuZGVyIHdpbGwgYmUgYWxsb3dlZCB0byB0cmFuc2ZlciBhbW91bnRzLCBhbmQKd2hlbiBhbiBhbW91bnQgaXMgdHJhbnNmZXJyZWQgdGhlIGFsbG93YW5jZSB3aWxsIGJlIHJlZHVjZWQgYnkgdGhlCmFtb3VudCB0cmFuc2ZlcnJlZC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHRvIGJlIGRyYXduIGZyb20uCiogYHNwZW5kZXJgIC0gVGhlIGFkZHJlc3MgYmVpbmcgYXV0aG9yaXplZCB0byBzcGVuZCB0aGUgdG9rZW5zIGhlbGQgYnkKYGZyb21gLgoqIGBhbW91bnRgIC0gVGhlIHRva2VucyB0byBiZSBtYWRlIGF2YWlsYWJsZSB0byBgc3BlbmRlcmAuCiogYGV4cGlyYXRpb25fbGVkZ2VyYCAtIFRoZSBsZWRnZXIgbnVtYmVyIHdoZXJlIHRoaXMgYWxsb3dhbmNlIGV4cGlyZXMuIENhbm5vdApiZSBsZXNzIHRoYW4gdGhlIGN1cnJlbnQgbGVkZ2VyIG51bWJlciB1bmxlc3MgdGhlIGFtb3VudCBpcyBiZWluZyBzZXQgdG8gMC4KQW4gZXhwaXJlZCBlbnRyeSAod2hlcmUgZXhwaXJhdGlvbl9sZWRnZXIgPCB0aGUgY3VycmVudCBsZWRnZXIgbnVtYmVyKQpzaG91bGQgYmUgdHJlYXRlZCBhcyBhIDAgYW1vdW50IGFsbG93YW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJhcHByb3ZlIiwgZnJvbTogQWRkcmVzcywKc3BlbmRlcjogQWRkcmVzc10sIGRhdGEgPSBbYW1vdW50OiBpMTI4LCBleHBpcmF0aW9uX2xlZGdlcjogdTMyXWAAAAAAB2FwcHJvdmUAAAAABAAAAAAAAAAEZnJvbQAAABMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAABFleHBpcmF0aW9uX2xlZGdlcgAAAAAAAAQAAAAAAAAAAAAAAJhSZXR1cm5zIHRoZSBiYWxhbmNlIG9mIGBpZGAuCgojIEFyZ3VtZW50cwoKKiBgaWRgIC0gVGhlIGFkZHJlc3MgZm9yIHdoaWNoIGEgYmFsYW5jZSBpcyBiZWluZyBxdWVyaWVkLiBJZiB0aGUKYWRkcmVzcyBoYXMgbm8gZXhpc3RpbmcgYmFsYW5jZSwgcmV0dXJucyAwLgAAAAdiYWxhbmNlAAAAAAEAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAsAAAAAAAABYkJ1cm4gYGFtb3VudGAgZnJvbSBgZnJvbWAuCgpSZWR1Y2VzIGZyb20ncyBiYWxhbmNlIGJ5IHRoZSBhbW91bnQsIHdpdGhvdXQgdHJhbnNmZXJyaW5nIHRoZSBiYWxhbmNlCnRvIGFub3RoZXIgaG9sZGVyJ3MgYmFsYW5jZS4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAABGJ1cm4AAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAALaQnVybiBgYW1vdW50YCBmcm9tIGBmcm9tYCwgY29uc3VtaW5nIHRoZSBhbGxvd2FuY2Ugb2YgYHNwZW5kZXJgLgoKUmVkdWNlcyBmcm9tJ3MgYmFsYW5jZSBieSB0aGUgYW1vdW50LCB3aXRob3V0IHRyYW5zZmVycmluZyB0aGUgYmFsYW5jZQp0byBhbm90aGVyIGhvbGRlcidzIGJhbGFuY2UuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gYnVybiB0aGUgYW1vdW50IGZyb20gZnJvbSdzIGJhbGFuY2UsIGlmCnRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlciBoYXMKb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZSB3aWxsIGJlCnJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSBidXJuLCBhbmQgaGF2aW5nIGl0cyBhbGxvd2FuY2UKY29uc3VtZWQgZHVyaW5nIHRoZSBidXJuLgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKYnVybmVkIGZyb20uCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSBidXJuZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsiYnVybiIsIGZyb206IEFkZHJlc3NdLCBkYXRhID0gYW1vdW50OgppMTI4YAAAAAAACWJ1cm5fZnJvbQAAAAAAAAMAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAABUUNsYXdiYWNrIGBhbW91bnRgIGZyb20gYGZyb21gIGFjY291bnQuIGBhbW91bnRgIGlzIGJ1cm5lZCBpbiB0aGUKY2xhd2JhY2sgcHJvY2Vzcy4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2UgZnJvbSB3aGljaCB0aGUgY2xhd2JhY2sgd2lsbAp0YWtlIHRva2Vucy4KKiBgYW1vdW50YCAtIFRoZSBhbW91bnQgb2YgdG9rZW5zIHRvIGJlIGNsYXdlZCBiYWNrLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbImNsYXdiYWNrIiwgYWRtaW46IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAACAUmV0dXJucyB0aGUgbnVtYmVyIG9mIGRlY2ltYWxzIHVzZWQgdG8gcmVwcmVzZW50IGFtb3VudHMgb2YgdGhpcyB0b2tlbi4KCiMgUGFuaWNzCgpJZiB0aGUgY29udHJhY3QgaGFzIG5vdCB5ZXQgYmVlbiBpbml0aWFsaXplZC4AAAAIZGVjaW1hbHMAAAAAAAAAAQAAAAQAAAAAAAAA801pbnRzIGBhbW91bnRgIHRvIGB0b2AuCgojIEFyZ3VtZW50cwoKKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSBtaW50ZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgbWludGVkLgoKIyBFdmVudHMKCkVtaXRzIGFuIGV2ZW50IHdpdGggdG9waWNzIGBbIm1pbnQiLCBhZG1pbjogQWRkcmVzcywgdG86IEFkZHJlc3NdLCBkYXRhCj0gYW1vdW50OiBpMTI4YAAAAAAEbWludAAAAAIAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAFlSZXR1cm5zIHRoZSBuYW1lIGZvciB0aGlzIHRva2VuLgoKIyBQYW5pY3MKCklmIHRoZSBjb250cmFjdCBoYXMgbm90IHlldCBiZWVuIGluaXRpYWxpemVkLgAAAAAAAARuYW1lAAAAAAAAAAEAAAAQAAAAAAAAAQxTZXRzIHRoZSBhZG1pbmlzdHJhdG9yIHRvIHRoZSBzcGVjaWZpZWQgYWRkcmVzcyBgbmV3X2FkbWluYC4KCiMgQXJndW1lbnRzCgoqIGBuZXdfYWRtaW5gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCBoZW5jZWZvcnRoIGJlIHRoZSBhZG1pbmlzdHJhdG9yCm9mIHRoaXMgdG9rZW4gY29udHJhY3QuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsic2V0X2FkbWluIiwgYWRtaW46IEFkZHJlc3NdLCBkYXRhID0KW25ld19hZG1pbjogQWRkcmVzc11gAAAACXNldF9hZG1pbgAAAAAAAAEAAAAAAAAACW5ld19hZG1pbgAAAAAAABMAAAAAAAAAAAAAAEZSZXR1cm5zIHRoZSBhZG1pbiBvZiB0aGUgY29udHJhY3QuCgojIFBhbmljcwoKSWYgdGhlIGFkbWluIGlzIG5vdCBzZXQuAAAAAAAFYWRtaW4AAAAAAAAAAAAAAQAAABMAAAAAAAABUFNldHMgd2hldGhlciB0aGUgYWNjb3VudCBpcyBhdXRob3JpemVkIHRvIHVzZSBpdHMgYmFsYW5jZS4gSWYKYGF1dGhvcml6ZWRgIGlzIHRydWUsIGBpZGAgc2hvdWxkIGJlIGFibGUgdG8gdXNlIGl0cyBiYWxhbmNlLgoKIyBBcmd1bWVudHMKCiogYGlkYCAtIFRoZSBhZGRyZXNzIGJlaW5nIChkZS0pYXV0aG9yaXplZC4KKiBgYXV0aG9yaXplYCAtIFdoZXRoZXIgb3Igbm90IGBpZGAgY2FuIHVzZSBpdHMgYmFsYW5jZS4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJzZXRfYXV0aG9yaXplZCIsIGlkOiBBZGRyZXNzXSwgZGF0YSA9ClthdXRob3JpemU6IGJvb2xdYAAAAA5zZXRfYXV0aG9yaXplZAAAAAAAAgAAAAAAAAACaWQAAAAAABMAAAAAAAAACWF1dGhvcml6ZQAAAAAAAAEAAAAAAAAAAAAAAFtSZXR1cm5zIHRoZSBzeW1ib2wgZm9yIHRoaXMgdG9rZW4uCgojIFBhbmljcwoKSWYgdGhlIGNvbnRyYWN0IGhhcyBub3QgeWV0IGJlZW4gaW5pdGlhbGl6ZWQuAAAAAAZzeW1ib2wAAAAAAAAAAAABAAAAEAAAAAAAAAFiVHJhbnNmZXIgYGFtb3VudGAgZnJvbSBgZnJvbWAgdG8gYHRvYC4KCiMgQXJndW1lbnRzCgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKd2l0aGRyYXduIGZyb20uCiogYHRvYCAtIFRoZSBhZGRyZXNzIHdoaWNoIHdpbGwgcmVjZWl2ZSB0aGUgdHJhbnNmZXJyZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgdHJhbnNmZXJyZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsidHJhbnNmZXIiLCBmcm9tOiBBZGRyZXNzLCB0bzogQWRkcmVzc10sCmRhdGEgPSBhbW91bnQ6IGkxMjhgAAAAAAAIdHJhbnNmZXIAAAADAAAAAAAAAARmcm9tAAAAEwAAAAAAAAACdG8AAAAAABMAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAADMVRyYW5zZmVyIGBhbW91bnRgIGZyb20gYGZyb21gIHRvIGB0b2AsIGNvbnN1bWluZyB0aGUgYWxsb3dhbmNlIHRoYXQKYHNwZW5kZXJgIGhhcyBvbiBgZnJvbWAncyBiYWxhbmNlLiBBdXRob3JpemVkIGJ5IHNwZW5kZXIKKGBzcGVuZGVyLnJlcXVpcmVfYXV0aCgpYCkuCgpUaGUgc3BlbmRlciB3aWxsIGJlIGFsbG93ZWQgdG8gdHJhbnNmZXIgdGhlIGFtb3VudCBmcm9tIGZyb20ncyBiYWxhbmNlCmlmIHRoZSBhbW91bnQgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBhbGxvd2FuY2UgdGhhdCB0aGUgc3BlbmRlcgpoYXMgb24gdGhlIGZyb20ncyBiYWxhbmNlLiBUaGUgc3BlbmRlcidzIGFsbG93YW5jZSBvbiBmcm9tJ3MgYmFsYW5jZQp3aWxsIGJlIHJlZHVjZWQgYnkgdGhlIGFtb3VudC4KCiMgQXJndW1lbnRzCgoqIGBzcGVuZGVyYCAtIFRoZSBhZGRyZXNzIGF1dGhvcml6aW5nIHRoZSB0cmFuc2ZlciwgYW5kIGhhdmluZyBpdHMKYWxsb3dhbmNlIGNvbnN1bWVkIGR1cmluZyB0aGUgdHJhbnNmZXIuCiogYGZyb21gIC0gVGhlIGFkZHJlc3MgaG9sZGluZyB0aGUgYmFsYW5jZSBvZiB0b2tlbnMgd2hpY2ggd2lsbCBiZQp3aXRoZHJhd24gZnJvbS4KKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSB0cmFuc2ZlcnJlZCB0b2tlbnMuCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSB0cmFuc2ZlcnJlZC4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJ0cmFuc2ZlciIsIGZyb206IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IGFtb3VudDogaTEyOGAAAAAAAAANdHJhbnNmZXJfZnJvbQAAAAAAAAQAAAAAAAAAB3NwZW5kZXIAAAAAEwAAAAAAAAAEZnJvbQAAABMAAAAAAAAAAnRvAAAAAAATAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAABQAAAAAAAAAAAAAAB0FwcHJvdmUAAAAAAQAAAAdhcHByb3ZlAAAAAAQAAAAAAAAABGZyb20AAAATAAAAAQAAAAAAAAAHc3BlbmRlcgAAAAATAAAAAQAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAAAAAARZXhwaXJhdGlvbl9sZWRnZXIAAAAAAAAEAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAIVHJhbnNmZXIAAAABAAAACHRyYW5zZmVyAAAAAwAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAADVRyYW5zZmVyTXV4ZWQAAAAAAAABAAAACHRyYW5zZmVyAAAABAAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAJ0bwAAAAAAEwAAAAEAAAAAAAAAC3RvX211eGVkX2lkAAAAAAQAAAAAAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAgAAAAUAAAAAAAAAAAAAAARCdXJuAAAAAQAAAARidXJuAAAAAgAAAAAAAAAEZnJvbQAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAARNaW50AAAAAQAAAARtaW50AAAAAgAAAAAAAAACdG8AAAAAABMAAAABAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAhDbGF3YmFjawAAAAEAAAAIY2xhd2JhY2sAAAACAAAAAAAAAARmcm9tAAAAEwAAAAEAAAAAAAAABmFtb3VudAAAAAAACwAAAAAAAAAAAAAABQAAAAAAAAAAAAAACFNldEFkbWluAAAAAQAAAAlzZXRfYWRtaW4AAAAAAAABAAAAAAAAAAluZXdfYWRtaW4AAAAAAAATAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAANU2V0QXV0aG9yaXplZAAAAAAAAAEAAAAOc2V0X2F1dGhvcml6ZWQAAAAAAAIAAAAAAAAAAmlkAAAAAAATAAAAAQAAAAAAAAAJYXV0aG9yaXplAAAAAAAAAQAAAAAAAAAA");return Ay.fromSpec(r)}generate(e){this.validateOptions(e);const t=new my(this.spec),n=new yy(this.spec),r=t.generate(),o=n.generate();let i='export { Client } from "./client.js";';""!==r.trim()&&(i=i.concat('\nexport * from "./types.js";'));const s=new gy,{packageJson:a,tsConfig:c,readme:u,gitignore:l}=s.generate(e);return{index:i,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=Xp,e.AccountRequiresMemoError=_u,e.Address=Op,e.Asset=ph,e.AssetType=dh,e.AuthClawbackEnabledFlag=8,e.AuthImmutableFlag=4,e.AuthRequiredFlag=1,e.AuthRevocableFlag=2,e.BASE_FEE=mf,e.BadRequestError=Tu,e.BadResponseError=Eu,e.BindingGenerator=Ay,e.Claimant=yh,e.Config=Ru,e.Contract=nf,e.Federation=Df,e.FeeBumpTransaction=Kp,e.Friendbot=Qf,e.Horizon=mm,e.Hyper=el.Hyper,e.Int128=sf,e.Int256=af,e.Keypair=lh,e.LiquidityPoolAsset=mh,e.LiquidityPoolFeeV18=30,e.LiquidityPoolId=wh,e.Memo=Wp,e.MemoHash=Gp,e.MemoID=zp,e.MemoNone=Hp,e.MemoReturn=jp,e.MemoText=$p,e.MuxedAccount=Qp,e.NetworkError=Au,e.Networks=vf,e.NotFoundError=Su,e.Operation=Vp,e.ScInt=uf,e.SignerKey=tf,e.Soroban=Af,e.SorobanDataBuilder=ef,e.StellarBase=Lf,e.StellarToml=Ju,e.StrKey=ih,e.TimeoutInfinite=0,e.Transaction=Zp,e.TransactionBase=gh,e.TransactionBuilder=yf,e.Uint128=rf,e.Uint256=of,e.UnsignedHyper=el.UnsignedHyper,e.Utils=xu,e.WebAuth=Jf,e.XdrLargeInt=cf,e.authorizeEntry=_f,e.authorizeInvocation=kf,e.buildAuthorizationEntryPreimage=Cf,e.buildInvocationTree=Bf,e.buildWithDelegatesEntry=Rf,e.cereal=nl,e.contract=fy,e.decodeAddressToMuxedAccount=bh,e.encodeMuxedAccount=Ah,e.encodeMuxedAccountToAddress=vh,e.extractBaseAddress=Sh,e.getLiquidityPoolId=fh,e.hash=$l,e.httpClient=bu,e.humanizeEvents=Tf,e.nativeToScVal=df,e.rpc=Im,e.scValToBigInt=lf,e.scValToNative=hf,e.scvSortedMap=pf,e.sign=Kd,e.verify=Xd,e.walkInvocationTree=Of,e.xdr=tl});
|
|
199
199
|
//# sourceMappingURL=stellar-sdk-axios.min.js.map
|