@xoxno/sdk-js 1.0.230 → 1.0.231

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.
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see index.esm.js.LICENSE.txt */
2
- "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,Asset as r,BASE_FEE as n,Contract as o,ScInt as s,Soroban as a,StrKey as i,TransactionBuilder as u,rpc as l,scValToBigInt as c,scValToNative as d,xdr as p}from"@stellar/stellar-sdk";var f={526(e,t){t.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,s=i(e),a=s[0],u=s[1],l=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),c=0,d=u>0?a-4:a;for(r=0;r<d;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,s=[],a=16383,i=0,u=n-o;i<u;i+=a)s.push(l(e,i,i+a>u?u:i+a));return 1===o?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=s[a],n[s.charCodeAt(a)]=a;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function l(e,t,r){for(var n,o=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),o.push(u(n));return o.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){const n=r(526),o=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const a=2147483647;function i(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){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 l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=i(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(K(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return p(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 f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(K(e,SharedArrayBuffer)||e&&K(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?i(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return c(e),i(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=i(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,u.prototype),n}function h(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function m(e,t){if(u.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 r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return H(e).length;default:if(o)return n?-1:j(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return E(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return x(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function w(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let s,a=1,i=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,i/=2,u/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(s=r;s<i;s++)if(l(e,s)===l(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===u)return n*a}else-1!==n&&(s-=s-n),n=-1}else for(r+u>i&&(r=i-u),s=r;s>=0;s--){let r=!0;for(let n=0;n<u;n++)if(l(e,s+n)!==l(t,n)){r=!1;break}if(r)return s}return-1}function v(e,t,r,n){r=Number(r)||0;const o=e.length-r;n?(n=Number(n))>o&&(n=o):n=o;const s=t.length;let a;for(n>s/2&&(n=s/2),a=0;a<n;++a){const n=parseInt(t.substr(2*a,2),16);if(Z(n))return a;e[r+a]=n}return a}function S(e,t,r,n){return G(j(t,e.length-r),e,r,n)}function I(e,t,r,n){return G(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function _(e,t,r,n){return G(H(t),e,r,n)}function B(e,t,r,n){return G(function(e,t){let r,n,o;const s=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),n=r>>8,o=r%256,s.push(o),s.push(n);return s}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function E(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o<r;){const t=e[o];let s=null,a=t>239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,i,u;switch(a){case 1:t<128&&(s=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(s=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=e[o+1],n=e[o+2],i=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&i)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&i,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),o+=a}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=A));return r}(n)}u.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}}(),u.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(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array),u.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},u.allocUnsafe=function(e){return d(e)},u.allocUnsafeSlow=function(e){return d(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(K(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let o=0,s=Math.min(r,n);o<s;++o)if(e[o]!==t[o]){r=e[o],n=t[o];break}return r<n?-1:n<r?1:0},u.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}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=u.allocUnsafe(t);let o=0;for(r=0;r<e.length;++r){let t=e[r];if(K(t,Uint8Array))o+t.length>n.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=m,u.prototype._isBuffer=!0,u.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},u.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},u.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},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?E(this,0,e):g.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if(K(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.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===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const i=Math.min(s,a),l=this.slice(n,o),c=e.slice(t,r);for(let e=0;e<i;++e)if(l[e]!==c[e]){s=l[e],a=c[e];break}return s<a?-1:a<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return v(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return I(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function k(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;o<r;++o)n+=String.fromCharCode(127&e[o]);return n}function x(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;o<r;++o)n+=String.fromCharCode(e[o]);return n}function T(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let o="";for(let n=t;n<r;++n)o+=Y[e[n]];return o}function q(e,t,r){const n=e.slice(t,r);let o="";for(let e=0;e<n.length-1;e+=2)o+=String.fromCharCode(n[e]+256*n[e+1]);return o}function U(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,n,o,s){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function O(e,t,r,n,o){W(t,n,o,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function $(e,t,r,n,o){W(t,n,o,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,s){return t=+t,r>>>=0,s||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,s){return t=+t,r>>>=0,s||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,u.prototype),n},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e],o=1,s=0;for(;++s<t&&(o*=256);)n+=this[e+s]*o;return n},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<<BigInt(32))})),u.prototype.readBigUInt64BE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(o)})),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e],o=1,s=0;for(;++s<t&&(o*=256);)n+=this[e+s]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=t,o=1,s=this[e+--n];for(;n>0&&(o*=256);)s+=this[e+--n]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),u.prototype.readBigInt64BE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,s=0;for(this[t]=255&e;++s<r&&(o*=256);)this[t+s]=e/o&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,s=1;for(this[t+o]=255&e;--o>=0&&(s*=256);)this[t+o]=e/s&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeBigUInt64LE=J((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return $(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=0,s=1,a=0;for(this[t]=255&e;++o<r&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeBigInt64LE=J((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return $(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const o=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),o},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const s=u.isBuffer(e)?e:u.from(e,n),a=s.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=s[o%a]}return this};const L={};function D(e,t,r){L[e]=class extends r{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 F(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,n,o,s){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let o;throw o=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new L.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,o,s)}function z(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new L.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=F(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=F(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function j(e,t){let r;t=t||1/0;const n=e.length;let o=null;const s=[];for(let a=0;a<n;++a){if(r=e.charCodeAt(a),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&s.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function H(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(X,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function G(e,t,r,n){let o;for(o=0;o<n&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=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 Z(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},251(e,t){t.read=function(e,t,r,n,o){var s,a,i=8*o-n-1,u=(1<<i)-1,l=u>>1,c=-7,d=r?o-1:0,p=r?-1:1,f=e[t+d];for(d+=p,s=f&(1<<-c)-1,f>>=-c,c+=i;c>0;s=256*s+e[t+d],d+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+e[t+d],d+=p,c-=8);if(0===s)s=1-l;else{if(s===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=l}return(f?-1:1)*a*Math.pow(2,s-n)},t.write=function(e,t,r,n,o,s){var a,i,u,l=8*s-o-1,c=(1<<l)-1,d=c>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,h=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+d>=1?p/u:p*Math.pow(2,1-d))*u>=2&&(a++,u/=2),a+d>=c?(i=0,a=c):a+d>=1?(i=(t*u-1)*Math.pow(2,o),a+=d):(i=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[r+f]=255&i,f+=h,i/=256,o-=8);for(a=a<<o|i,l+=o;l>0;e[r+f]=255&a,f+=h,a/=256,l-=8);e[r+f-h]|=128*m}},468(e,t,r){r.d(t,{gm:()=>b,IY:()=>y,Vd:()=>g});const n={type:"string"},o={type:"number"},s={type:"boolean"},a={...n,nullable:!0},i={...o,nullable:!0},u={...n,enum:["mainnet","testnet"]},l={...n,enum:["ready","stale","incomplete"]};function c(e){return{type:"object",required:Object.keys(e),properties:e}}const d={sac:n,symbol:n,name:n,decimals:i,logoUrl:a},p=c({valid:s,stale:s,deviation:s,timestamp:i}),f=c({...d,hubId:o,hubName:n,amountRaw:{...a,description:"Integer token base units, never scaled shares."},amount:a,apy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,valueUsd:i,priceStatus:p,indexRay:a,indexedAt:o,indexedLedger:o}),h=c({amountRaw:a,amount:a,usd:i}),m=c({spokeId:o,spokeName:n,ltvBps:o,supplyCapacity:h,borrowCapacity:h,canSupply:s,canBeCollateral:s,canBorrow:s,canOpenAccount:{...s,description:"Spoke admits new accounts; other entry gates still apply."}}),g={type:"array",items:c({accountId:n,nftContract:n,nftImage:{...n,format:"uri",description:"Dynamic position SVG served by the network's XOXNO API."},network:u,spokeId:i,spokeName:a,supplied:{type:"array",items:f},borrow:{type:"array",items:f},hasDebt:{...s,nullable:!0,description:"Null when account rows are unavailable."},healthFactor:{...i,description:"Null without debt or when risk inputs are unavailable."},borrowLimitUsd:i,availableBorrowUsd:{...i,description:"Account headroom, before per-market constraints."},netApy:{...i,description:"Net annual yield divided by positive net equity; fraction."},dataStatus:l})},y={type:"array",items:c({...d,hubId:o,hubName:n,network:u,supplyApy:{...i,description:"Fraction: 0.05 means 5%."},borrowApy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,priceStatus:p,spokes:{type:"array",items:m},dataStatus:l,indexedAt:{...o,description:"Pool state timestamp. Capacities are indexed snapshot estimates; prepare/simulate before signing."},indexedLedger:o})};function w(e){if(!e)return;const t=/\s*<([^<>\s]+)>\s*((?:;\s*[\w!#$%&'*+.^`|~-]+\s*=\s*(?:"(?:[^"\\\r\n]|\\.)*"|[\w!#$%&'*+.^`|~:/-]+)\s*)*)(,|$)/gy;let r,n=0;for(;n<e.length;){const o=t.exec(e);if(!o||o[3]&&t.lastIndex===e.length)throw new Error("Invalid pagination Link header");let s=!1,a=!1;for(const e of o[2].matchAll(/;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\.)*)"|([\w!#$%&'*+.^`|~:/-]+))\s*/g))if("rel"===e[1].toLowerCase()){if(a)throw new Error("Duplicate pagination link relation");a=!0,s=(e[2]??e[3]).replace(/\\(.)/g,"$1").toLowerCase().split(/\s+/).includes("next")}if(s){if(void 0!==r)throw new Error("Multiple next pagination links");r=o[1]}n=t.lastIndex}return r}function b(e){const t=new URL(e.baseUrl.trim());if(!["https:","http:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an HTTP API root without credentials, query or fragment");t.pathname=`${t.pathname.replace(/\/+$/,"")}/`;const r=e.fetch??globalThis.fetch?.bind(globalThis);if(!r)throw new Error("A fetch implementation is required");async function n(e,n){const o=new URL(`stellar-lending/v1/${e}`,t);let s=o;const a=new Set,i=[];for(;;){if(a.has(s.href))throw new Error("Pagination Link cycle");a.add(s.href);const e=await r(s.href,{signal:n,redirect:"error"});if(e.redirected||e.url&&new URL(e.url).href!==s.href)throw new Error("Stellar lending redirects are not allowed");if(!e.ok)throw new Error(`Stellar lending request failed: HTTP ${e.status}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Stellar lending response must be an array");i.push(...t);const u=w(e.headers.get("Link"));if(!u)break;const l=new URL(u,s);if(l.origin!==o.origin||l.pathname!==o.pathname||l.username||l.password||l.hash)throw new Error("Pagination Link must stay on the same API endpoint");s=l}return i}return{assets:({usage:e,signal:t}={})=>{if(void 0!==e&&"collateral"!==e&&"borrow"!==e)throw new Error("usage must be collateral or borrow");return n("assets"+(e?`?usage=${e}`:""),t)},positions:(e,{signal:t}={})=>{if(!e.trim()||"."===e||".."===e)throw new Error("owner is required");return n(`users/${encodeURIComponent(e)}/positions`,t)}}}}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={exports:{}};return f[e](r,r.exports,m),r.exports}m.d=(e,t)=>{for(var r in t)m.o(t,r)&&!m.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const g="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",y="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",w="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e";var b;!function(e){e.MAINNET="1",e.DEVNET="D"}(b||(b={}));class v{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=b.MAINNET,apiUrl:r,...n}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=n,this.config=t==b.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",FM_SC:g,DR_SC:y,KG_SC:w,Staking_SC:"erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",Manager_SC:"erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",P2P_SC:"erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6"}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",FM_SC:g,DR_SC:y,KG_SC:w,Staking_SC:"erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",Manager_SC:"erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",P2P_SC:"erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:n,cache:o,debug:s,timeout:a,...i}=this.init,{next:u,cache:l,debug:c,timeout:d,headers:p,method:f="GET",...h}=r,m=p?.Authorization,g="Bearer undefined"===m?void 0:m,y="GET"!==f&&"HEAD"!==f&&"PUT"!==f,w={...p,Referer:"https://xoxno.sdk","User-Agent":"XOXNO/1.0/SDK",...y?{"Content-Type":"application/json"}:{},...g?{Authorization:g}:{}},b=Object.entries(t??{}).filter((([,e])=>void 0!==e)).flatMap((([e,t])=>Array.isArray(t)?t.filter((e=>void 0!==e)).map((t=>`${e}=${encodeURIComponent(t)}`)):`${e}=${encodeURIComponent(t)}`)).join("&"),v=`${this.apiUrl}${e}${b.length?`?${b}`:""}`,{revalidate:S,...I}=n??{},{revalidate:_,...B}=u??{},R="GET"!==f||g?void 0:_??S,E="GET"!==f||g||R?void 0:l??o,A=h.body,k=d??a??(null==A?3e4:0),x=k>0?AbortSignal.timeout(k):void 0,T=h.signal??i.signal,q=x&&T?AbortSignal.any([T,x]):x??T,U={...i,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:E,next:{...I,...B,revalidate:R}};(c??s)&&console.debug("SDK fetch: ",v,U);const C=await fetch(v,U).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${v}: ${e.message}`),{cause:e});throw e})),O=await C.text();if(!C.ok){let e;try{e=JSON.parse(O)}catch{e={message:O}}const t=[v,C.status,C.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(O)}catch{return O}}}const S={stellarMainnet:{name:"mainnet",passphrase:"Public Global Stellar Network ; September 2015",horizonUrl:"https://horizon.stellar.org",sorobanRpcUrl:"https://stellar-gateway.xoxno.com",quoteUrl:"https://stellar-swap.xoxno.com",explorerNetwork:"public",aquariusApiUrl:"https://amm-api.aqua.network",aquariusRouter:"CBQDHNBFBZYE4MKPWBSJOPIYLW4SFSXAXUTSXJN76GNKYVYPCKWC6QUK",lendingController:"CAUCMIN5KSXEVZ7NMXR3LZATGD5EFIEUI5XWTFLYRO2R5OTXI22WE5JX",lendingPool:"CBXRNDQMAJFG4VUKMKFEMFS75UUXE2SPSNV4LEEFCSNBCN66PYRWBKXO",aggregatorRouter:"CCVENFSVCBYDHVOACFZXMNNYVOZ3LKXPZYU5LUI4N7KTXOKRVYD7F3TR",governance:"CC44PEQW7HSEPKAZ5ZRPH2JS5M5KVJXCUBLJ2ZX4E3WCDKMNFILHC2AD",priceAggregator:"CBGUF2G2Q7HCVCWYISDXBHPVBGMYNXA7PG2VET66YBZX6IKOOV27NSMV",positionNftContract:"CAWCSG77AY2W24QZ6ZXLHZU4UXEFHZBM6EI4A4IF7JB5CTY4XND3TI6C"},stellarTestnet:{name:"testnet",passphrase:"Test SDF Network ; September 2015",horizonUrl:"https://horizon-testnet.stellar.org",sorobanRpcUrl:"https://stellar-testnet-gateway.xoxno.com",quoteUrl:"https://testnet-stellar-swap.xoxno.com",explorerNetwork:"testnet",aquariusApiUrl:"https://amm-api-testnet.aqua.network",aquariusRouter:"CBCFTQSPDBAIZ6R6PJQKSQWKNKWH2QIV3I4J72SHWBIK3ADRRAM5A6GD",lendingController:"CCXRWJ6SIU2WPFEGLFGJVITPL57QAYIMIO6OAM2NBGNDQSSCK2FFV3F3",lendingPool:"CBSGF6QOQAMPFBEVSYPEQHSZRIHJ6RCGUPCRDMUX36DEKRWFAO2PZB5A",aggregatorRouter:"CDNTWMWW2WGYTKIZTJYNGNVQQZI4KTC5BQRZ3275KESRX5T4O3AYECL5",governance:"CDS33JDOYH3F3FL4QUQ6DV4WKHML2AKHF4LADTZ57FRUAEBTE7NMY5FQ",priceAggregator:"CBMARXSYE56NPDLX42TTICM5GS5XQCYRD5VMCJME624TS6C2S53VETYU",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},I=S;function _(e){return S["testnet"===e?"stellarTestnet":"stellarMainnet"]}const B={mainnet:S.stellarMainnet.passphrase,testnet:S.stellarTestnet.passphrase};var R=m(287);const E=["Soroswap","Aquarius","Phoenix","Sushi","CometDex","Curve"],A={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4,Curve:7},k=1,x=1e6,T=5,q=6,U=0,C=1,O=2,$=128,N=48,P=32,M=256,L=$-O,D=e=>new t(e).toScVal(),F=e=>new s(e).toI128(),W=e=>p.ScVal.scvU32(e),z=e=>{if("number"==typeof e&&!Number.isSafeInteger(e))throw new Error("Stellar builder: u64 numbers must be safe integers; pass a decimal string for larger values");return new s("string"==typeof e?e:e.toString()).toU64()},V=e=>p.ScVal.scvBool(e),X=e=>p.ScVal.scvString(e),j=e=>p.ScVal.scvSymbol(e),H=()=>p.ScVal.scvVoid(),G=e=>p.ScVal.scvVec(e),K=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,n=R.hp.from(r,"hex");if(n.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${n.length} bytes from "${e}")`);return p.ScVal.scvBytes(n)},Z=(e,t)=>null==e?H():t(e),Y=(e,t)=>te({asset:D(t),hub_id:W(e)}),J=(e,t,r)=>p.ScVal.scvVec([Y(e,t),F(r)]),Q=e=>p.ScVal.scvVec(e.map((e=>J(e.hubId,e.asset,e.amount)))),ee=e=>{if("Transfer"===e)return G([j("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return G([j("Credit"),z(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},te=e=>{const t=Object.keys(e).sort().map((t=>new p.ScMapEntry({key:j(t),val:e[t]})));return p.ScVal.scvMap(t)};class re{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=M)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=L)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=P)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>x)throw new Error(`Stellar builder: split weight ${e} outside 1..=${x}`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,n,o){this.ops.push([e,t,r,n,o])}emitPath(e,t){e.hops.forEach(((r,n)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const o=e.hops[n-1];if(o&&r.tokenIn!==o.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(A[r.venue],0===n?t:C,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const n=t[e].hops[0]?.tokenIn,o=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===n&&o.push(r);const s=o.reduce(((e,r)=>e+t[r].splitPpm),0);if(s>x)throw new Error(`Stellar builder: split weights for one token sum to ${s}, above ${x}`);const a=s===x;let i=x;o.forEach(((e,n)=>{r[e]=!0;const s=t[e];let u;if(n+1===o.length&&a)u=U;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(s.splitPpm*x/i);i-=Math.min(s.splitPpm,i),u=$+this.weight(e)}this.emitPath(s,u)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>N)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts ${N}`);const n=[k,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)n.push(...e);for(const e of this.weights)n.push(e>>>16&255,e>>>8&255,255&e);return R.hp.from(n)}get assetList(){return this.assets}get amountList(){return this.amounts}}const ne=e=>{const t=new re(e.totalMinOut),r=t.asset(e.tokenIn),n=t.asset(e.tokenOut);if(r===n)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const n=t.asset(e.burnPool),o=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(T,U,n,r,o)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const n=e.mintPoolTokens;if(!n||2!==n.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[o,s]=n,[a,i]=e.preSwapFromA?[o,s]:[s,o];t.emit(A.Aquarius,O+t.amount(r),t.asset(e.mintPool),t.asset(a),t.asset(i))}t.emit(q,U,t.asset(e.mintPool),n,t.amount(e.mintMinShares??"1"))}const o=Number(e.referralId??0);if(!Number.isInteger(o)||o<0||o>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return te({amounts:p.ScVal.scvVec(t.amountList.map((e=>F(e)))),assets:p.ScVal.scvVec(t.assetList.map((e=>D(e)))),ops:p.ScVal.scvBytes(t.toBytes(r,n,o))})},oe=e=>{const t=R.hp.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return p.ScVal.scvBytes(t)},se=()=>p.ScVal.scvBytes(R.hp.alloc(0)),ae=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return R.hp.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const n=R.hp.from(t,"base64");if(0===n.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return n},ie=e=>{if("string"==typeof e)return oe(ae(e));if(e instanceof Uint8Array)return 0===e.length?se():oe(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?oe(ae(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?oe(ae(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?oe(ae(e.bytes)):0===e.bytes.length?se():oe(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length&&!t.burnPool&&!t.mintPool)throw new Error("Stellar builder: `steps.paths` needs a strategy path or a liquidity burn/mint operation");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,n]of t.paths.entries()){if(!n||"number"!=typeof n.splitPpm||n.splitPpm<=0||!Array.isArray(n.hops)||0===n.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of n.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!E.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=n.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+n.splitPpm)}for(const[e,n]of r){if(n>x)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${n}, above ${x}`);if(!t.mintPool&&n!==x)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to ${x}, got ${n}`)}return t})(e),p.ScVal.scvBytes(R.hp.from(ne(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},ue=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=R.hp.from(t,"hex");return p.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return p.ScVal.scvBytes(R.hp.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function le(e,t){if("number"!=typeof t||!Number.isInteger(t)||t<0||t>18)throw new Error("Token decimals must be an integer from 0 to 18");if("string"!=typeof e||!/^\d+(?:\.\d+)?$/.test(e))throw new Error("Token amount must be plain decimal text");const r=a.parseTokenAmount(e,t),n=BigInt(r);if(n<=0n||n>(1n<<127n)-1n)throw new Error("Token amount must be within the positive i128 range");return r}function ce(t,r,s){if(!t.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const a=new o(t.controllerAddress),i=new e(t.caller,t.sourceSequence);return{xdr:new u(i,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(a.call(r,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function de(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return W(e)}function pe(e,t){const r=t.accountNonce??0;return ce(e,"supply",[D(e.caller),z(r),de(t.spokeId),Q([...t.assets])])}function fe(e,t){return pe(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function he(e,t){return ce(e,"borrow",[D(e.caller),z(t.accountNonce),Q([...t.borrows]),Z(t.to,D)])}function me(e,t){return he(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function ge(e,t){return ce(e,"withdraw",[D(e.caller),z(t.accountNonce),Q([...t.withdrawals]),Z(t.to,D)])}function ye(e,t){return ge(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function we(e,t){return ce(e,"repay",[D(e.caller),z(t.accountNonce),Q([...t.payments])])}function be(e,t){return we(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function ve(e,t){return ce(e,"liquidate",[D(e.caller),z(t.accountNonce),Q([...t.debtPayments]),ee(t.seizeMode??"Transfer")])}function Se(e){const t=d(p.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function Ie(e,t){return ce(e,"get_liquidation_estimate",[z(t.accountNonce),Q([...t.debtPayments]),ee(t.seizeMode??"Transfer")])}const _e=e=>(Array.isArray(e)?e:[]).map((e=>{const t=e;return{asset:String(t.asset),amount:String(t.amount)}}));function Be(e){const t=d(p.ScVal.fromXDR(e,"base64"));if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Stellar builder: liquidation estimate must be a struct");return{seizedCollaterals:_e(t.seized_collaterals),protocolFees:_e(t.protocol_fees),refunds:_e(t.refunds),maxPaymentWad:String(t.max_payment_wad),bonusRateBps:String(t.bonus_rate_bps)}}function Re(e,t){return ce(e,"flash_loan",[D(e.caller),Y(t.hubId,t.asset),F(t.amount),D(t.receiver),ue(t.data)])}function Ee(e,t){return ce(e,"migrate_from_blend",[D(e.caller),z(t.accountId),de(t.spokeId),W(t.hubId),D(t.blendPool),G(t.collateralTokens.map(D)),G(t.supplyTokens.map(D)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),p.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,p.ScVal.scvVec([D(t),F(r)]);var t,r}))))]);var r}function Ae(e,t){const r=t.accountNonce??0;return ce(e,"multiply",[D(e.caller),z(r),de(t.spokeId),Y(t.collateral.hubId,t.collateral.asset),F(t.debtToFlashLoan),Y(t.debt.hubId,t.debt.asset),W(t.mode),ie(t.steps),Z(t.initialPayment,(e=>J(e.hubId,e.asset,e.amount))),Z(t.convertSwap,ie)])}function ke(e,t){return ce(e,"swap_debt",[D(e.caller),z(t.accountNonce),Y(t.existingDebt.hubId,t.existingDebt.asset),F(t.newDebtAmount),Y(t.newDebt.hubId,t.newDebt.asset),ie(t.steps)])}function xe(e,t){return ce(e,"swap_collateral",[D(e.caller),z(t.accountNonce),Y(t.current.hubId,t.current.asset),F(t.fromAmount),Y(t.newCollateral.hubId,t.newCollateral.asset),ie(t.steps)])}function Te(e,t){return ce(e,"repay_debt_with_collateral",[D(e.caller),z(t.accountNonce),Y(t.collateral.hubId,t.collateral.asset),F(t.collateralAmount),Y(t.debt.hubId,t.debt.asset),ie(t.steps),V(t.closePosition)])}const qe="/stellar-lending",Ue=encodeURIComponent,Ce=(e,t)=>e.fetchWithTimeout(`${qe}/context`,t),Oe=(e,t)=>e.fetchWithTimeout(`${qe}/live-state`,t),$e=(e,t)=>e.fetchWithTimeout(`${qe}/markets/detailed`,t),Ne=(e,t)=>e.fetchWithTimeout(`${qe}/assets`,t),Pe=(e,t)=>e.fetchWithTimeout(`${qe}/hubs`,t),Me=(e,t)=>e.fetchWithTimeout(`${qe}/spokes`,t),Le=(e,t={},r)=>e.fetchWithTimeout(`${qe}/reserves`,{...r,params:{...t}}),De=(e,t,r,n,o)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}`,o),Fe=(e,t,r)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}`,r),We=(e,t,r)=>e.fetchWithTimeout(`${qe}/hubs/${t}`,r),ze=(e,t,r)=>e.fetchWithTimeout(`${qe}/spokes/${t}`,r),Ve=(e,t,r)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/positions`,r),Xe=(e,t,r)=>e.fetchWithTimeout(`${qe}/accounts/${Ue(t)}/positions`,r),je=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/assets/${Ue(r)}/balance`,n),He=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/page`,{...n,params:{...r}}),Ge=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/markets`,{...n,params:{side:r}}),Ke=(e,t,r,n,o,s)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}/holders`,{...s,params:{side:o}}),Ze=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/hubs/${t}/holders`,{...n,params:{side:r}}),Ye=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/spokes/${t}/holders`,{...n,params:{side:r}}),Je=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/graph`,{...n,params:{...r}}),Qe=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/hubs/${t}/graph`,{...n,params:{...r}}),et=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/spokes/${t}/graph`,{...n,params:{...r}}),tt=(e,t,r,n,o,s)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}/graph`,{...s,params:{...o}}),rt=(e,t,r={},n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/activity`,{...n,params:{...r}}),nt=(e,t,r={},n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/activity/page`,{...n,params:{...r}}),ot=(e,t={},r)=>e.fetchWithTimeout(`${qe}/governance/proposals`,{...r,params:{...t}}),st=(e,t={},r)=>e.fetchWithTimeout(`${qe}/positions`,{...r,params:{...t}}),at=(e,t={},r)=>e.fetchWithTimeout(`${qe}/participants`,{...r,params:{...t}}),it=(e,t={},r)=>e.fetchWithTimeout(`${qe}/liquidations/leaderboard`,{...r,params:{...t}}),ut=(e,t={},r)=>e.fetchWithTimeout(`${qe}/distribution`,{...r,params:{...t}}),lt=(e,t={},r)=>e.fetchWithTimeout(`${qe}/campaign/leaderboard`,{...r,params:{...t}}),ct=(e,t,r)=>e.fetchWithTimeout(`${qe}/stats/history`,{...r,params:{...t}}),dt=(e,t,r)=>e.fetchWithTimeout(`${qe}/revenue`,{...r,params:{...t}}),pt=(e,t,r)=>e.fetchWithTimeout(`${qe}/revenue/fees`,{...r,params:{...t}}),ft=(e,t,r)=>e.fetchWithTimeout(`${qe}/liquidations`,{...r,params:{...t}}),ht=(e,t,r)=>e.fetchWithTimeout(`${qe}/volume`,{...r,params:{...t}}),mt=(e,t,r)=>e.fetchWithTimeout(`${qe}/active-users`,{...r,params:{...t}}),gt=(e,t,r)=>e.fetchWithTimeout(`${qe}/rate-spread`,{...r,params:{...t}}),yt=(e,t,r)=>e.fetchWithTimeout(`${qe}/defillama`,{...r,params:{...t}}),wt=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/history`,{...n,params:{...r}}),bt=(e,t,r)=>e.fetchWithTimeout(`${qe}/pnl`,{...r,params:{accountId:t}}),vt=(e,t,r)=>e.fetchWithTimeout(`${qe}/pnl/scope`,{...r,params:{scope:t}}),St=(e,t,r)=>e.fetchWithTimeout(`${qe}/campaign/me`,{...r,params:{owner:t}}),It=e=>({context:t=>Ce(e,t),liveState:t=>Oe(e,t),marketsDetailed:t=>$e(e,t),assets:t=>Ne(e,t),hubs:t=>Pe(e,t),spokes:t=>Me(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?Le(e,t,r):Le(e,{},t),reserve:(t,r,n,o)=>De(e,t,r,n,o),asset:(t,r)=>Fe(e,t,r),hub:(t,r)=>We(e,t,r),spoke:(t,r)=>ze(e,t,r),userPositions:(t,r)=>Ve(e,t,r),accountPositions:(t,r)=>Xe(e,t,r),walletBalance:(t,r,n)=>je(e,t,r,n),assetPage:(t,r,n)=>He(e,t,r,n),assetMarkets:(t,r,n)=>Ge(e,t,r,n),reserveHolders:(t,r,n,o,s)=>Ke(e,t,r,n,o,s),hubHolders:(t,r,n)=>Ze(e,t,r,n),spokeHolders:(t,r,n)=>Ye(e,t,r,n),assetGraph:(t,r,n)=>Je(e,t,r,n),hubGraph:(t,r,n)=>Qe(e,t,r,n),spokeGraph:(t,r,n)=>et(e,t,r,n),reserveGraph:(t,r,n,o,s)=>tt(e,t,r,n,o,s),userActivity:(t,r={},n)=>rt(e,t,r,n),userActivityPage:(t,r={},n)=>nt(e,t,r,n),governanceProposals:(t={},r)=>ot(e,t,r),positionsLeaderboard:(t={},r)=>st(e,t,r),participants:(t={},r)=>at(e,t,r),liquidationsLeaderboard:(t={},r)=>it(e,t,r),distribution:(t={},r)=>ut(e,t,r),campaignLeaderboard:(t={},r)=>lt(e,t,r),statsHistory:(t,r)=>ct(e,t,r),revenue:(t,r)=>dt(e,t,r),feeRevenue:(t,r)=>pt(e,t,r),liquidations:(t,r)=>ft(e,t,r),volume:(t,r)=>ht(e,t,r),activeUsers:(t,r)=>mt(e,t,r),rateSpread:(t,r)=>gt(e,t,r),defillama:(t,r)=>yt(e,t,r),userHistory:(t,r,n)=>wt(e,t,r,n),positionsPnl:(t,r)=>bt(e,t,r),pnlByScope:(t,r)=>vt(e,t,r),campaignMe:(t,r)=>St(e,t,r)});var _t=m(468);const Bt=e=>te({base_borrow_rate:F(e.baseBorrowRateRay),max_borrow_rate:F(e.maxBorrowRateRay),max_utilization:F(e.maxUtilizationRay),mid_utilization:F(e.midUtilizationRay),optimal_utilization:F(e.optimalUtilizationRay),reserve_factor:W(e.reserveFactorBps),slope1:F(e.slope1Ray),slope2:F(e.slope2Ray),slope3:F(e.slope3Ray)}),Rt=e=>te({asset_decimals:W(e.assetDecimals),asset_id:D(e.assetId),base_borrow_rate:F(e.baseBorrowRateRay),flashloan_fee:W(e.flashloanFeeBps),is_flashloanable:V(e.isFlashloanable),max_borrow_rate:F(e.maxBorrowRateRay),max_utilization:F(e.maxUtilizationRay),mid_utilization:F(e.midUtilizationRay),optimal_utilization:F(e.optimalUtilizationRay),reserve_factor:W(e.reserveFactorBps),slope1:F(e.slope1Ray),slope2:F(e.slope2Ray),slope3:F(e.slope3Ray)}),Et=e=>te({max_borrow_positions:W(e.maxBorrowPositions),max_supply_positions:W(e.maxSupplyPositions)}),At=e=>{if("Token"in e&&e.Token)return G([j("Token"),D(e.Token)]);if("Ref"in e&&e.Ref)return G([j("Ref"),j(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},kt=e=>{if("Stellar"in e)return G([j("Stellar"),D(e.Stellar)]);if("Symbol"in e)return G([j("Symbol"),j(e.Symbol)]);if("String"in e)return G([j("String"),X(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},xt=e=>{if("Spot"===e)return G([j("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return G([j("Twap"),W(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Tt=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return G([j(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},qt=e=>{if("Market"===e||"Fundamental"===e)return G([j(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ut=e=>{if("Reflector"in e){const t=e.Reflector;return G([j("Reflector"),te({asset:kt(t.asset),contract:D(t.contract),read_mode:xt(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return G([j("MultiFeed"),te({contract:D(t.contract),feed_id:X(t.feedId),kind:Tt(t.kind),nature:qt(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ct=e=>{const t=e;return te({decimals:W(t.decimals),max_stale_seconds:z(t.maxStaleSeconds),provider:Ut(t.provider)})},Ot=e=>{if("RequireDisjoint"===e)return G([j("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return G([j("AllowShared"),G(t.map((e=>te({contract:D(e.contract),kind:Tt(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},$t=e=>{const t=e,r=t.sources??[];let n,o;if("number"==typeof t.toleranceBps)n=1e4+t.toleranceBps,o=Math.max(1,Math.floor(1e8/n));else{const e=t.tolerance??{};n=Number(e.upperRatioBps),o=Number(e.lowerRatioBps)}return te({asset_decimals:W(Number(t.assetDecimals)),independence:Ot(t.independence),max_price_stale_seconds:z(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:F(String(t.maxSanityPriceWad)),min_sanity_price_wad:F(String(t.minSanityPriceWad)),sources:G(r.map((e=>(e=>{if("Feed"in e)return G([j("Feed"),Ct(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return G([j("Scaled"),te({factor:Ct(t.factor),max_factor_wad:F(t.maxFactorWad),min_factor_wad:F(t.minFactorWad),quote:At(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return G([j("LpShare"),te({key_a:At(t.keyA),key_b:At(t.keyB),kind:G([j(t.kind||"ConstantProduct")]),pool:D(t.pool),reserve_a_decimals:W(t.reserveADecimals),reserve_b_decimals:W(t.reserveBDecimals),share_decimals:W(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:te({lower_ratio_bps:W(o),upper_ratio_bps:W(n)})})};function Nt(e,t){return ce(e,"upgrade",[K(t.wasmHash)])}function Pt(e,t){return ce(e,"migrate",[W(t.newVersion)])}function Mt(e){return ce(e,"pause",[])}function Lt(e){return ce(e,"unpause",[])}function Dt(e,t){return ce(e,"grant_role",[D(t.account),j(t.role)])}function Ft(e,t){return ce(e,"revoke_role",[D(t.account),j(t.role)])}function Wt(e,t){return ce(e,"transfer_ownership",[D(t.newOwner),W(t.liveUntilLedger)])}function zt(e){return ce(e,"accept_ownership",[])}function Vt(e,t){return ce(e,"set_swap_aggregator",[D(t.aggregator)])}function Xt(e,t){return ce(e,"set_price_aggregator",[D(t.aggregator)])}function jt(e,t){return ce(e,"set_accumulator",[D(t.accumulator)])}function Ht(e,t){return ce(e,"set_position_limits",[Et(t)])}function Gt(e,t){return ce(e,"approve_blend_pool",[D(t.pool)])}function Kt(e,t){return ce(e,"revoke_blend_pool",[D(t.pool)])}function Zt(e,t){return ce(e,"set_oracle",[At(t.key),$t(t.oracle)])}function Yt(e,t){const r=t.toleranceBps,n=t.upperRatioBps??1e4+r,o=t.lowerRatioBps??Math.max(1,Math.floor(1e8/n));return ce(e,"set_tolerance",[At(t.key),te({lower_ratio_bps:W(o),upper_ratio_bps:W(n)})])}function Jt(e,t){return ce(e,"set_spoke_asset_flags",[W(t.spokeId),Y(t.hubId,t.asset),V(t.paused),V(t.frozen),V(t.noSeize)])}function Qt(e,t){return ce(e,"set_oracle_sanity_bounds",[D(t.asset),F(t.minPriceWad),F(t.maxPriceWad)])}function er(e,t){return ce(e,"update_indexes",[D(e.caller),G(t.assets.map((e=>Y(e.hubId,e.asset))))])}function tr(e,t){return ce(e,"renew_account",[D(e.caller),z(t.accountNonce)])}function rr(e,t){return ce(e,"create_liquidity_pool",[W(t.hubId),D(t.asset),Rt(t.params)])}function nr(e,t){return ce(e,"upgrade_liquidity_pool_params",[Y(t.hubId,t.asset),Bt(t.params)])}function or(e,t){return ce(e,"claim_revenue",[D(e.caller),G(t.assets.map((e=>Y(e.hubId,e.asset))))])}function sr(e,t){return ce(e,"add_rewards",[D(e.caller),Q(t.rewards)])}function ar(e,t){return ce(e,"update_account_threshold",[D(e.caller),V(t.hasRisks),G(t.accountNonces.map((e=>z(e))))])}const ir="00".repeat(32),ur=e=>{if("string"==typeof e)return K(e);const t=R.hp.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return p.ScVal.scvBytes(t)},lr=(e,...t)=>G([j(e),...t]),cr=e=>te({new_owner:D(e.newOwner),live_until_ledger:W(e.liveUntilLedger)}),dr=e=>te({asset:D(e.asset),bonus:W(e.bonus),borrow_cap:F(e.borrowCap),can_borrow:V(e.canBorrow),can_collateral:V(e.canCollateral),frozen:V(e.frozen),hub_id:W(e.hubId),paused:V(e.paused),liquidation_fees:W(e.liquidationFees),ltv:W(e.ltv),no_seize:V(e.noSeize),spoke_id:W(e.spokeId),supply_cap:F(e.supplyCap),threshold:W(e.threshold)}),pr=e=>te({account:D(e.account),role:j(e.role)});function fr(t,r,s){if(!t.governanceAddress)throw new Error("Stellar governanceAddress is required");const a=new o(t.governanceAddress),i=new e(t.caller,t.sourceSequence);return{xdr:new u(i,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(a.call(r,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const hr=(e,t,r)=>fr(e,"propose",[D(e.caller),t,ur(r)]),mr=(e,t,r)=>fr(e,"execute_self",[H(),t,ur(r)]);function gr(e,t,r){return hr(e,lr("SetSwapAggregator",D(t.aggregator)),r)}function yr(e,t,r){return hr(e,lr("SetPriceAggregator",D(t.aggregator)),r)}function wr(e,t,r){return hr(e,lr("SetAccumulator",D(t.accumulator)),r)}function br(e,t,r){return hr(e,lr("SetPositionLimits",Et(t)),r)}function vr(e,t){return hr(e,lr("CreateHub"),t)}function Sr(e,t){return hr(e,lr("AddSpoke"),t)}function Ir(e,t,r){return hr(e,lr("RemoveSpoke",W(t.spokeId)),r)}function _r(e,t,r){return hr(e,lr("AddAssetToSpoke",dr(t)),r)}function Br(e,t,r){return hr(e,lr("EditAssetInSpoke",dr(t)),r)}function Rr(e,t,r){return hr(e,lr("RemoveAssetFromSpoke",te({hub_asset:Y((n=t).hubId,n.asset),spoke_id:W(n.spokeId)})),r);var n}function Er(e,t,r){return hr(e,lr("SetSpokeLiquidationCurve",te({hf_for_max_bonus_wad:F((n=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:W(n.liquidationBonusFactorBps),spoke_id:W(n.spokeId),target_hf_wad:F(n.targetHfWad)})),r);var n}function Ar(e,t,r){return hr(e,lr("SetPositionManager",D(t.manager),V(t.isActive)),r)}function kr(e,t,r){return hr(e,lr("SetMinBorrowCollateralUsd",F(t.floorWad)),r)}function xr(e,t,r){return hr(e,lr("ApproveToken",D(t.token)),r)}function Tr(e,t,r){return hr(e,lr("RevokeToken",D(t.token)),r)}function qr(e,t,r){return hr(e,lr("ApproveBlendPool",D(t.pool)),r)}function Ur(e,t,r){return hr(e,lr("RevokeBlendPool",D(t.pool)),r)}function Cr(e,t,r){return hr(e,lr("CreateLiquidityPool",te({asset:D((n=t).asset),hub_id:W(n.hubId),params:Rt(n.params)})),r);var n}function Or(e,t,r){return hr(e,lr("UpgradeLiquidityPoolParams",te({hub_asset:Y((n=t).hubId,n.asset),params:Bt(n.params)})),r);var n}function $r(e,t,r){return hr(e,lr("DeployPool",K(t.wasmHash)),r)}function Nr(e,t,r){return hr(e,lr("UpgradePool",K(t.wasmHash)),r)}function Pr(e,t,r){return hr(e,lr("UpgradeController",K(t.wasmHash)),r)}function Mr(e,t,r){return hr(e,lr("MigrateController",W(t.newVersion)),r)}function Lr(e,t,r){return hr(e,lr("TransferCtrlOwnership",cr(t)),r)}function Dr(e,t,r){return hr(e,lr("ConfigureAssetOracle",te({key:At((n=t).key),oracle:$t(n.oracle)})),r);var n}function Fr(e,t,r){return hr(e,lr("EditOracleTolerance",te({key:At((n=t).key),tolerance:W(n.tolerance)})),r);var n}function Wr(e,t,r){return hr(e,lr("UpgradeGov",K(t.wasmHash)),r)}function zr(e,t,r){return hr(e,lr("UpdateGovDelay",W(t.newDelay)),r)}function Vr(e,t,r){return hr(e,lr("GrantGovRole",pr(t)),r)}function Xr(e,t,r){return hr(e,lr("RevokeGovRole",pr(t)),r)}function jr(e,t,r){return hr(e,lr("TransferGovOwnership",cr(t)),r)}function Hr(e,t){const r=G(t.argsXdr.map((e=>p.ScVal.fromXDR(e,"base64")))),n=ur(t.predecessor??ir);return fr(e,"execute",[H(),D(t.target),j(t.functionName),r,n,ur(t.salt)])}function Gr(e,t,r){return mr(e,lr("UpgradeGov",K(t.wasmHash)),r)}function Kr(e,t,r){return mr(e,lr("UpdateGovDelay",W(t.newDelay)),r)}function Zr(e,t,r){return mr(e,lr("GrantGovRole",pr(t)),r)}function Yr(e,t,r){return mr(e,lr("RevokeGovRole",pr(t)),r)}function Jr(e,t,r){return mr(e,lr("TransferGovOwnership",cr(t)),r)}const Qr=e=>G(e.map(D));function en(e,t,r){return fr(e,"propose_canceller_reset",[Qr(t.newCancellers),ur(r)])}function tn(e,t,r){return fr(e,"execute_canceller_reset",[Z(t.executor,D),Qr(t.newCancellers),ur(r)])}function rn(e,t){return fr(e,"set_spoke_asset_flags",[D(e.caller),W(t.spokeId),Y(t.hubId,t.asset),V(t.paused),V(t.frozen),V(t.noSeize)])}function nn(e,t){return fr(e,"set_oracle_sanity_bounds",[D(e.caller),D(t.asset),F(t.minPriceWad),F(t.maxPriceWad)])}function on(e){return fr(e,"create_hub",[D(e.caller)])}function sn(e){return fr(e,"add_spoke",[D(e.caller)])}function an(e,t){return fr(e,"revoke_role_immediate",[D(t.account),j(t.role)])}function un(e){return fr(e,"pause",[D(e.caller)])}function ln(e,t){return hr(e,lr("Unpause"),t)}const cn=e=>e.toXDR("base64"),dn=e=>p.ScVal.fromXDR(e,"base64"),pn=e=>e.map((e=>String(d(dn(e))))).join(":"),fn=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),hn=e=>Number(e),mn=e=>String(e),gn=e=>e instanceof Uint8Array?R.hp.from(e).toString("hex"):R.hp.isBuffer(e)?e.toString("hex"):String(e),yn=["None","Multiply","Long","Short"],wn=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit","flash_pos"],bn=e=>Array.isArray(e)?e:[],vn=(e,t)=>{const r="Borrow"===t;return{action:(n=e[0],wn[hn(n)]??fn(n)),positionType:t,hubId:hn(e[1]),asset:mn(e[2]),scaledAmountRay:fn(e[3]),indexRay:fn(e[4]),amount:fn(e[5]),liquidationThresholdBps:r?void 0:hn(e[6]),liquidationBonusBps:r?void 0:hn(e[7]),loanToValueBps:r?void 0:hn(e[8]),liquidationFeesBps:r?void 0:hn(e[9])};var n},Sn=e=>{return{owner:mn(e[0]),spokeId:hn(e[1]),mode:(t=e[2],yn[hn(t)]??"None")};var t},In=e=>Array.isArray(e)?e[1]:void 0,_n=e=>{const t=(r=e,Array.isArray(r)?mn(r[0]):mn(r));var r;if("Token"===t)return{Token:mn(In(e))};if("Ref"===t)return{Ref:mn(In(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:mn(t.Token)};if(void 0!==t.Ref)return{Ref:mn(t.Ref)}}return{Token:mn(e)}},Bn=e=>{const t=e.tolerance??{};return{assetDecimals:hn(e.asset_decimals),maxPriceStaleSeconds:hn(e.max_price_stale_seconds),sources:bn(e.sources).map((e=>e)),tolerance:{upperRatio:hn(t.upper_ratio_bps),lowerRatio:hn(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:fn(e.min_sanity_price_wad),maxSanityPriceWad:fn(e.max_sanity_price_wad)}},Rn={"market:create":e=>({topic:"market:create",data:{hubId:hn(e.hub_id),baseAsset:mn(e.base_asset),maxBorrowRate:fn(e.max_borrow_rate),baseBorrowRate:fn(e.base_borrow_rate),slope1:fn(e.slope1),slope2:fn(e.slope2),slope3:fn(e.slope3),midUtilization:fn(e.mid_utilization),optimalUtilization:fn(e.optimal_utilization),maxUtilization:fn(e.max_utilization),reserveFactor:hn(e.reserve_factor),marketAddress:mn(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{hubId:hn(e.hub_id),asset:mn(e.asset),maxBorrowRateRay:fn(e.max_borrow_rate),baseBorrowRateRay:fn(e.base_borrow_rate),slope1Ray:fn(e.slope1),slope2Ray:fn(e.slope2),slope3Ray:fn(e.slope3),midUtilizationRay:fn(e.mid_utilization),optimalUtilizationRay:fn(e.optimal_utilization),maxUtilizationRay:fn(e.max_utilization),reserveFactorBps:hn(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:bn(e).map((e=>{return t=bn(e),{hubId:hn(t[0]),asset:mn(t[1]),timestamp:hn(t[2]),supplyIndexRay:fn(t[3]),borrowIndexRay:fn(t[4]),cash:fn(t[5]),suppliedRay:fn(t[6]),borrowedRay:fn(t[7]),revenueRay:fn(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:bn(e).map((e=>{const t=e;return{hubId:hn(t.hub_id),asset:mn(t.asset),params:(r=t.params,{maxBorrowRateRay:fn(r.max_borrow_rate),baseBorrowRateRay:fn(r.base_borrow_rate),slope1Ray:fn(r.slope1),slope2Ray:fn(r.slope2),slope3Ray:fn(r.slope3),midUtilizationRay:fn(r.mid_utilization),optimalUtilizationRay:fn(r.optimal_utilization),maxUtilizationRay:fn(r.max_utilization),reserveFactorBps:hn(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:hn(r.flashloan_fee),assetId:mn(r.asset_id),assetDecimals:hn(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=bn(e);return{topic:"position:batch_update",data:{accountId:fn(t[0]),accountAttributes:Sn(bn(t[1])),updates:[...bn(t[2]).map((e=>vn(bn(e),"Deposit"))),...bn(t[3]).map((e=>vn(bn(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:hn(e.hub_id),asset:mn(e.asset),receiver:mn(e.receiver),caller:mn(e.caller),amount:fn(e.amount),fee:fn(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:_n(e.key),oracle:Bn(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:mn(e.asset),oracle:Bn(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:mn(e.liquidator),accountId:fn(e.account_id),repaidUsdWad:fn(e.repaid_usd_wad),bonusBps:fn(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:fn(e.account_id),totalBorrowUsdWad:fn(e.total_borrow_usd_wad),totalCollateralUsdWad:fn(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:mn(e.token),amount:fn(e.amount),accountId:fn(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:hn(e.hub_id),asset:mn(e.asset),amount:fn(e.amount),fee:fn(e.fee),amountSent:fn(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:mn(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:gn(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:mn(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:mn(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:mn(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:mn(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:gn(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:hn(e.max_supply_positions),maxBorrowPositions:hn(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:fn(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:mn(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:hn(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:fn(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:fn(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:hn(t.liquidation_bonus_factor_bps)}}}},En=Object.freeze(Object.keys(Rn));function An(e,t){const r=pn(e),n=Rn[r];return n?n(d(dn(t))):null}const kn=1e4;function xn(e,t){return`${e}-${BigInt(t).toString(10)}`}function Tn(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function qn(e,t=0){return 1e4*e+t}function Un(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const Cn=(e,t,r)=>{const n=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&n.searchParams.set(e,String(t));return n.toString()};async function On(e,t){if(!t.baseUrl)throw new Error("Stellar quote baseUrl is required");if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Cn(t.baseUrl,"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,simulate:e.simulate,referralId:e.referralId,platform:e.platform,fresh:e.fresh}),n=await fetch(r,t.fetchOptions);if(!n.ok){const e=await n.text().catch((()=>""));throw new Error(`Stellar quote server responded ${n.status} ${n.statusText} for ${r} — ${e}`)}return await n.json()}async function $n(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=Cn(e.baseUrl,"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}function Nn(e,t){const r=e[t];return"function"==typeof r?r.call(e):r}function Pn(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Mn(e){return Ln(Nn(e,"bytes"))}function Ln(e){const t=e;return R.hp.from("value"in t?t.value:t)}const Dn=10,Fn=5,Wn=3,zn=Dn+Fn*N+Wn*P,Vn=16384;class Xn extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const jn=(e,t)=>{throw new Xn(e,t)},Hn=e=>{const t="string"==typeof e?e:e&&"object"==typeof e&&"routeXdr"in e?e.routeXdr:void 0;if("string"==typeof t&&t.length>2*Vn)return jn("OVERSIZED",`encoded route has ${t.length} characters`);try{return Mn(ie(e))}catch(e){return jn("MALFORMED",e instanceof Error?e.message:String(e))}},Gn=e=>{let t;try{t=p.ScVal.fromXDR(e)}catch(e){return jn("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==Pn(t))return jn("MALFORMED","payload must be a StrategyPayload map");const r=Nn(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===Pn(Nn(e,"key"))?Nn(Nn(e,"key"),"sym").toString():"")).join(","))return jn("MALFORMED","payload fields must be exactly amounts, assets, ops");const[n,o,s]=r.map((e=>Nn(e,"val")));return"scvVec"!==Pn(n)||"scvVec"!==Pn(o)||"scvBytes"!==Pn(s)?jn("MALFORMED","payload field has the wrong type"):{amounts:Nn(n,"vec")??[],assets:Nn(o,"vec")??[],ops:Mn(s)}};function Kn(e){const r=Hn(e);0===r.length&&jn("MALFORMED","route is empty"),r.length>Vn&&jn("OVERSIZED",`route has ${r.length} bytes, above ${Vn}`);const n=Gn(r),o=n.assets.length,s=n.amounts.length;0===o&&jn("MALFORMED","asset registry is empty"),(o>M||s>L)&&jn("OVERSIZED",`registries hold ${o} assets and ${s} amounts`);const a=n.assets.map(((e,r)=>"scvAddress"!==Pn(e)?jn("MALFORMED",`assets[${r}] is not an address`):t.fromScAddress(Nn(e,"address")).toString())),i=n.amounts.map(((e,t)=>"scvI128"!==Pn(e)?jn("MALFORMED",`amounts[${t}] is not an i128`):c(e))),u=n.ops;u.length<Dn&&jn("MALFORMED","program header is truncated"),u.length>zn&&jn("OVERSIZED",`program has ${u.length} bytes, above ${zn}`);const l=e=>{const t=u[e];return void 0===t?jn("MALFORMED",`program byte ${e} is missing`):t},d=l(0);d!==k&&jn("UNSUPPORTED_VERSION",`program version ${d}, expected ${k}`);const p=l(8),f=l(9);0===p&&jn("INVALID_STRUCTURE","program has no instructions"),(p>N||f>P)&&jn("OVERSIZED",`program declares ${p} instructions and ${f} weights`);const h=Dn+Fn*p;u.length!==h+Wn*f&&jn("MALFORMED","program length does not match its instruction and weight counts");const m=l(1),g=l(2),y=l(3);(m>=o||g>=o||y>=s)&&jn("MALFORMED","header index is outside its registry"),m===g&&jn("INVALID_STRUCTURE","token_in equals token_out");const w=u.readUInt32BE(4),b=[];for(let e=0;e<f;e+=1){const t=u.readUIntBE(h+Wn*e,Wn);(0===t||t>x)&&jn("INVALID_STRUCTURE",`split weight ${t} outside 1..=${x}`),b.push(t)}const v=e=>a[e]??jn("MALFORMED",`asset index ${e} is outside the registry`),S=e=>i[e]??jn("MALFORMED",`amount index ${e} is outside the registry`),I=[];let _;for(let e=0;e<p;e+=1){const t=Dn+Fn*e,r=l(t),n=l(t+1),o=l(t+2),a=l(t+3),i=l(t+4),u=E.find((e=>A[e]===r));let c;if(u||r===T||r===q||jn("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),n===U)c={kind:"all"};else if(n===C)void 0!==_&&_===a||jn("INVALID_STRUCTURE",`instruction ${e} does not chain onto its predecessor`),c={kind:"prev"};else if(n>=$){const t=b[n-$];void 0===t&&jn("MALFORMED",`instruction ${e} weight index is out of range`),c={kind:"ppm",ppm:t}}else c={kind:"fixed",amount:S(n-O)};const d=v(o);r!==T&&r!==q?(a===i&&jn("INVALID_STRUCTURE",`instruction ${e} swaps a token for itself`),I.push({kind:"swap",venue:u,mode:c,pool:d,tokenIn:v(a),tokenOut:v(i)}),_=i):("all"!==c.kind&&jn("MALFORMED",`liquidity instruction ${e} must use mode All`),i>=s&&jn("MALFORMED",`instruction ${e} amount index is out of range`),I.push({kind:r===T?"burn":"mint",pool:d,shareToken:v(a),amountIndex:i}),_=r===q?a:void 0)}const B=S(y);return B<=0n&&jn("MIN_OUT_TOO_LOW",`encoded total_min_out is ${B}`),{version:d,tokenIn:v(m),tokenOut:v(g),totalMinOut:B,referralId:w,assets:a,amounts:i,ops:I,weights:b}}function Zn(e,t){if(i.isValidContract(e))return e;if(!t)return jn("EXPECTATION_MISSING",`token ${e} is not a contract id; pass \`network\` to derive its asset contract`);try{const n=e.indexOf(":");return("XLM"===e||"native"===e?r.native():new r(e.slice(0,n),e.slice(n+1))).contractId(B[t])}catch{return jn("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Yn=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):jn("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function Jn(e,t){const r=Yn(t.minOut,"expected.minOut");r<=0n&&jn("EXPECTATION_MISSING","expected.minOut must be positive");const n=Kn(e);if(n.tokenIn!==t.tokenIn&&jn("TOKEN_IN_MISMATCH",`route spends ${n.tokenIn}, expected ${t.tokenIn}`),n.tokenOut!==t.tokenOut&&jn("TOKEN_OUT_MISMATCH",`route delivers ${n.tokenOut}, expected ${t.tokenOut}`),n.totalMinOut<r&&jn("MIN_OUT_TOO_LOW",`route enforces a minimum of ${n.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Yn(t.amountIn,"expected.amountIn");for(const t of n.ops)"swap"===t.kind&&"fixed"===t.mode.kind&&t.tokenIn===n.tokenIn&&t.mode.amount>e&&jn("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return n}const Qn=e=>ne(e).toXDR("base64");function eo(t,r){if(!t.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const s=new o(t.routerAddress),a=new e(t.caller,t.sourceSequence),i=ie(((e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e)(r,t.referralId));return{xdr:new u(a,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(s.call("execute_strategy",D(t.caller),F(t.totalIn),i)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function to(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(no),splitPpm:e.splitPpm}))):[{hops:e.hops.map(no),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function ro(e,t={}){const r=t.expected??{},n="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:to(e,t),o=[e.amountOutMin,r.minOut].filter((e=>void 0!==e)).map((e=>{if("bigint"==typeof e)return e;if("string"!=typeof e||!/^\d+$/.test(e))throw new Xn("MALFORMED","minimum output must be a base-unit integer string");return BigInt(e)})).reduce(((e,t)=>void 0===e||t>e?t:e),void 0);if(void 0===o)throw new Xn("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return Jn(n,{tokenIn:Zn(r.tokenIn??e.from,t.network),tokenOut:Zn(r.tokenOut??e.to,t.network),minOut:o,amountIn:r.amountIn??e.amountIn}),n}const no=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function oo(e){try{const{envelopeXdr:r,networkPassphrase:n,routerAddress:o,viewer:s,operationIndex:a}=e;if(!n||!i.isValidContract(o)||new t(s).toString()!==s||"string"!=typeof r||r.length>1048576||r.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)||void 0!==a&&(!Number.isSafeInteger(a)||a<0))return null;const l=u.fromXDR(r,n),d="innerTransaction"in l?l.innerTransaction:l;if(void 0!==a&&a>=d.operations.length)return null;let p=null;for(const[e,r]of d.operations.entries()){if(void 0!==a&&e!==a)continue;if("invokeHostFunction"!==r.type)continue;const n=r.func;if("hostFunctionTypeInvokeContract"!==Pn(n))continue;const u=Nn(n,"invokeContract");if(t.fromScAddress(Nn(u,"contractAddress")).toString()!==o||"execute_strategy"!==Nn(u,"functionName").toString())continue;const l=Nn(u,"args"),[d,f,h]=l;if(3!==l.length||!d||!f||!h||"scvAddress"!==Pn(d)||"scvI128"!==Pn(f)||"scvBytes"!==Pn(h))return null;if(t.fromScAddress(Nn(d,"address")).toString()!==s)continue;const m=c(f);if(m<=0n)return null;const g=Kn(Mn(h));if(g.tokenIn===g.tokenOut||!i.isValidContract(g.tokenIn)||!i.isValidContract(g.tokenOut))return null;if(p)return null;p={tokenIn:g.tokenIn,tokenOut:g.tokenOut,amountInAtoms:m.toString(),operationIndex:e}}return p}catch{return null}}class so extends Error{code;offender;constructor(e,t,r){super(`Stellar authorization check failed [${e}]: ${t}${r?` — ${r.contract}.${r.fn}(${r.args.join(", ")})`:""}`),this.name="StellarAuthPolicyError",this.code=e,this.offender=r}}const ao=e=>e&&"scvAddress"===Pn(e)?t.fromScAddress(Nn(e,"address")).toString():void 0,io=e=>e&&"scvI128"===Pn(e)?c(e):void 0,uo=e=>e&&"scvVec"===Pn(e)?Nn(e,"vec")??[]:void 0,lo=(e,t)=>{if(!e||"scvMap"!==Pn(e))return;const r=(Nn(e,"map")??[]).find((e=>"scvSymbol"===Pn(Nn(e,"key"))&&Nn(Nn(e,"key"),"sym").toString()===t));return r?Nn(r,"val"):void 0},co=e=>ao(e)??io(e)?.toString()??e.toXDR("base64"),po=e=>({contract:t.fromScAddress(Nn(e,"contractAddress")).toString(),fn:Nn(e,"functionName").toString(),args:Nn(e,"args").map(co)}),fo=e=>{const t=Nn(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===Pn(t)?Nn(t,"contractFn"):void 0};function ho(e,r,n){const o=e.filter((e=>{const o=Nn(e,"credentials"),s=Pn(o);if("sorobanCredentialsAddress"!==s&&"sorobanCredentialsSourceAccount"!==s)throw new so("MALFORMED_TRANSACTION","unsupported authorization credentials");return("sorobanCredentialsAddress"===s?t.fromScAddress(Nn(Nn(o,"address"),"address")).toString():n??r.caller)===r.caller}));if(o.length>1)throw new so("DUPLICATE_ENTRY",`${o.length} authorization entries for ${r.caller}, expected one`);const s=o[0];if(!s)return;const a=fo(Nn(s,"rootInvocation"));if(!a)throw new so("UNEXPECTED_ROOT","root is not a contract call");const i=po(a);if(i.contract!==r.root.contract||i.fn!==r.root.fn)throw new so("UNEXPECTED_ROOT",`expected ${r.root.contract}.${r.root.fn}`,i);const u=r.transfers.map((()=>0n)),l=(r.calls??[]).map((()=>0));for(const e of Nn(Nn(s,"rootInvocation"),"subInvocations")){const t=fo(e);if(!t)throw new so("UNEXPECTED_CALL","sub-invocation is not a contract call");const n=po(t);if(Nn(e,"subInvocations").length>0)throw new so("NESTED_INVOCATION","sub-invocation carries its own sub-invocations",n);const o=(r.calls??[]).findIndex((e=>e.contract===n.contract&&e.fn===n.fn));if(-1!==o){const e=(r.calls??[])[o],s=e.reject(Nn(t,"args"));if(s)throw new so("UNEXPECTED_CALL",s,n);if(l[o]=(l[o]??0)+1,(l[o]??0)>e.maxCount)throw new so("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,n);continue}if("transfer"!==n.fn||3!==Nn(t,"args").length)throw new so("UNEXPECTED_CALL","only `transfer` is allowed",n);if(!r.transfers.some((e=>e.token===n.contract)))throw new so("UNEXPECTED_TOKEN","transfer on an unexpected token",n);const[s,a,i]=Nn(t,"args");if(ao(s)!==r.caller)throw new so("UNEXPECTED_SENDER","transfer is not from the caller",n);const c=ao(a),d=r.transfers.findIndex((e=>e.token===n.contract&&e.to===c));if(-1===d)throw new so("UNEXPECTED_RECIPIENT","transfer to an unexpected recipient",n);const p=io(i),f=r.transfers[d],h=(u[d]??0n)+(p??0n);if(void 0===p||p<=0n||h>f.maxAmount)throw new so("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,n);u[d]=h}}const mo=e=>{throw new so("MALFORMED_TRANSACTION",e)},go=(e,t)=>{const r=new Map;for(const t of uo(e)??mo("payments argument is not a vector")){const[e,n]=uo(t)??[],o=ao(lo(e,"asset")),s=io(n);if(void 0===o||void 0===s||s<0n)return mo("payment is not a (HubAssetKey, i128) tuple");r.set(o,(r.get(o)??0n)+s)}return[...r].map((([e,r])=>({token:e,to:t,maxAmount:r})))},yo=new Set([1,3,5]),wo=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(ao(e[0])!==t)return"`from` is not the caller";if(ao(e[1])!==r||ao(e[2])!==r)return"`spender` and `to` must be the lending controller";const n=uo(e[3]);if(!n)return"requests is not a vector";for(const e of n){const t=lo(e,"request_type");if(!t||"scvU32"!==Pn(t)||!yo.has(Nn(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function bo(e,t,r){const{contract:n,fn:o}=po(t),s=Nn(t,"args"),a={caller:e,root:{contract:n,fn:o},transfers:[]};if(n===r.governance)return a;if(n===r.aggregatorRouter){if("execute_strategy"!==o)return a;const t=io(s[1]);if(ao(s[0])!==e||void 0===t||"scvBytes"!==Pn(s[2]))return mo("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=Kn(Mn(s[2]));return a.transfers=[{token:r.tokenIn,to:n,maxAmount:t}],a}if(n!==r.lendingController)throw new so("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${n}; pass an explicit policy`);if(ao(s[0])!==e)throw new so("CALLER_MISMATCH",`${o} is not invoked for ${e}`);switch(o){case"supply":a.transfers=go(s[3],r.lendingPool);break;case"repay":case"liquidate":a.transfers=go(s[2],r.lendingPool);break;case"multiply":{const e=s[8];e&&"scvVoid"!==Pn(e)&&(a.transfers=go(p.ScVal.scvVec([e]),n));break}case"migrate_from_blend":{const t=ao(s[4])??mo("blend_pool is not an address");a.calls=[wo(t,e,n)];break}}return a}const vo=e=>{let t;try{t=p.TransactionEnvelope.fromXDR(e,"base64")}catch{return mo("not a transaction envelope")}if("envelopeTypeTx"!==Pn(t))return mo("expected a regular (v1) transaction");const r=Nn(Nn(t,"v1"),"tx"),n=Nn(r,"operations")[0];if(!n||1!==Nn(r,"operations").length)return mo("expected exactly one operation");const o=Nn(n,"body");if("invokeHostFunction"!==Pn(o))return mo("operation is not a contract invocation");const s=Nn(o,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==Pn(Nn(s,"hostFunction"))?mo("host function is not a contract call"):{source:(a=Nn(n,"sourceAccount")??Nn(r,"sourceAccount"),i.encodeEd25519PublicKey(Ln("keyTypeMuxedEd25519"===Pn(a)?Nn(Nn(a,"med25519"),"ed25519"):Nn(a,"ed25519")))),op:s,call:Nn(Nn(s,"hostFunction"),"invokeContract")};var a};function So(e,t){const r=vo(e);if(void 0!==t.builtXdr&&Nn(vo(t.builtXdr).op,"hostFunction").toXDR("base64")!==Nn(r.op,"hostFunction").toXDR("base64"))throw new so("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",po(r.call));const n=t.policy??bo(t.caller,r.call,{..._(t.network),...t.deployment});ho(Nn(r.op,"auth"),n,r.source)}function Io(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function _o(e,t,r){const n=r?.instructionLeeway??2e7;if(!Number.isInteger(n)||n<0||n>4294967295)throw new Error("instructionLeeway must be an integer from 0 to 4294967295");const o=u.fromXDR(t,r?.network?B[r.network]:"");try{const t=await e.simulateTransaction(o,{cpuInstructions:n});if(l.Api.isSimulationError(t))throw new Error(t.error);return l.assembleTransaction(o,t).build().toXDR()}catch(e){if(r?.invokedContractId)throw Io(r.invokedContractId,e);throw e}}async function Bo(e,t,r){return _o(e,t.xdr,r)}function Ro(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function Eo(e,t){return new Uint8Array(0)}const Ao=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return R.hp.from(t,"hex")};function ko(t){const r=new e(t.caller,t.sourceSequence),n=new o(t.forwarderAddress).call("mint_and_forward",p.ScVal.scvBytes(Ao(t.message)),p.ScVal.scvBytes(Ao(t.attestation)));return{xdr:new u(r,{fee:t.fee??"10000000",networkPassphrase:B[t.network]}).addOperation(n).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const xo=10n**27n,To=10n**18n,qo=10000n,Uo=27,Co=18;function Oo(e,t="value"){let r;if("bigint"==typeof e)r=e;else if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Stellar math: ${t} must be a safe integer, got ${e}`);r=BigInt(e)}else{const n=e.trim();if(!/^-?\d+$/.test(n))throw new Error(`Stellar math: ${t} must be a decimal integer string, got "${e}"`);r=BigInt(n)}if(r<0n)throw new Error(`Stellar math: ${t} must be non-negative, got ${r}`);return r}function $o(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function No(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");const n=e*t,o=n/r;return n%r===0n?o:o+1n}function Po(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function Mo(e,t){if(0n===t)throw new Error("Stellar math: division by zero");const r=e/t;return e%t>=t/2n+t%2n?r+1n:r}const Lo=e=>10n**BigInt(e);function Do(e,t,r){return t===r?e:r>t?e*Lo(r-t):e/Lo(t-r)}function Fo(e,t,r){if(t===r)return e;if(r>t)return e*Lo(r-t);const n=Lo(t-r),o=e/n;return e%n===0n?o:o+1n}function Wo(e,t,r){return t===r?e:r>t?e*Lo(r-t):Mo(e,Lo(t-r))}const zo={floor:$o,ceil:No,halfUp:Po},Vo={floor:Do,ceil:Fo,halfUp:Wo};function Xo(e,t,r,n){return Vo[n](zo[n](e,t,xo),Uo,r)}function jo(e,t,r){return Xo(Oo(e,"scaledRay"),Oo(t,"indexRay"),r,"floor")}function Ho(e,t,r){return Xo(Oo(e,"scaledRay"),Oo(t,"indexRay"),r,"ceil")}function Go(e,t,r){return Xo(Oo(e,"scaledRay"),Oo(t,"indexRay"),r,"halfUp")}function Ko(e,t){if(t>Uo)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return Do(e,t,Uo)}function Zo(e,t,r,n){const o=zo[n](e,t,xo),s=Vo[n](o,Uo,Co);return zo[n](s,r,To)}function Yo(e,t,r,n){const o=Vo[n](Ko(e,t),Uo,Co);return zo[n](o,r,To)}const Jo=e=>Number(e)/1e18,Qo=e=>Number(e)/1e27,es=(e,t)=>Number(e)/10**t;function ts(e,t){if(!Number.isFinite(e)||e<=0||e>=1e21)return 0n;const r=e.toFixed(t),[n="0",o=""]=r.split(".");return BigInt(n+o.padEnd(t,"0"))}const rs=e=>ts(e,Co),ns=(e,t)=>Po(e,t,xo),os=(e,t)=>Po(e,xo,t);function ss(e,t){return 0n===t?0n:os(e,t)}function as(e,t){const r=e>xo?xo:e,n=Oo(t.baseRateRay,"irm.baseRateRay"),o=Oo(t.slope1Ray,"irm.slope1Ray"),s=Oo(t.slope2Ray,"irm.slope2Ray"),a=Oo(t.slope3Ray,"irm.slope3Ray"),i=Oo(t.midUtilizationRay,"irm.midUtilizationRay"),u=Oo(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),l=Oo(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<i)c=n+os(ns(r,o),i);else if(r<u){const e=u-i;c=n+o+os(ns(r-i,s),e)}else{const e=xo-u;c=n+o+s+(0n===e?0n:os(ns(r-u,a),e))}return c>l?l:c}function is(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:Po(ns(e,t),qo-BigInt(r),qo)}const us=e=>Qo(e),ls=e=>Math.expm1(Qo(e)),cs=5n*To,ds=(e,t,r)=>`${e}:${t}:${r}`;function ps(e,t,r,n){const o=Array.isArray(e)?e:void 0,s=o?o.find((e=>e.spokeId===t&&e.hubId===r&&e.asset===n)):e[ds(t,r,n)]??Object.values(e).find((e=>e.spokeId===t&&e.hubId===r&&e.asset===n));if(!s)throw new Error(`Stellar math: no reserve for ${ds(t,r,n)}`);return s}const fs=/^0*[1-9]\d*$/,hs=e=>"string"==typeof e&&fs.test(e)?BigInt(e).toString():null,ms=(e,t)=>`${e}:${t}`;function gs(e){const t=new Map,r=new Map,n=new Set,o=new Set;for(const s of e?.indexes??[]){const e=ms(s.hubId,s.asset),a=hs(s.supplyIndex),i=hs(s.borrowIndex),u=hs(s.usdPrice),l=t.get(e),c=l&&hs(l.supplyIndex)===a&&hs(l.borrowIndex)===i&&hs(l.usdPrice)===u;null==a||null==i||null==u||l&&!c?n.add(e):l||t.set(e,s);const d=!1===s.valid||!0===s.stale||!0===s.deviation,p=r.get(s.asset);null==u||d||void 0!==p&&p.toString()!==u?o.add(s.asset):void 0===p&&r.set(s.asset,BigInt(u))}for(const e of n)t.delete(e);for(const e of o)r.delete(e);return{indexes:t,prices:r,rejectedIndexKeys:n,rejectedAssets:o}}const ys=(e,t)=>$o(e,BigInt(t),qo);function ws(e,t,r,n){const o="supply"===e.side,s=Math.min(e.entryLtvBps,e.entryLiquidationThresholdBps);return{side:e.side,hubId:e.hubId,asset:e.asset,decimals:e.decimals,scaledRay:e.scaledRay.toString(),indexRay:e.indexRay.toString(),usdPriceWad:e.priceWad.toString(),usdPrice:Jo(e.priceWad),amountBase:t.toString(),amountShort:es(t,e.decimals),usdWad:r.toString(),usd:Jo(r),gateUsdWad:n.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:o?ys(n,s).toString():"0",liquidationWeightedUsdWad:o?ys(n,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function bs(e){if("supply"===e.side)return ws(e,Xo(e.scaledRay,e.indexRay,e.decimals,"floor"),Zo(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),Zo(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Xo(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=Zo(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ws(e,t,r,r)}function vs(e,t,r,n){const o=Ko(t,r);return"supply"===e?$o(o,xo,n):No(o,xo,n)}function Ss(e,t,r,n){const o=Ko(t,r);return"supply"===e?No(o,xo,n):$o(o,xo,n)}function Is(e,t){return bs({...e,scaledRay:vs(e.side,t,e.decimals,e.indexRay)})}const _s=(...e)=>{for(const t of e){const e=hs(t);if(null!=e)return BigInt(e)}return xo};function Bs(e,t,r,n){const o=Oo("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===o)return null;const s=n.indexes.get(ms(t.hubId,t.asset)),a=n.prices.get(t.asset),i="supply"===e?_s(s?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):_s(s?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),u=a??rs(r.usdPrice);return bs({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:o,indexRay:i,priceWad:u,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==s&&void 0!==a})}const Rs=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function Es(e,t,r,n,o){const s=Rs(t,(e=>e.usdWad)),a=Rs(t,(e=>e.ltvWeightedUsdWad)),i=Rs(t,(e=>e.liquidationWeightedUsdWad)),u=Rs(r,(e=>e.usdWad)),l=0n===u?null:$o(i,To,u),c=0n===i?0:Number(u)/Number(i)*100,d=a<n||a<=u?0n:a-u;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:s.toString(),totalCollateralUsd:Jo(s),ltvWeightedCollateralUsdWad:a.toString(),ltvWeightedCollateralUsd:Jo(a),liquidationWeightedCollateralUsdWad:i.toString(),liquidationWeightedCollateralUsd:Jo(i),totalDebtUsdWad:u.toString(),totalDebtUsd:Jo(u),healthFactorWad:null===l?null:l.toString(),healthFactor:null===l?null:Jo(l),healthPercent:c,borrowLimitUsdWad:a.toString(),borrowLimitUsd:Jo(a),availableBorrowUsdWad:d.toString(),availableBorrowUsd:Jo(d),minBorrowCollateralUsdWad:n.toString(),minBorrowCollateralUsd:Jo(n),isLiquidatable:null!==l&&l<To,liveDataValid:o}}function As(e){const{positions:t,reserves:r,liveState:n}=e,o=t[0];if(!o)throw new Error("Stellar math: computeAccountRisk needs at least one position row");for(const e of t)if(e.accountId!==o.accountId)throw new Error(`Stellar math: computeAccountRisk received mixed account ids (${o.accountId}, ${e.accountId})`);const s=gs(n),a=[],i=[];for(const e of t){const t=ps(r,e.spokeId,e.hubId,e.asset),n=Bs("supply",e,t,s);n&&a.push(n);const o=Bs("borrow",e,t,s);o&&i.push(o)}const u=null!=n?.minBorrowCollateralUsdWad?Oo(n.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):cs,l=void 0!==n&&[...a,...i].every((e=>e.liveDataUsed));return Es({accountId:o.accountId,owner:o.owner,spokeId:o.spokeId,mode:o.positionMode},a,i,u,l)}const ks=200n,xs=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),Ts=e=>e<0n?0n:e,qs=(e,t,r,n)=>({amountBase:e.amount,amountShort:es(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:n}),Us=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function Cs(e){const t=e.assetDecimals,r=Oo(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:ts(e.hubPool.suppliedShort,t),borrowedBase:ts(e.hubPool.borrowedShort,t),cashBase:ts(e.availableLiquidityShort,t),spokeSuppliedBase:ts(e.suppliedShort,t),spokeBorrowedBase:ts(e.borrowedShort,t),maxUtilizationRay:r>=xo?null:r}}const Os=(e,t)=>e<=0n?null:Number(t)/Number(e);function $s(e,t){if(e<=0n||!t(0n))return 0n;let r=0n,n=e+1n;for(;n-r>1n;){const e=(r+n)/2n;t(e)?r=e:n=e}return r}const Ns=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Ps(e,t,r){if(t.paused)return Us("paused");if(t.frozen)return Us("frozen");if(!t.isBorrowable)return Us("cap");const n=t.assetDecimals,o=Cs(t),s=Ns(e.borrows,t),a=gs(r).indexes.get(ms(t.hubId,t.asset)),i=s?BigInt(s.indexRay):Oo(a?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),u=s?BigInt(s.usdPriceWad):function(e,t){return gs(t).prices.get(e.asset)??rs(e.usdPrice)}(t,r),l=s?BigInt(s.scaledRay):0n,c=BigInt(e.totalDebtUsdWad)-(s?BigInt(s.usdWad):0n),d=BigInt(e.ltvWeightedCollateralUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=[];if(d<p)f.push({amount:0n,reason:"minCollateral"});else{const t=d-BigInt(e.totalDebtUsdWad),r=t<=0n||u<=0n?0n:$o(t,10n**BigInt(n),u),o=e=>c+Zo(l+vs("borrow",e,n,i),i,u,"ceil");f.push({amount:0n===r?0n:$s(r+16n,(e=>o(e)<=d)),reason:"ltv"})}f.push({amount:Ts(Oo(t.borrowCap,"borrowCap")-o.spokeBorrowedBase),reason:"cap"});const h=Po(o.suppliedBase,200n,qo);f.push({amount:Ts(o.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const n=Ko(e.suppliedBase,t);return 0n===n?null:$s(Ts($o(e.suppliedBase,r,xo)-e.borrowedBase)+16n,(o=>ss(Ko(e.borrowedBase+o,t),n)<=r))}(o,n);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=xs(f);return qs(g,n,!1,Os(o.suppliedBase,o.borrowedBase+g.amount))}function Ms(e,t,r){if(t.paused)return Us("paused");const n=Ns(e.supplies,t);if(!n)return Us(null);const o=n.decimals,s=Cs(t),a=BigInt(n.scaledRay),i=BigInt(n.indexRay),u=BigInt(n.usdPriceWad),l=BigInt(n.amountBase),c=Xo(a,i,o,"halfUp"),d=BigInt(e.totalDebtUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=BigInt(Math.min(n.entryLtvBps,n.entryLiquidationThresholdBps)),h=[];let m=!0;if(d>0n&&f>0n){const t=d>p?d:p,r=p>d?"minCollateral":"healthFactor",s=BigInt(e.ltvWeightedCollateralUsdWad)-BigInt(n.ltvWeightedUsdWad);if(s<t){m=!1;const e=t-s,l=No(e,qo,f),d=BigInt(n.gateUsdWad)-l,p=d<=0n?0n:$o(d,10n**BigInt(o),u),g=c>0n?c-1n:0n,y=p+16n>g?g:p+16n,w=e=>{const t=Ss("supply",e,o,i);return $o(Zo(t>=a?0n:a-t,i,u,"floor"),f,qo)};h.push({amount:$s(y,(t=>w(t)>=e)),reason:r})}}h.push({amount:l,reason:null}),h.push({amount:s.cashBase,reason:"liquidity"});const g=function(e,t){const r=e.maxUtilizationRay;if(null===r||0n===e.borrowedBase)return null;if(0n===r)return 0n;const n=No(e.borrowedBase,xo,r),o=e.suppliedBase<n?0n:e.suppliedBase-n+16n,s=Ko(e.borrowedBase,t);return $s(o>e.suppliedBase?e.suppliedBase:o,(n=>{const o=Ko(e.suppliedBase-n,t);return o>0n&&ss(s,o)<=r}))}(s,o);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=xs(h),w=m&&y.amount>=l;return qs(y,o,w,Os(s.suppliedBase-y.amount,s.borrowedBase))}function Ls(e){if(e.paused)return Us("paused");if(e.frozen)return Us("frozen");const t=e.assetDecimals,r=Cs(e),n={amount:Ts(Oo(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return qs(n,t,!1,Os(r.suppliedBase+n.amount,r.borrowedBase))}function Ds(e,t,r){if(t.paused)return Us("paused");const n=Ns(e.borrows,t);if(!n)return Us(null);const o=n.decimals,s=Cs(t),a=BigInt(n.amountBase),i=void 0===r?null:Oo(r,"walletBalance"),u=null!==i&&i<a?{amount:i,reason:"liquidity"}:{amount:a,reason:null};return qs(u,o,u.amount>=a,Os(s.suppliedBase,Ts(s.borrowedBase-u.amount)))}const Fs=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,Ws=e=>{if("bigint"==typeof e)return e;const t=e.trim();if(!/^-?\d+$/.test(t))throw new Error(`Stellar math: delta amountBase must be an integer string, got "${e}"`);return BigInt(t)};function zs(e,t){const r=[...e.supplies],n=[...e.borrows];for(const e of t){const t="supply"===e.side?r:n,o=t.findIndex((t=>Fs(t,e))),s=-1===o?void 0:t[o],a=Ws(e.amountBase);let i;if(s){const e={side:s.side,hubId:s.hubId,asset:s.asset,decimals:s.decimals,indexRay:BigInt(s.indexRay),priceWad:BigInt(s.usdPriceWad),entryLtvBps:s.entryLtvBps,entryLiquidationThresholdBps:s.entryLiquidationThresholdBps,entryLiquidationBonusBps:s.entryLiquidationBonusBps,entryLiquidationFeesBps:s.entryLiquidationFeesBps,liveDataUsed:s.liveDataUsed},t=BigInt(s.scaledRay);let r;if(a>=0n)r=t+vs(e.side,a,e.decimals,e.indexRay);else{const n=-a,o=n>=("supply"===e.side?Xo(t,e.indexRay,e.decimals,"halfUp"):BigInt(s.amountBase))?t:Ss(e.side,n,e.decimals,e.indexRay);r=o>=t?0n:t-o}i=0n===r?null:bs({...e,scaledRay:r})}else i=a<=0n?null:Is(Vs(e),a);-1===o?i&&t.push(i):i?t[o]=i:t.splice(o,1)}return Es({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,n,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Vs(e){const t=e.reserve;if(!t)throw new Error(`Stellar math: projectAccountRisk needs \`reserve\` for a new ${e.side} position on ${e.hubId}:${e.asset}`);return{side:e.side,hubId:e.hubId,asset:e.asset,decimals:t.assetDecimals,indexRay:Oo("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:rs(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function Xs(e,t=0n,r=0n){const n=e.assetDecimals,o=e=>e<0n?0n:e,s=o(ts(e.hubPool.suppliedShort,n)+Ws(t)),a=ss(Ko(o(ts(e.hubPool.borrowedShort,n)+Ws(r)),n),Ko(s,n)),i=as(a,e.irm),u=is(a,i,e.irm.reserveFactorBps);return{utilization:Qo(a),utilizationRay:a.toString(),borrowAprRay:i.toString(),supplyAprRay:u.toString(),borrowApr:us(i),supplyApr:us(u),borrowApy:ls(i),supplyApy:ls(u)}}const js={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},5:{name:"PoolAlreadyDeployed",message:"Singleton pool, controller, or price aggregator already recorded."},6:{name:"InvalidAsset",message:"Invalid asset address."},7:{name:"AssetsAreTheSame",message:"Same market or token where distinct HubAssetKeys or underlying assets, respectively, are required."},8:{name:"WrongToken",message:"Params.asset_id differs from the market's asset."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},13:{name:"AccountNotInMarket",message:"Caller lacks the account's position NFT, or the account has no metadata."},14:{name:"AmountMustBePositive",message:"The amount must be greater than zero."},16:{name:"InvalidPayments",message:"Payments or route list empty when required, non-empty when forbidden, or over the view limit."},18:{name:"NotSmartContract",message:"Address is not a deployed contract."},24:{name:"AccountNotFound",message:"Account id has no state, or its NFT owner is unresolvable."},25:{name:"AccountModeMismatch",message:"Account mode differs from the call's required mode."},27:{name:"AggregatorNotSet",message:"Swap or price aggregator not configured."},29:{name:"PositionLimitsNotSet",message:"No position limits stored."},30:{name:"PoolNotInitialized",message:"Pool or controller unset, or market params/state missing."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},33:{name:"MathOverflow",message:"Checked arithmetic overflow or failed narrowing conversion."},34:{name:"InternalError",message:"Internal invariant failed. Report it."},36:{name:"InvalidPositionLimits",message:"Supply or borrow limit is zero or above POSITION_LIMIT_MAX (5)."},38:{name:"SpotOnlyNotProductionSafe",message:"Every oracle source reads an unsmoothed spot market."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},40:{name:"TimelockOperationExpired",message:"Scheduled operation's grace period elapsed."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},42:{name:"BlendPoolNotApproved",message:"Blend pool not approved."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},45:{name:"RegistryCapReached",message:"Account already has MAX_DELEGATES (16)."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},47:{name:"BorrowRoundsToZeroShares",message:"Positive borrow mints zero scaled debt shares."},48:{name:"CannotRemoveLastProposer",message:"Revoke would leave no proposer."},49:{name:"WithdrawRoundsToZeroShares",message:"Positive withdrawal burns zero scaled supply shares."},50:{name:"NetSettleRoundsToZeroShares",message:"Positive net settlement burns zero shares."},51:{name:"SupplyRoundsToZeroShares",message:"Positive supply mints zero scaled shares."},52:{name:"RepayRoundsToZeroShares",message:"Positive net repayment burns zero scaled debt shares."},53:{name:"PositionNftNotSet",message:"NFT address unset on a path needing it, such as account creation. Ownership lookup can return #24 instead."},54:{name:"PositionNftAlreadyDeployed",message:"Position-NFT address already recorded."},55:{name:"DivisionByZero",message:"Fixed-point multiply-divide with zero denominator."},100:{name:"InsufficientCollateral",message:"Post-operation LTV-weighted collateral below total debt, or health factor below 1 WAD."},101:{name:"HealthFactorTooHigh",message:"Target has no debt or health factor >= 1 WAD; not liquidatable."},102:{name:"HealthFactorTooLow",message:"Update_account_threshold with has_risks = true ends below 1.05 WAD. A gated liquidation-tuple refresh skips a tuple that fails its hypothetical health-factor check."},104:{name:"NotCollateral",message:"Spoke listing disallows the asset as collateral."},107:{name:"AssetNotBorrowable",message:"Spoke listing disallows borrowing the asset."},109:{name:"PositionLimitExceeded",message:"New slot exceeds the position limit, or a sub-3-decimal supply leg would coexist with another supply slot."},110:{name:"PositionNotFound",message:"Reserved code; no longer emitted."},111:{name:"InvalidPositionMode",message:"Mode is not Multiply, Long, or Short."},112:{name:"InsufficientLiquidity",message:"Market cash below the draw, or the draw breaks the liquidation buffer."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},114:{name:"CannotCleanBadDebt",message:"Account fails the bad-debt gate."},115:{name:"WithdrawLessThanFee",message:"Liquidation protocol fee exceeds the gross withdrawal."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},118:{name:"OptUtilTooHigh",message:"Optimal utilization >= 100%."},119:{name:"InvalidReserveFactor",message:"Reserve factor >= 100%."},120:{name:"DebtPositionNotFound",message:"No debt position for that hub asset."},121:{name:"CollateralPositionNotFound",message:"No supply position for that hub asset."},122:{name:"CannotCloseWithRemainingDebt",message:"Close_position with borrow positions open."},123:{name:"PoolInsolvent",message:"Supplier claims exceed cash plus debt, or zero supply with debt outstanding."},126:{name:"MinBorrowCollateralNotMet",message:"With debt outstanding, LTV-weighted collateral below the USD floor, or a sub-3-decimal supply leg under 2 raw units after floor conversion."},127:{name:"UtilizationAboveMax",message:"Post-operation utilization above max_utilization."},128:{name:"BaseRateNegative",message:"Negative base borrow rate."},129:{name:"SlopeNonMonotonic",message:"Rate slopes do not increase monotonically."},130:{name:"MaxRateBelowBase",message:"Max borrow rate not strictly above base."},131:{name:"MaxBorrowRateTooHigh",message:"Max borrow rate exceeds MAX_BORROW_RATE_RAY (200% APR)."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},133:{name:"SelfLiquidationNotAllowed",message:"SeizeMode::Credit(id) receiver is the liquidated account. Owners may still liquidate their own account."},134:{name:"InvalidLiquidationCurve",message:"Curve bounds fail validation."},135:{name:"FullCloseRequired",message:"Retired; no error site."},201:{name:"InvalidAggregator",message:"Proposed aggregator is not a deployed contract."},204:{name:"InvalidOracleTokenType",message:"Reflector asset given as string; only address or symbol accepted."},205:{name:"UnsafePriceNotAllowed",message:"Two legs disagree beyond tolerance, or only one produced a reading."},206:{name:"PriceFeedStale",message:"Observation exceeds its staleness budget. Timestamps over 60 s ahead are dropped; the error then depends on remaining sources."},208:{name:"BadLastTolerance",message:"Upper ratio outside 10150..12500 (excess over BPS outside 150..2500 bps), or lower ratio is not the required rounded reciprocal."},210:{name:"NoLastPrice",message:"No readable source, or an Aquarius LP read failed (for example, reserves or shares)."},211:{name:"NoAccumulator",message:"Controller has no revenue accumulator."},212:{name:"ReflectorHistoryEmpty",message:"Reflector returns no price history."},216:{name:"OracleNotConfigured",message:"No oracle for the price key, or the response omits a requested asset."},217:{name:"InvalidPrice",message:"Price <= 0, or LP fair-value math non-representable."},218:{name:"InvalidStalenessConfig",message:"Max_stale_seconds out of range or below the source's guaranteed freshness."},219:{name:"TwapInsufficientObservations",message:"Record count zero or below the smoothing minimum, or history too short, too long, or denser than feed resolution."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},222:{name:"InvalidOracleResolution",message:"Reflector resolution below minimum, above max_stale_seconds, or implying a TWAP span above it."},223:{name:"SanityBoundViolated",message:"Price outside the stored sanity band."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."},226:{name:"SanityBandTooWideForSingleSource",message:"Band exceeds the tighter limit for single-source, LP, or dual-source oracles with identical provider trust sets."},227:{name:"SanityBandMustTighten",message:"Set_sanity_band would widen the band. Widen via timelocked ConfigureAssetOracle."},228:{name:"TwapRecordsOutOfRange",message:"Record count above MAX_TWAP_RECORDS (12)."},229:{name:"OracleDepthExceeded",message:"Composition nests deeper than MAX_RESOLUTION_DEPTH (3)."},230:{name:"FactorOutOfBounds",message:"Scaled source's factor price outside its min/max."},231:{name:"SourceCountOutOfRange",message:"Zero or over two sources, or Aquarius LP combined with another source."},232:{name:"IndependenceNotDeclared",message:"Sources violate RequireDisjoint, or AllowShared is empty or not exactly the shared providers."},234:{name:"UnsupportedAquariusPool",message:"Aquarius pool of wrong type, or zero reserve or total shares."},235:{name:"InsufficientAquariusLiquidity",message:"Pool value below min_pool_value_wad."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},310:{name:"SpokeMismatch",message:"Account's spoke differs from the targeted spoke."},311:{name:"SpokeSupplyCapReached",message:"Supply would exceed the spoke supply cap."},312:{name:"SpokeBorrowCapReached",message:"Borrow would exceed the spoke borrow cap."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},319:{name:"SpokeFlagsEpochMismatch",message:"RelaxSpokeAssetFlags epoch is stale or wrong; checked at proposal and execution."},400:{name:"FlashLoanOngoing",message:"Flash loan in progress; re-entrant calls refused."},401:{name:"FlashloanNotEnabled",message:"Market is_flashloanable is false."},402:{name:"InvalidFlashloanRepay",message:"Allowance below principal plus fee, or a pool balance check after payout, callback, or repayment fails."},409:{name:"StrategyFeeExceeds",message:"Strategy fee exceeds the borrowed amount."},412:{name:"InvalidFlashloanReceiver",message:"Receiver not a deployed Wasm contract, or a controller payout targets the controller or pool."},500:{name:"ConvertStepsRequired",message:"Multiply initial payment is neither collateral nor debt asset, with no convert_swap."},501:{name:"RouterOverspend",message:"Controller input balance rose during the swap, or router spent over amount_in."},502:{name:"NoSwapOutput",message:"Swap produced no positive measured output."},503:{name:"CollateralRequired",message:"Flash_position collateral list has no positive minimum. Empty list raises #16."},504:{name:"CollateralMinimumNotMet",message:"Measured deposit below its minimum, or none positive."},505:{name:"FlashPositionClosed",message:"Flash_position ended without supply or positive debt in its debt market."}},Hs=/Error\(Contract,\s*#(\d+)\)/,Gs=/contract:(C[A-Z2-7]{55})[^\n]*?Error\(Contract,\s*#(\d+)\)/g,Ks=/\[xoxno-invoked:(C[A-Z2-7]{55})\]/,Zs=/contract:C[A-Z2-7]{55}/;function Ys(e,t){let r;if(t?.contracts?.length)r=((e,t)=>{for(const r of e.matchAll(Gs))if(t.has(r[1]))return Number(r[2]);if(Zs.test(e))return null;const r=e.match(Ks),n=e.match(Hs);return r&&t.has(r[1])&&n?Number(n[1]):null})(e,new Set(t.contracts));else{const t=e.match(Hs);r=t?Number(t[1]):null}if(null===r)return null;const n=js[r];return n?{code:r,...n}:null}export{qo as BPS,cs as DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD,ks as LIQUIDATION_BUFFER_BPS,xo as RAY,Uo as RAY_DECIMALS,ir as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,En as STELLAR_LENDING_TOPICS,S as STELLAR_NETWORKS,B as STELLAR_NETWORK_PASSPHRASE,Vn as STELLAR_ROUTE_MAX_BYTES,kn as SYNTHETIC_EVENT_ORDER_STRIDE,so as StellarAuthPolicyError,Xn as StellarRouteVerificationError,To as WAD,Co as WAD_DECIMALS,v as XOXNOClient,Es as aggregateAccountRisk,as as annualBorrowRateRay,ho as assertStellarAuthEntries,So as assertStellarPreparedTxAuth,Ko as baseToRay,es as baseToShort,Yo as baseValueWad,gs as buildLiveSnapshot,Eo as buildSameTokenRepaySwapSteps,zt as buildStellarAcceptOwnershipTx,sr as buildStellarAddRewardsTx,Gt as buildStellarApproveBlendPoolTx,he as buildStellarBorrowBatchTx,me as buildStellarBorrowTx,ko as buildStellarCctpForwardTx,or as buildStellarClaimRevenueTx,rr as buildStellarCreateLiquidityPoolTx,tn as buildStellarExecuteCancellerResetTx,eo as buildStellarExecuteStrategyTx,Re as buildStellarFlashLoanTx,sn as buildStellarGovernanceAddSpokeImmediateTx,on as buildStellarGovernanceCreateHubImmediateTx,Gr as buildStellarGovernanceExecuteGovernanceUpgradeTx,Zr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,Yr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,Jr as buildStellarGovernanceExecuteTransferGovOwnTx,Hr as buildStellarGovernanceExecuteTx,Kr as buildStellarGovernanceExecuteUpdateDelayTx,un as buildStellarGovernancePauseTx,an as buildStellarGovernanceRevokeRoleImmediateTx,nn as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,rn as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Dt as buildStellarGrantRoleTx,xn as buildStellarLendingIdentifier,ve as buildStellarLiquidateTx,Ie as buildStellarLiquidationEstimateTx,Ee as buildStellarMigrateFromBlendTx,Pt as buildStellarMigrateTx,Ae as buildStellarMultiplyTx,Mt as buildStellarPauseTx,_r as buildStellarProposeAddAssetToSpokeTx,Sr as buildStellarProposeAddSpokeTx,qr as buildStellarProposeApproveBlendPoolTx,xr as buildStellarProposeApproveTokenTx,en as buildStellarProposeCancellerResetTx,Dr as buildStellarProposeConfigureAssetOracleTx,vr as buildStellarProposeCreateHubTx,Cr as buildStellarProposeCreateLiquidityPoolTx,$r as buildStellarProposeDeployPoolTx,Br as buildStellarProposeEditAssetInSpokeTx,Fr as buildStellarProposeEditOracleToleranceTx,Wr as buildStellarProposeGovernanceUpgradeTx,Vr as buildStellarProposeGrantGovernanceRoleTx,Mr as buildStellarProposeMigrateControllerTx,Rr as buildStellarProposeRemoveAssetFromSpokeTx,Ir as buildStellarProposeRemoveSpokeTx,Ur as buildStellarProposeRevokeBlendPoolTx,Xr as buildStellarProposeRevokeGovernanceRoleTx,Tr as buildStellarProposeRevokeTokenTx,wr as buildStellarProposeSetAccumulatorTx,kr as buildStellarProposeSetMinBorrowCollatTx,br as buildStellarProposeSetPositionLimitsTx,Ar as buildStellarProposeSetPositionManagerTx,yr as buildStellarProposeSetPriceAggregatorTx,Er as buildStellarProposeSetSpokeLiquidationCurveTx,gr as buildStellarProposeSetSwapAggregatorTx,Lr as buildStellarProposeTransferCtrlOwnershipTx,jr as buildStellarProposeTransferGovOwnTx,ln as buildStellarProposeUnpauseTx,zr as buildStellarProposeUpdateDelayTx,Pr as buildStellarProposeUpgradeControllerTx,Or as buildStellarProposeUpgradePoolParamsTx,Nr as buildStellarProposeUpgradePoolTx,tr as buildStellarRenewAccountTx,we as buildStellarRepayBatchTx,Te as buildStellarRepayDebtWithCollateralTx,be as buildStellarRepayTx,Kt as buildStellarRevokeBlendPoolTx,Ft as buildStellarRevokeRoleTx,jt as buildStellarSetAccumulatorTx,Qt as buildStellarSetOracleSanityBoundsTx,Yt as buildStellarSetOracleToleranceTx,Zt as buildStellarSetOracleTx,Ht as buildStellarSetPositionLimitsTx,Xt as buildStellarSetPriceAggregatorTx,Jt as buildStellarSetSpokeAssetFlagsTx,Vt as buildStellarSetSwapAggregatorTx,pe as buildStellarSupplyBatchTx,fe as buildStellarSupplyTx,xe as buildStellarSwapCollateralTx,ke as buildStellarSwapDebtTx,Wt as buildStellarTransferOwnershipTx,Lt as buildStellarUnpauseTx,ar as buildStellarUpdateAccountThresholdTx,er as buildStellarUpdateIndexesTx,Nt as buildStellarUpgradeControllerTx,nr as buildStellarUpgradeLiquidityPoolParamsTx,ge as buildStellarWithdrawBatchTx,ye as buildStellarWithdrawTx,ce as buildTx,Ss as burnShares,As as computeAccountRisk,An as decodeStellarLendingEvent,Se as decodeStellarLiquidateReturn,Be as decodeStellarLiquidationEstimate,Kn as decodeStellarRouteBytes,oo as decodeStellarSwapEnvelope,is as depositRateRay,Mo as divByIntHalfUp,$t as encodeAssetOracle,Bt as encodeInterestRateModel,Rt as encodeMarketParamsRaw,Et as encodePositionLimits,At as encodePriceKey,Qn as encodeStrategyPayloadToRouteXdr,Tn as extractEventOrder,Xe as getStellarAccountPositions,mt as getStellarActiveUsersSeries,On as getStellarAggregatorQuote,Fe as getStellarAsset,Je as getStellarAssetGraph,Ge as getStellarAssetMarkets,He as getStellarAssetPage,Ne as getStellarAssets,lt as getStellarCampaignLeaderboard,St as getStellarCampaignMe,yt as getStellarDefiLlamaDimensions,_ as getStellarDeployment,$e as getStellarDetailedMarkets,pt as getStellarFeeRevenueSeries,ot as getStellarGovernanceProposals,ut as getStellarHolderDistribution,We as getStellarHub,Qe as getStellarHubGraph,Ze as getStellarHubHolders,Pe as getStellarHubs,Ce as getStellarLendingContext,Oe as getStellarLendingLiveState,it as getStellarLiquidationsLeaderboard,ft as getStellarLiquidationsSeries,at as getStellarParticipantCounts,vt as getStellarPnlByScope,st as getStellarPositionsLeaderboard,bt as getStellarPositionsPnl,$n as getStellarQuoteTokens,gt as getStellarRateSpreadSeries,De as getStellarReserve,tt as getStellarReserveGraph,Ke as getStellarReserveHolders,Le as getStellarReserves,dt as getStellarRevenueSeries,ze as getStellarSpoke,et as getStellarSpokeGraph,Ye as getStellarSpokeHolders,Me as getStellarSpokes,ct as getStellarStatsHistory,rt as getStellarUserActivity,nt as getStellarUserActivityPage,wt as getStellarUserHistory,Ve as getStellarUserPositions,ht as getStellarVolumeSeries,je as getStellarWalletBalance,ms as liveIndexKey,to as mapQuoteResponseToStrategyPayload,ro as mapQuoteResponseToStrategySwap,Ys as mapSorobanError,Un as mapStellarPositionActivityType,Ps as maxBorrow,Ds as maxRepay,Ls as maxSupply,Ms as maxWithdraw,vs as mintShares,No as mulDivCeil,$o as mulDivFloor,Po as mulDivHalfUp,ts as numberToScaled,rs as numberToWad,le as parseStellarTokenAmount,Zo as positionValueWad,Bo as prepareStellarBuiltTx,_o as prepareStellarTxXdr,zs as projectAccountRisk,Xs as projectReserveApy,ls as rayAprToApy,us as rayAprToNumber,Qo as rayToNumber,Fo as rescaleCeil,Do as rescaleFloor,Wo as rescaleHalfUp,ds as reserveKey,ps as resolveReserve,bo as stellarAuthPolicyForInvocation,pn as stellarLendingDispatchKey,It as stellarLendingRead,I as stellarNetworks,Zn as stellarTokenContractId,qn as syntheticEventOrder,Io as tagStellarInvokedContractError,cn as toBase64Xdr,Oo as toBigInt,Ro as toStellarPositionMode,Xo as unscale,Ho as unscaleBorrowCeil,Go as unscaleHalfUp,jo as unscaleSupplyFloor,ss as utilizationRay,Is as valueBasePosition,bs as valueScaledPosition,Jn as verifyStellarRouteBytes,Jo as wadToNumber};export const createStellarLendingReadClient=_t.gm;export const lendingAssetsSchema=_t.IY;export const lendingPositionsSchema=_t.Vd;
2
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,Asset as r,BASE_FEE as n,Contract as o,ScInt as a,Soroban as s,StrKey as i,TransactionBuilder as u,rpc as l,scValToBigInt as c,scValToNative as d,xdr as p}from"@stellar/stellar-sdk";var f={526(e,t){t.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=i(e),s=a[0],u=a[1],l=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,u)),c=0,d=u>0?s-4:s;for(r=0;r<d;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,a=[],s=16383,i=0,u=n-o;i<u;i+=s)a.push(l(e,i,i+s>u?u:i+s));return 1===o?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=a[s],n[a.charCodeAt(s)]=s;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function l(e,t,r){for(var n,o=[],a=t;a<r;a+=3)n=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),o.push(u(n));return o.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){const n=r(526),o=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){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 l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=i(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(K(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return p(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 f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(K(e,SharedArrayBuffer)||e&&K(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?i(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return c(e),i(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=i(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,u.prototype),n}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function m(e,t){if(u.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 r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return H(e).length;default:if(o)return n?-1:j(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return E(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return x(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function w(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let a,s=1,i=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,i/=2,u/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let n=-1;for(a=r;a<i;a++)if(l(e,a)===l(t,-1===n?0:a-n)){if(-1===n&&(n=a),a-n+1===u)return n*s}else-1!==n&&(a-=a-n),n=-1}else for(r+u>i&&(r=i-u),a=r;a>=0;a--){let r=!0;for(let n=0;n<u;n++)if(l(e,a+n)!==l(t,n)){r=!1;break}if(r)return a}return-1}function v(e,t,r,n){r=Number(r)||0;const o=e.length-r;n?(n=Number(n))>o&&(n=o):n=o;const a=t.length;let s;for(n>a/2&&(n=a/2),s=0;s<n;++s){const n=parseInt(t.substr(2*s,2),16);if(Z(n))return s;e[r+s]=n}return s}function S(e,t,r,n){return G(j(t,e.length-r),e,r,n)}function _(e,t,r,n){return G(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function I(e,t,r,n){return G(H(t),e,r,n)}function B(e,t,r,n){return G(function(e,t){let r,n,o;const a=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),n=r>>8,o=r%256,a.push(o),a.push(n);return a}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function E(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o<r;){const t=e[o];let a=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=r){let r,n,i,u;switch(s){case 1:t<128&&(a=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(a=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(a=u));break;case 4:r=e[o+1],n=e[o+2],i=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&i)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&i,u>65535&&u<1114112&&(a=u))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),o+=s}return function(e){const t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=k));return r}(n)}u.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}}(),u.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(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array),u.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},u.allocUnsafe=function(e){return d(e)},u.allocUnsafeSlow=function(e){return d(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(K(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let o=0,a=Math.min(r,n);o<a;++o)if(e[o]!==t[o]){r=e[o],n=t[o];break}return r<n?-1:n<r?1:0},u.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}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=u.allocUnsafe(t);let o=0;for(r=0;r<e.length;++r){let t=e[r];if(K(t,Uint8Array))o+t.length>n.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=m,u.prototype._isBuffer=!0,u.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},u.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},u.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},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?E(this,0,e):g.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},a&&(u.prototype[a]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if(K(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.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===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let a=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const i=Math.min(a,s),l=this.slice(n,o),c=e.slice(t,r);for(let e=0;e<i;++e)if(l[e]!==c[e]){a=l[e],s=c[e];break}return a<s?-1:s<a?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let a=!1;for(;;)switch(n){case"hex":return v(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return _(this,e,t,r);case"base64":return I(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;o<r;++o)n+=String.fromCharCode(127&e[o]);return n}function x(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;o<r;++o)n+=String.fromCharCode(e[o]);return n}function T(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let o="";for(let n=t;n<r;++n)o+=Y[e[n]];return o}function q(e,t,r){const n=e.slice(t,r);let o="";for(let e=0;e<n.length-1;e+=2)o+=String.fromCharCode(n[e]+256*n[e+1]);return o}function U(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,n,o,a){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<a)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function O(e,t,r,n,o){W(t,n,o,e,r,7);let a=Number(t&BigInt(4294967295));e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function $(e,t,r,n,o){W(t,n,o,e,r,7);let a=Number(t&BigInt(4294967295));e[r+7]=a,a>>=8,e[r+6]=a,a>>=8,e[r+5]=a,a>>=8,e[r+4]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function N(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,a){return t=+t,r>>>=0,a||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,a){return t=+t,r>>>=0,a||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,u.prototype),n},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e],o=1,a=0;for(;++a<t&&(o*=256);)n+=this[e+a]*o;return n},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<<BigInt(32))})),u.prototype.readBigUInt64BE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(o)})),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=this[e],o=1,a=0;for(;++a<t&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let n=t,o=1,a=this[e+--n];for(;n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),u.prototype.readBigInt64BE=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,a=0;for(this[t]=255&e;++a<r&&(o*=256);)this[t+a]=e/o&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,a=1;for(this[t+o]=255&e;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeBigUInt64LE=J((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return $(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=0,a=1,s=0;for(this[t]=255&e;++o<r&&(a*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/a|0)-s&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a|0)-s&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(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},u.prototype.writeBigInt64LE=J((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return $(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const o=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),o},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const a=u.isBuffer(e)?e:u.from(e,n),s=a.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=a[o%s]}return this};const L={};function D(e,t,r){L[e]=class extends r{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 F(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,n,o,a){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let o;throw o=a>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(a+1)}${n}`:`>= -(2${n} ** ${8*(a+1)-1}${n}) and < 2 ** ${8*(a+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new L.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,o,a)}function z(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new L.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=F(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=F(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function j(e,t){let r;t=t||1/0;const n=e.length;let o=null;const a=[];for(let s=0;s<n;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(X,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function G(e,t,r,n){let o;for(o=0;o<n&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=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 Z(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},251(e,t){t.read=function(e,t,r,n,o){var a,s,i=8*o-n-1,u=(1<<i)-1,l=u>>1,c=-7,d=r?o-1:0,p=r?-1:1,f=e[t+d];for(d+=p,a=f&(1<<-c)-1,f>>=-c,c+=i;c>0;a=256*a+e[t+d],d+=p,c-=8);for(s=a&(1<<-c)-1,a>>=-c,c+=n;c>0;s=256*s+e[t+d],d+=p,c-=8);if(0===a)a=1-l;else{if(a===u)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),a-=l}return(f?-1:1)*s*Math.pow(2,a-n)},t.write=function(e,t,r,n,o,a){var s,i,u,l=8*a-o-1,c=(1<<l)-1,d=c>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,h=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,s=c):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+d>=1?p/u:p*Math.pow(2,1-d))*u>=2&&(s++,u/=2),s+d>=c?(i=0,s=c):s+d>=1?(i=(t*u-1)*Math.pow(2,o),s+=d):(i=t*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;e[r+f]=255&i,f+=h,i/=256,o-=8);for(s=s<<o|i,l+=o;l>0;e[r+f]=255&s,f+=h,s/=256,l-=8);e[r+f-h]|=128*m}},468(e,t,r){r.d(t,{gm:()=>b,IY:()=>y,Vd:()=>g});const n={type:"string"},o={type:"number"},a={type:"boolean"},s={...n,nullable:!0},i={...o,nullable:!0},u={...n,enum:["mainnet","testnet"]},l={...n,enum:["ready","stale","incomplete"]};function c(e){return{type:"object",required:Object.keys(e),properties:e}}const d={sac:n,symbol:n,name:n,decimals:i,logoUrl:s},p=c({valid:a,stale:a,deviation:a,timestamp:i}),f=c({...d,hubId:o,hubName:n,amountRaw:{...s,description:"Integer token base units, never scaled shares."},amount:s,apy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,valueUsd:i,priceStatus:p,indexRay:s,indexedAt:o,indexedLedger:o}),h=c({amountRaw:s,amount:s,usd:i}),m=c({spokeId:o,spokeName:n,ltvBps:o,supplyCapacity:h,borrowCapacity:h,canSupply:a,canBeCollateral:a,canBorrow:a,canOpenAccount:{...a,description:"Spoke admits new accounts; other entry gates still apply."}}),g={type:"array",items:c({accountId:n,nftContract:n,nftImage:{...n,format:"uri",description:"Dynamic position SVG served by the network's XOXNO API."},network:u,spokeId:i,spokeName:s,supplied:{type:"array",items:f},borrow:{type:"array",items:f},hasDebt:{...a,nullable:!0,description:"Null when account rows are unavailable."},healthFactor:{...i,description:"Null without debt or when risk inputs are unavailable."},borrowLimitUsd:i,availableBorrowUsd:{...i,description:"Account headroom, before per-market constraints."},netApy:{...i,description:"Net annual yield divided by positive net equity; fraction."},dataStatus:l})},y={type:"array",items:c({...d,hubId:o,hubName:n,network:u,supplyApy:{...i,description:"Fraction: 0.05 means 5%."},borrowApy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,priceStatus:p,spokes:{type:"array",items:m},dataStatus:l,indexedAt:{...o,description:"Pool state timestamp. Capacities are indexed snapshot estimates; prepare/simulate before signing."},indexedLedger:o})};function w(e){if(!e)return;const t=/\s*<([^<>\s]+)>\s*((?:;\s*[\w!#$%&'*+.^`|~-]+\s*=\s*(?:"(?:[^"\\\r\n]|\\.)*"|[\w!#$%&'*+.^`|~:/-]+)\s*)*)(,|$)/gy;let r,n=0;for(;n<e.length;){const o=t.exec(e);if(!o||o[3]&&t.lastIndex===e.length)throw new Error("Invalid pagination Link header");let a=!1,s=!1;for(const e of o[2].matchAll(/;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\.)*)"|([\w!#$%&'*+.^`|~:/-]+))\s*/g))if("rel"===e[1].toLowerCase()){if(s)throw new Error("Duplicate pagination link relation");s=!0,a=(e[2]??e[3]).replace(/\\(.)/g,"$1").toLowerCase().split(/\s+/).includes("next")}if(a){if(void 0!==r)throw new Error("Multiple next pagination links");r=o[1]}n=t.lastIndex}return r}function b(e){const t=new URL(e.baseUrl.trim());if(!["https:","http:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an HTTP API root without credentials, query or fragment");t.pathname=`${t.pathname.replace(/\/+$/,"")}/`;const r=e.fetch??globalThis.fetch?.bind(globalThis);if(!r)throw new Error("A fetch implementation is required");async function n(e,n){const o=new URL(`stellar-lending/v1/${e}`,t);let a=o;const s=new Set,i=[];for(;;){if(s.has(a.href))throw new Error("Pagination Link cycle");s.add(a.href);const e=await r(a.href,{signal:n,redirect:"error"});if(e.redirected||e.url&&new URL(e.url).href!==a.href)throw new Error("Stellar lending redirects are not allowed");if(!e.ok)throw new Error(`Stellar lending request failed: HTTP ${e.status}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Stellar lending response must be an array");i.push(...t);const u=w(e.headers.get("Link"));if(!u)break;const l=new URL(u,a);if(l.origin!==o.origin||l.pathname!==o.pathname||l.username||l.password||l.hash)throw new Error("Pagination Link must stay on the same API endpoint");a=l}return i}return{assets:({usage:e,signal:t}={})=>{if(void 0!==e&&"collateral"!==e&&"borrow"!==e)throw new Error("usage must be collateral or borrow");return n("assets"+(e?`?usage=${e}`:""),t)},positions:(e,{signal:t}={})=>{if(!e.trim()||"."===e||".."===e)throw new Error("owner is required");return n(`users/${encodeURIComponent(e)}/positions`,t)}}}}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={exports:{}};return f[e](r,r.exports,m),r.exports}m.d=(e,t)=>{for(var r in t)m.o(t,r)&&!m.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const g="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",y="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",w="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e";var b;!function(e){e.MAINNET="1",e.DEVNET="D"}(b||(b={}));class v{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=b.MAINNET,apiUrl:r,...n}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=n,this.config=t==b.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",FM_SC:g,DR_SC:y,KG_SC:w,Staking_SC:"erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",Manager_SC:"erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",P2P_SC:"erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6"}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",FM_SC:g,DR_SC:y,KG_SC:w,Staking_SC:"erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",Manager_SC:"erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",P2P_SC:"erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:n,cache:o,debug:a,timeout:s,...i}=this.init,{next:u,cache:l,debug:c,timeout:d,headers:p,method:f="GET",...h}=r,m=p?.Authorization,g="Bearer undefined"===m?void 0:m,y="GET"!==f&&"HEAD"!==f&&"PUT"!==f,w={...p,Referer:"https://xoxno.sdk","User-Agent":"XOXNO/1.0/SDK",...y?{"Content-Type":"application/json"}:{},...g?{Authorization:g}:{}},b=Object.entries(t??{}).filter((([,e])=>void 0!==e)).flatMap((([e,t])=>Array.isArray(t)?t.filter((e=>void 0!==e)).map((t=>`${e}=${encodeURIComponent(t)}`)):`${e}=${encodeURIComponent(t)}`)).join("&"),v=`${this.apiUrl}${e}${b.length?`?${b}`:""}`,{revalidate:S,..._}=n??{},{revalidate:I,...B}=u??{},R="GET"!==f||g?void 0:I??S,E="GET"!==f||g||R?void 0:l??o,k=h.body,A=d??s??(null==k?3e4:0),x=A>0?AbortSignal.timeout(A):void 0,T=h.signal??i.signal,q=x&&T?AbortSignal.any([T,x]):x??T,U={...i,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:E,next:{..._,...B,revalidate:R}};(c??a)&&console.debug("SDK fetch: ",v,U);const C=await fetch(v,U).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${v}: ${e.message}`),{cause:e});throw e})),O=await C.text();if(!C.ok){let e;try{e=JSON.parse(O)}catch{e={message:O}}const t=[v,C.status,C.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(O)}catch{return O}}}const S={stellarMainnet:{name:"mainnet",passphrase:"Public Global Stellar Network ; September 2015",horizonUrl:"https://horizon.stellar.org",sorobanRpcUrl:"https://stellar-gateway.xoxno.com",quoteUrl:"https://stellar-swap.xoxno.com",explorerNetwork:"public",aquariusApiUrl:"https://amm-api.aqua.network",aquariusRouter:"CBQDHNBFBZYE4MKPWBSJOPIYLW4SFSXAXUTSXJN76GNKYVYPCKWC6QUK",lendingController:"CAUCMIN5KSXEVZ7NMXR3LZATGD5EFIEUI5XWTFLYRO2R5OTXI22WE5JX",lendingPool:"CBXRNDQMAJFG4VUKMKFEMFS75UUXE2SPSNV4LEEFCSNBCN66PYRWBKXO",aggregatorRouter:"CCVENFSVCBYDHVOACFZXMNNYVOZ3LKXPZYU5LUI4N7KTXOKRVYD7F3TR",governance:"CC44PEQW7HSEPKAZ5ZRPH2JS5M5KVJXCUBLJ2ZX4E3WCDKMNFILHC2AD",priceAggregator:"CBGUF2G2Q7HCVCWYISDXBHPVBGMYNXA7PG2VET66YBZX6IKOOV27NSMV",positionNftContract:"CAWCSG77AY2W24QZ6ZXLHZU4UXEFHZBM6EI4A4IF7JB5CTY4XND3TI6C"},stellarTestnet:{name:"testnet",passphrase:"Test SDF Network ; September 2015",horizonUrl:"https://horizon-testnet.stellar.org",sorobanRpcUrl:"https://stellar-testnet-gateway.xoxno.com",quoteUrl:"https://testnet-stellar-swap.xoxno.com",explorerNetwork:"testnet",aquariusApiUrl:"https://amm-api-testnet.aqua.network",aquariusRouter:"CBCFTQSPDBAIZ6R6PJQKSQWKNKWH2QIV3I4J72SHWBIK3ADRRAM5A6GD",lendingController:"CCXRWJ6SIU2WPFEGLFGJVITPL57QAYIMIO6OAM2NBGNDQSSCK2FFV3F3",lendingPool:"CBSGF6QOQAMPFBEVSYPEQHSZRIHJ6RCGUPCRDMUX36DEKRWFAO2PZB5A",aggregatorRouter:"CDNTWMWW2WGYTKIZTJYNGNVQQZI4KTC5BQRZ3275KESRX5T4O3AYECL5",governance:"CDS33JDOYH3F3FL4QUQ6DV4WKHML2AKHF4LADTZ57FRUAEBTE7NMY5FQ",priceAggregator:"CBMARXSYE56NPDLX42TTICM5GS5XQCYRD5VMCJME624TS6C2S53VETYU",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},_=S;function I(e){return S["testnet"===e?"stellarTestnet":"stellarMainnet"]}const B={mainnet:S.stellarMainnet.passphrase,testnet:S.stellarTestnet.passphrase};var R=m(287);const E=["Soroswap","Aquarius","Phoenix","Sushi","CometDex","Curve"],k={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4,Curve:7},A=1,x=1e6,T=5,q=6,U=0,C=1,O=2,$=128,N=48,P=32,M=256,L=$-O,D=e=>new t(e).toScVal(),F=e=>new a(e).toI128(),W=e=>p.ScVal.scvU32(e),z=e=>{if("number"==typeof e&&!Number.isSafeInteger(e))throw new Error("Stellar builder: u64 numbers must be safe integers; pass a decimal string for larger values");return new a("string"==typeof e?e:e.toString()).toU64()},V=e=>p.ScVal.scvBool(e),X=e=>p.ScVal.scvString(e),j=e=>p.ScVal.scvSymbol(e),H=()=>p.ScVal.scvVoid(),G=e=>p.ScVal.scvVec(e),K=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,n=R.hp.from(r,"hex");if(n.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${n.length} bytes from "${e}")`);return p.ScVal.scvBytes(n)},Z=(e,t)=>null==e?H():t(e),Y=(e,t)=>te({asset:D(t),hub_id:W(e)}),J=(e,t,r)=>p.ScVal.scvVec([Y(e,t),F(r)]),Q=e=>p.ScVal.scvVec(e.map((e=>J(e.hubId,e.asset,e.amount)))),ee=e=>{if("Transfer"===e)return G([j("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return G([j("Credit"),z(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},te=e=>{const t=Object.keys(e).sort().map((t=>new p.ScMapEntry({key:j(t),val:e[t]})));return p.ScVal.scvMap(t)};class re{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=M)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=L)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=P)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>x)throw new Error(`Stellar builder: split weight ${e} outside 1..=${x}`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,n,o){this.ops.push([e,t,r,n,o])}emitPath(e,t){e.hops.forEach(((r,n)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const o=e.hops[n-1];if(o&&r.tokenIn!==o.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(k[r.venue],0===n?t:C,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const n=t[e].hops[0]?.tokenIn,o=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===n&&o.push(r);const a=o.reduce(((e,r)=>e+t[r].splitPpm),0);if(a>x)throw new Error(`Stellar builder: split weights for one token sum to ${a}, above ${x}`);const s=a===x;let i=x;o.forEach(((e,n)=>{r[e]=!0;const a=t[e];let u;if(n+1===o.length&&s)u=U;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(a.splitPpm*x/i);i-=Math.min(a.splitPpm,i),u=$+this.weight(e)}this.emitPath(a,u)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>N)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts ${N}`);const n=[A,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)n.push(...e);for(const e of this.weights)n.push(e>>>16&255,e>>>8&255,255&e);return R.hp.from(n)}get assetList(){return this.assets}get amountList(){return this.amounts}}const ne=e=>{const t=new re(e.totalMinOut),r=t.asset(e.tokenIn),n=t.asset(e.tokenOut);if(r===n)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const n=t.asset(e.burnPool),o=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(T,U,n,r,o)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const n=e.mintPoolTokens;if(!n||2!==n.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[o,a]=n,[s,i]=e.preSwapFromA?[o,a]:[a,o];t.emit(k.Aquarius,O+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(q,U,t.asset(e.mintPool),n,t.amount(e.mintMinShares??"1"))}const o=Number(e.referralId??0);if(!Number.isInteger(o)||o<0||o>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return te({amounts:p.ScVal.scvVec(t.amountList.map((e=>F(e)))),assets:p.ScVal.scvVec(t.assetList.map((e=>D(e)))),ops:p.ScVal.scvBytes(t.toBytes(r,n,o))})},oe=e=>{const t=R.hp.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return p.ScVal.scvBytes(t)},ae=()=>p.ScVal.scvBytes(R.hp.alloc(0)),se=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return R.hp.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const n=R.hp.from(t,"base64");if(0===n.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return n},ie=e=>{if("string"==typeof e)return oe(se(e));if(e instanceof Uint8Array)return 0===e.length?ae():oe(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?oe(se(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?oe(se(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?oe(se(e.bytes)):0===e.bytes.length?ae():oe(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length&&!t.burnPool&&!t.mintPool)throw new Error("Stellar builder: `steps.paths` needs a strategy path or a liquidity burn/mint operation");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,n]of t.paths.entries()){if(!n||"number"!=typeof n.splitPpm||n.splitPpm<=0||!Array.isArray(n.hops)||0===n.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of n.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!E.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=n.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+n.splitPpm)}for(const[e,n]of r){if(n>x)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${n}, above ${x}`);if(!t.mintPool&&n!==x)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to ${x}, got ${n}`)}return t})(e),p.ScVal.scvBytes(R.hp.from(ne(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},ue=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=R.hp.from(t,"hex");return p.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return p.ScVal.scvBytes(R.hp.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function le(e,t){if("number"!=typeof t||!Number.isInteger(t)||t<0||t>18)throw new Error("Token decimals must be an integer from 0 to 18");if("string"!=typeof e||!/^\d+(?:\.\d+)?$/.test(e))throw new Error("Token amount must be plain decimal text");const r=s.parseTokenAmount(e,t),n=BigInt(r);if(n<=0n||n>(1n<<127n)-1n)throw new Error("Token amount must be within the positive i128 range");return r}function ce(t,r,a){if(!t.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const s=new o(t.controllerAddress),i=new e(t.caller,t.sourceSequence);return{xdr:new u(i,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(s.call(r,...a)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function de(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return W(e)}function pe(e,t){const r=t.accountNonce??0;return ce(e,"supply",[D(e.caller),z(r),de(t.spokeId),Q([...t.assets])])}function fe(e,t){return pe(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function he(e,t){return ce(e,"borrow",[D(e.caller),z(t.accountNonce),Q([...t.borrows]),Z(t.to,D)])}function me(e,t){return he(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function ge(e,t){return ce(e,"withdraw",[D(e.caller),z(t.accountNonce),Q([...t.withdrawals]),Z(t.to,D)])}function ye(e,t){return ge(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function we(e,t){return ce(e,"repay",[D(e.caller),z(t.accountNonce),Q([...t.payments])])}function be(e,t){return we(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function ve(e,t){return ce(e,"liquidate",[D(e.caller),z(t.accountNonce),Q([...t.debtPayments]),ee(t.seizeMode??"Transfer")])}function Se(e){const t=d(p.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function _e(e,t){return ce(e,"get_liquidation_estimate",[z(t.accountNonce),Q([...t.debtPayments]),ee(t.seizeMode??"Transfer")])}const Ie=e=>(Array.isArray(e)?e:[]).map((e=>{const t=e;return{asset:String(t.asset),amount:String(t.amount)}}));function Be(e){const t=d(p.ScVal.fromXDR(e,"base64"));if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Stellar builder: liquidation estimate must be a struct");return{seizedCollaterals:Ie(t.seized_collaterals),protocolFees:Ie(t.protocol_fees),refunds:Ie(t.refunds),maxPaymentWad:String(t.max_payment_wad),bonusRateBps:String(t.bonus_rate_bps)}}function Re(e,t){return ce(e,"flash_loan",[D(e.caller),Y(t.hubId,t.asset),F(t.amount),D(t.receiver),ue(t.data)])}function Ee(e,t){return ce(e,"migrate_from_blend",[D(e.caller),z(t.accountId),de(t.spokeId),W(t.hubId),D(t.blendPool),G(t.collateralTokens.map(D)),G(t.supplyTokens.map(D)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),p.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,p.ScVal.scvVec([D(t),F(r)]);var t,r}))))]);var r}function ke(e,t){const r=t.accountNonce??0;return ce(e,"multiply",[D(e.caller),z(r),de(t.spokeId),Y(t.collateral.hubId,t.collateral.asset),F(t.debtToFlashLoan),Y(t.debt.hubId,t.debt.asset),W(t.mode),ie(t.steps),Z(t.initialPayment,(e=>J(e.hubId,e.asset,e.amount))),Z(t.convertSwap,ie)])}function Ae(e,t){return ce(e,"swap_debt",[D(e.caller),z(t.accountNonce),Y(t.existingDebt.hubId,t.existingDebt.asset),F(t.newDebtAmount),Y(t.newDebt.hubId,t.newDebt.asset),ie(t.steps)])}function xe(e,t){return ce(e,"swap_collateral",[D(e.caller),z(t.accountNonce),Y(t.current.hubId,t.current.asset),F(t.fromAmount),Y(t.newCollateral.hubId,t.newCollateral.asset),ie(t.steps)])}function Te(e,t){return ce(e,"repay_debt_with_collateral",[D(e.caller),z(t.accountNonce),Y(t.collateral.hubId,t.collateral.asset),F(t.collateralAmount),Y(t.debt.hubId,t.debt.asset),ie(t.steps),V(t.closePosition)])}const qe="/stellar-lending",Ue=encodeURIComponent,Ce=(e,t)=>e.fetchWithTimeout(`${qe}/context`,t),Oe=(e,t)=>e.fetchWithTimeout(`${qe}/live-state`,t),$e=(e,t)=>e.fetchWithTimeout(`${qe}/markets/detailed`,t),Ne=(e,t)=>e.fetchWithTimeout(`${qe}/assets`,t),Pe=(e,t)=>e.fetchWithTimeout(`${qe}/hubs`,t),Me=(e,t)=>e.fetchWithTimeout(`${qe}/spokes`,t),Le=(e,t={},r)=>e.fetchWithTimeout(`${qe}/reserves`,{...r,params:{...t}}),De=(e,t,r,n,o)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}`,o),Fe=(e,t,r)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}`,r),We=(e,t,r)=>e.fetchWithTimeout(`${qe}/hubs/${t}`,r),ze=(e,t,r)=>e.fetchWithTimeout(`${qe}/spokes/${t}`,r),Ve=(e,t,r)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/positions`,r),Xe=(e,t,r)=>e.fetchWithTimeout(`${qe}/accounts/${Ue(t)}/positions`,r),je=(e,t,r)=>e.fetchWithTimeout(`/user/${Ue(t)}/token-inventory`,r),He=async(e,t,r,n)=>{const o=await je(e,t,n),a=e.chain===b.MAINNET?"mainnet":"testnet",s=(o?.tokens??[]).find((e=>e.identifier===r));if(s)return{owner:t,network:s.stellarNetwork??a,asset:r,amount:String(s.balance),decimals:s.decimals};const{decimals:i}=await Fe(e,r,n);if("number"!=typeof i)throw new Error(`Stellar lending: no decimals for ${r}; it is not a lending asset`);return{owner:t,network:a,asset:r,amount:"0",decimals:i}},Ge=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/page`,{...n,params:{...r}}),Ke=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/markets`,{...n,params:{side:r}}),Ze=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}/holders`,{...a,params:{side:o}}),Ye=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/hubs/${t}/holders`,{...n,params:{side:r}}),Je=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/spokes/${t}/holders`,{...n,params:{side:r}}),Qe=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/assets/${Ue(t)}/graph`,{...n,params:{...r}}),et=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/hubs/${t}/graph`,{...n,params:{...r}}),tt=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/spokes/${t}/graph`,{...n,params:{...r}}),rt=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${qe}/reserves/${t}/${r}/${Ue(n)}/graph`,{...a,params:{...o}}),nt=(e,t,r={},n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/activity`,{...n,params:{...r}}),ot=(e,t,r={},n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/activity/page`,{...n,params:{...r}}),at=(e,t={},r)=>e.fetchWithTimeout(`${qe}/governance/proposals`,{...r,params:{...t}}),st=(e,t={},r)=>e.fetchWithTimeout(`${qe}/positions`,{...r,params:{...t}}),it=(e,t={},r)=>e.fetchWithTimeout(`${qe}/participants`,{...r,params:{...t}}),ut=(e,t={},r)=>e.fetchWithTimeout(`${qe}/liquidations/leaderboard`,{...r,params:{...t}}),lt=(e,t={},r)=>e.fetchWithTimeout(`${qe}/distribution`,{...r,params:{...t}}),ct=(e,t={},r)=>e.fetchWithTimeout(`${qe}/campaign/leaderboard`,{...r,params:{...t}}),dt=(e,t,r)=>e.fetchWithTimeout(`${qe}/stats/history`,{...r,params:{...t}}),pt=(e,t,r)=>e.fetchWithTimeout(`${qe}/revenue`,{...r,params:{...t}}),ft=(e,t,r)=>e.fetchWithTimeout(`${qe}/revenue/fees`,{...r,params:{...t}}),ht=(e,t,r)=>e.fetchWithTimeout(`${qe}/liquidations`,{...r,params:{...t}}),mt=(e,t,r)=>e.fetchWithTimeout(`${qe}/volume`,{...r,params:{...t}}),gt=(e,t,r)=>e.fetchWithTimeout(`${qe}/active-users`,{...r,params:{...t}}),yt=(e,t,r)=>e.fetchWithTimeout(`${qe}/rate-spread`,{...r,params:{...t}}),wt=(e,t,r)=>e.fetchWithTimeout(`${qe}/defillama`,{...r,params:{...t}}),bt=(e,t,r,n)=>e.fetchWithTimeout(`${qe}/users/${Ue(t)}/history`,{...n,params:{...r}}),vt=(e,t,r)=>e.fetchWithTimeout(`${qe}/pnl`,{...r,params:{accountId:t}}),St=(e,t,r)=>e.fetchWithTimeout(`${qe}/pnl/scope`,{...r,params:{scope:t}}),_t=(e,t,r)=>e.fetchWithTimeout(`${qe}/campaign/me`,{...r,params:{owner:t}}),It=e=>({context:t=>Ce(e,t),liveState:t=>Oe(e,t),marketsDetailed:t=>$e(e,t),assets:t=>Ne(e,t),hubs:t=>Pe(e,t),spokes:t=>Me(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?Le(e,t,r):Le(e,{},t),reserve:(t,r,n,o)=>De(e,t,r,n,o),asset:(t,r)=>Fe(e,t,r),hub:(t,r)=>We(e,t,r),spoke:(t,r)=>ze(e,t,r),userPositions:(t,r)=>Ve(e,t,r),accountPositions:(t,r)=>Xe(e,t,r),walletTokens:(t,r)=>je(e,t,r),walletBalance:(t,r,n)=>He(e,t,r,n),assetPage:(t,r,n)=>Ge(e,t,r,n),assetMarkets:(t,r,n)=>Ke(e,t,r,n),reserveHolders:(t,r,n,o,a)=>Ze(e,t,r,n,o,a),hubHolders:(t,r,n)=>Ye(e,t,r,n),spokeHolders:(t,r,n)=>Je(e,t,r,n),assetGraph:(t,r,n)=>Qe(e,t,r,n),hubGraph:(t,r,n)=>et(e,t,r,n),spokeGraph:(t,r,n)=>tt(e,t,r,n),reserveGraph:(t,r,n,o,a)=>rt(e,t,r,n,o,a),userActivity:(t,r={},n)=>nt(e,t,r,n),userActivityPage:(t,r={},n)=>ot(e,t,r,n),governanceProposals:(t={},r)=>at(e,t,r),positionsLeaderboard:(t={},r)=>st(e,t,r),participants:(t={},r)=>it(e,t,r),liquidationsLeaderboard:(t={},r)=>ut(e,t,r),distribution:(t={},r)=>lt(e,t,r),campaignLeaderboard:(t={},r)=>ct(e,t,r),statsHistory:(t,r)=>dt(e,t,r),revenue:(t,r)=>pt(e,t,r),feeRevenue:(t,r)=>ft(e,t,r),liquidations:(t,r)=>ht(e,t,r),volume:(t,r)=>mt(e,t,r),activeUsers:(t,r)=>gt(e,t,r),rateSpread:(t,r)=>yt(e,t,r),defillama:(t,r)=>wt(e,t,r),userHistory:(t,r,n)=>bt(e,t,r,n),positionsPnl:(t,r)=>vt(e,t,r),pnlByScope:(t,r)=>St(e,t,r),campaignMe:(t,r)=>_t(e,t,r)});var Bt=m(468);const Rt=e=>te({base_borrow_rate:F(e.baseBorrowRateRay),max_borrow_rate:F(e.maxBorrowRateRay),max_utilization:F(e.maxUtilizationRay),mid_utilization:F(e.midUtilizationRay),optimal_utilization:F(e.optimalUtilizationRay),reserve_factor:W(e.reserveFactorBps),slope1:F(e.slope1Ray),slope2:F(e.slope2Ray),slope3:F(e.slope3Ray)}),Et=e=>te({asset_decimals:W(e.assetDecimals),asset_id:D(e.assetId),base_borrow_rate:F(e.baseBorrowRateRay),flashloan_fee:W(e.flashloanFeeBps),is_flashloanable:V(e.isFlashloanable),max_borrow_rate:F(e.maxBorrowRateRay),max_utilization:F(e.maxUtilizationRay),mid_utilization:F(e.midUtilizationRay),optimal_utilization:F(e.optimalUtilizationRay),reserve_factor:W(e.reserveFactorBps),slope1:F(e.slope1Ray),slope2:F(e.slope2Ray),slope3:F(e.slope3Ray)}),kt=e=>te({max_borrow_positions:W(e.maxBorrowPositions),max_supply_positions:W(e.maxSupplyPositions)}),At=e=>{if("Token"in e&&e.Token)return G([j("Token"),D(e.Token)]);if("Ref"in e&&e.Ref)return G([j("Ref"),j(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},xt=e=>{if("Stellar"in e)return G([j("Stellar"),D(e.Stellar)]);if("Symbol"in e)return G([j("Symbol"),j(e.Symbol)]);if("String"in e)return G([j("String"),X(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Tt=e=>{if("Spot"===e)return G([j("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return G([j("Twap"),W(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},qt=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return G([j(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ut=e=>{if("Market"===e||"Fundamental"===e)return G([j(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ct=e=>{if("Reflector"in e){const t=e.Reflector;return G([j("Reflector"),te({asset:xt(t.asset),contract:D(t.contract),read_mode:Tt(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return G([j("MultiFeed"),te({contract:D(t.contract),feed_id:X(t.feedId),kind:qt(t.kind),nature:Ut(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ot=e=>{const t=e;return te({decimals:W(t.decimals),max_stale_seconds:z(t.maxStaleSeconds),provider:Ct(t.provider)})},$t=e=>{if("RequireDisjoint"===e)return G([j("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return G([j("AllowShared"),G(t.map((e=>te({contract:D(e.contract),kind:qt(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},Nt=e=>{const t=e,r=t.sources??[];let n,o;if("number"==typeof t.toleranceBps)n=1e4+t.toleranceBps,o=Math.max(1,Math.floor(1e8/n));else{const e=t.tolerance??{};n=Number(e.upperRatioBps),o=Number(e.lowerRatioBps)}return te({asset_decimals:W(Number(t.assetDecimals)),independence:$t(t.independence),max_price_stale_seconds:z(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:F(String(t.maxSanityPriceWad)),min_sanity_price_wad:F(String(t.minSanityPriceWad)),sources:G(r.map((e=>(e=>{if("Feed"in e)return G([j("Feed"),Ot(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return G([j("Scaled"),te({factor:Ot(t.factor),max_factor_wad:F(t.maxFactorWad),min_factor_wad:F(t.minFactorWad),quote:At(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return G([j("LpShare"),te({key_a:At(t.keyA),key_b:At(t.keyB),kind:G([j(t.kind||"ConstantProduct")]),pool:D(t.pool),reserve_a_decimals:W(t.reserveADecimals),reserve_b_decimals:W(t.reserveBDecimals),share_decimals:W(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:te({lower_ratio_bps:W(o),upper_ratio_bps:W(n)})})};function Pt(e,t){return ce(e,"upgrade",[K(t.wasmHash)])}function Mt(e,t){return ce(e,"migrate",[W(t.newVersion)])}function Lt(e){return ce(e,"pause",[])}function Dt(e){return ce(e,"unpause",[])}function Ft(e,t){return ce(e,"grant_role",[D(t.account),j(t.role)])}function Wt(e,t){return ce(e,"revoke_role",[D(t.account),j(t.role)])}function zt(e,t){return ce(e,"transfer_ownership",[D(t.newOwner),W(t.liveUntilLedger)])}function Vt(e){return ce(e,"accept_ownership",[])}function Xt(e,t){return ce(e,"set_swap_aggregator",[D(t.aggregator)])}function jt(e,t){return ce(e,"set_price_aggregator",[D(t.aggregator)])}function Ht(e,t){return ce(e,"set_accumulator",[D(t.accumulator)])}function Gt(e,t){return ce(e,"set_position_limits",[kt(t)])}function Kt(e,t){return ce(e,"approve_blend_pool",[D(t.pool)])}function Zt(e,t){return ce(e,"revoke_blend_pool",[D(t.pool)])}function Yt(e,t){return ce(e,"set_oracle",[At(t.key),Nt(t.oracle)])}function Jt(e,t){const r=t.toleranceBps,n=t.upperRatioBps??1e4+r,o=t.lowerRatioBps??Math.max(1,Math.floor(1e8/n));return ce(e,"set_tolerance",[At(t.key),te({lower_ratio_bps:W(o),upper_ratio_bps:W(n)})])}function Qt(e,t){return ce(e,"set_spoke_asset_flags",[W(t.spokeId),Y(t.hubId,t.asset),V(t.paused),V(t.frozen),V(t.noSeize)])}function er(e,t){return ce(e,"set_oracle_sanity_bounds",[D(t.asset),F(t.minPriceWad),F(t.maxPriceWad)])}function tr(e,t){return ce(e,"update_indexes",[D(e.caller),G(t.assets.map((e=>Y(e.hubId,e.asset))))])}function rr(e,t){return ce(e,"renew_account",[D(e.caller),z(t.accountNonce)])}function nr(e,t){return ce(e,"create_liquidity_pool",[W(t.hubId),D(t.asset),Et(t.params)])}function or(e,t){return ce(e,"upgrade_liquidity_pool_params",[Y(t.hubId,t.asset),Rt(t.params)])}function ar(e,t){return ce(e,"claim_revenue",[D(e.caller),G(t.assets.map((e=>Y(e.hubId,e.asset))))])}function sr(e,t){return ce(e,"add_rewards",[D(e.caller),Q(t.rewards)])}function ir(e,t){return ce(e,"update_account_threshold",[D(e.caller),V(t.hasRisks),G(t.accountNonces.map((e=>z(e))))])}const ur="00".repeat(32),lr=e=>{if("string"==typeof e)return K(e);const t=R.hp.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return p.ScVal.scvBytes(t)},cr=(e,...t)=>G([j(e),...t]),dr=e=>te({new_owner:D(e.newOwner),live_until_ledger:W(e.liveUntilLedger)}),pr=e=>te({asset:D(e.asset),bonus:W(e.bonus),borrow_cap:F(e.borrowCap),can_borrow:V(e.canBorrow),can_collateral:V(e.canCollateral),frozen:V(e.frozen),hub_id:W(e.hubId),paused:V(e.paused),liquidation_fees:W(e.liquidationFees),ltv:W(e.ltv),no_seize:V(e.noSeize),spoke_id:W(e.spokeId),supply_cap:F(e.supplyCap),threshold:W(e.threshold)}),fr=e=>te({account:D(e.account),role:j(e.role)});function hr(t,r,a){if(!t.governanceAddress)throw new Error("Stellar governanceAddress is required");const s=new o(t.governanceAddress),i=new e(t.caller,t.sourceSequence);return{xdr:new u(i,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(s.call(r,...a)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const mr=(e,t,r)=>hr(e,"propose",[D(e.caller),t,lr(r)]),gr=(e,t,r)=>hr(e,"execute_self",[H(),t,lr(r)]);function yr(e,t,r){return mr(e,cr("SetSwapAggregator",D(t.aggregator)),r)}function wr(e,t,r){return mr(e,cr("SetPriceAggregator",D(t.aggregator)),r)}function br(e,t,r){return mr(e,cr("SetAccumulator",D(t.accumulator)),r)}function vr(e,t,r){return mr(e,cr("SetPositionLimits",kt(t)),r)}function Sr(e,t){return mr(e,cr("CreateHub"),t)}function _r(e,t){return mr(e,cr("AddSpoke"),t)}function Ir(e,t,r){return mr(e,cr("RemoveSpoke",W(t.spokeId)),r)}function Br(e,t,r){return mr(e,cr("AddAssetToSpoke",pr(t)),r)}function Rr(e,t,r){return mr(e,cr("EditAssetInSpoke",pr(t)),r)}function Er(e,t,r){return mr(e,cr("RemoveAssetFromSpoke",te({hub_asset:Y((n=t).hubId,n.asset),spoke_id:W(n.spokeId)})),r);var n}function kr(e,t,r){return mr(e,cr("SetSpokeLiquidationCurve",te({hf_for_max_bonus_wad:F((n=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:W(n.liquidationBonusFactorBps),spoke_id:W(n.spokeId),target_hf_wad:F(n.targetHfWad)})),r);var n}function Ar(e,t,r){return mr(e,cr("SetPositionManager",D(t.manager),V(t.isActive)),r)}function xr(e,t,r){return mr(e,cr("SetMinBorrowCollateralUsd",F(t.floorWad)),r)}function Tr(e,t,r){return mr(e,cr("ApproveToken",D(t.token)),r)}function qr(e,t,r){return mr(e,cr("RevokeToken",D(t.token)),r)}function Ur(e,t,r){return mr(e,cr("ApproveBlendPool",D(t.pool)),r)}function Cr(e,t,r){return mr(e,cr("RevokeBlendPool",D(t.pool)),r)}function Or(e,t,r){return mr(e,cr("CreateLiquidityPool",te({asset:D((n=t).asset),hub_id:W(n.hubId),params:Et(n.params)})),r);var n}function $r(e,t,r){return mr(e,cr("UpgradeLiquidityPoolParams",te({hub_asset:Y((n=t).hubId,n.asset),params:Rt(n.params)})),r);var n}function Nr(e,t,r){return mr(e,cr("DeployPool",K(t.wasmHash)),r)}function Pr(e,t,r){return mr(e,cr("UpgradePool",K(t.wasmHash)),r)}function Mr(e,t,r){return mr(e,cr("UpgradeController",K(t.wasmHash)),r)}function Lr(e,t,r){return mr(e,cr("MigrateController",W(t.newVersion)),r)}function Dr(e,t,r){return mr(e,cr("TransferCtrlOwnership",dr(t)),r)}function Fr(e,t,r){return mr(e,cr("ConfigureAssetOracle",te({key:At((n=t).key),oracle:Nt(n.oracle)})),r);var n}function Wr(e,t,r){return mr(e,cr("EditOracleTolerance",te({key:At((n=t).key),tolerance:W(n.tolerance)})),r);var n}function zr(e,t,r){return mr(e,cr("UpgradeGov",K(t.wasmHash)),r)}function Vr(e,t,r){return mr(e,cr("UpdateGovDelay",W(t.newDelay)),r)}function Xr(e,t,r){return mr(e,cr("GrantGovRole",fr(t)),r)}function jr(e,t,r){return mr(e,cr("RevokeGovRole",fr(t)),r)}function Hr(e,t,r){return mr(e,cr("TransferGovOwnership",dr(t)),r)}function Gr(e,t){const r=G(t.argsXdr.map((e=>p.ScVal.fromXDR(e,"base64")))),n=lr(t.predecessor??ur);return hr(e,"execute",[H(),D(t.target),j(t.functionName),r,n,lr(t.salt)])}function Kr(e,t,r){return gr(e,cr("UpgradeGov",K(t.wasmHash)),r)}function Zr(e,t,r){return gr(e,cr("UpdateGovDelay",W(t.newDelay)),r)}function Yr(e,t,r){return gr(e,cr("GrantGovRole",fr(t)),r)}function Jr(e,t,r){return gr(e,cr("RevokeGovRole",fr(t)),r)}function Qr(e,t,r){return gr(e,cr("TransferGovOwnership",dr(t)),r)}const en=e=>G(e.map(D));function tn(e,t,r){return hr(e,"propose_canceller_reset",[en(t.newCancellers),lr(r)])}function rn(e,t,r){return hr(e,"execute_canceller_reset",[Z(t.executor,D),en(t.newCancellers),lr(r)])}function nn(e,t){return hr(e,"set_spoke_asset_flags",[D(e.caller),W(t.spokeId),Y(t.hubId,t.asset),V(t.paused),V(t.frozen),V(t.noSeize)])}function on(e,t){return hr(e,"set_oracle_sanity_bounds",[D(e.caller),D(t.asset),F(t.minPriceWad),F(t.maxPriceWad)])}function an(e){return hr(e,"create_hub",[D(e.caller)])}function sn(e){return hr(e,"add_spoke",[D(e.caller)])}function un(e,t){return hr(e,"revoke_role_immediate",[D(t.account),j(t.role)])}function ln(e){return hr(e,"pause",[D(e.caller)])}function cn(e,t){return mr(e,cr("Unpause"),t)}const dn=e=>e.toXDR("base64"),pn=e=>p.ScVal.fromXDR(e,"base64"),fn=e=>e.map((e=>String(d(pn(e))))).join(":"),hn=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),mn=e=>Number(e),gn=e=>String(e),yn=e=>e instanceof Uint8Array?R.hp.from(e).toString("hex"):R.hp.isBuffer(e)?e.toString("hex"):String(e),wn=["None","Multiply","Long","Short"],bn=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit","flash_pos"],vn=e=>Array.isArray(e)?e:[],Sn=(e,t)=>{const r="Borrow"===t;return{action:(n=e[0],bn[mn(n)]??hn(n)),positionType:t,hubId:mn(e[1]),asset:gn(e[2]),scaledAmountRay:hn(e[3]),indexRay:hn(e[4]),amount:hn(e[5]),liquidationThresholdBps:r?void 0:mn(e[6]),liquidationBonusBps:r?void 0:mn(e[7]),loanToValueBps:r?void 0:mn(e[8]),liquidationFeesBps:r?void 0:mn(e[9])};var n},_n=e=>{return{owner:gn(e[0]),spokeId:mn(e[1]),mode:(t=e[2],wn[mn(t)]??"None")};var t},In=e=>Array.isArray(e)?e[1]:void 0,Bn=e=>{const t=(r=e,Array.isArray(r)?gn(r[0]):gn(r));var r;if("Token"===t)return{Token:gn(In(e))};if("Ref"===t)return{Ref:gn(In(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:gn(t.Token)};if(void 0!==t.Ref)return{Ref:gn(t.Ref)}}return{Token:gn(e)}},Rn=e=>{const t=e.tolerance??{};return{assetDecimals:mn(e.asset_decimals),maxPriceStaleSeconds:mn(e.max_price_stale_seconds),sources:vn(e.sources).map((e=>e)),tolerance:{upperRatio:mn(t.upper_ratio_bps),lowerRatio:mn(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:hn(e.min_sanity_price_wad),maxSanityPriceWad:hn(e.max_sanity_price_wad)}},En={"market:create":e=>({topic:"market:create",data:{hubId:mn(e.hub_id),baseAsset:gn(e.base_asset),maxBorrowRate:hn(e.max_borrow_rate),baseBorrowRate:hn(e.base_borrow_rate),slope1:hn(e.slope1),slope2:hn(e.slope2),slope3:hn(e.slope3),midUtilization:hn(e.mid_utilization),optimalUtilization:hn(e.optimal_utilization),maxUtilization:hn(e.max_utilization),reserveFactor:mn(e.reserve_factor),marketAddress:gn(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{hubId:void 0===e.hub_id?void 0:mn(e.hub_id),asset:gn(e.asset),maxBorrowRateRay:hn(e.max_borrow_rate),baseBorrowRateRay:hn(e.base_borrow_rate),slope1Ray:hn(e.slope1),slope2Ray:hn(e.slope2),slope3Ray:hn(e.slope3),midUtilizationRay:hn(e.mid_utilization),optimalUtilizationRay:hn(e.optimal_utilization),maxUtilizationRay:hn(e.max_utilization),reserveFactorBps:mn(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:vn(e).map((e=>{return t=vn(e),{hubId:mn(t[0]),asset:gn(t[1]),timestamp:mn(t[2]),supplyIndexRay:hn(t[3]),borrowIndexRay:hn(t[4]),cash:hn(t[5]),suppliedRay:hn(t[6]),borrowedRay:hn(t[7]),revenueRay:hn(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:vn(e).map((e=>{const t=e;return{hubId:mn(t.hub_id),asset:gn(t.asset),params:(r=t.params,{maxBorrowRateRay:hn(r.max_borrow_rate),baseBorrowRateRay:hn(r.base_borrow_rate),slope1Ray:hn(r.slope1),slope2Ray:hn(r.slope2),slope3Ray:hn(r.slope3),midUtilizationRay:hn(r.mid_utilization),optimalUtilizationRay:hn(r.optimal_utilization),maxUtilizationRay:hn(r.max_utilization),reserveFactorBps:mn(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:mn(r.flashloan_fee),assetId:gn(r.asset_id),assetDecimals:mn(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=vn(e);return{topic:"position:batch_update",data:{accountId:hn(t[0]),accountAttributes:_n(vn(t[1])),updates:[...vn(t[2]).map((e=>Sn(vn(e),"Deposit"))),...vn(t[3]).map((e=>Sn(vn(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:mn(e.hub_id),asset:gn(e.asset),receiver:gn(e.receiver),caller:gn(e.caller),amount:hn(e.amount),fee:hn(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Bn(e.key),oracle:Rn(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:gn(e.asset),oracle:Rn(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:gn(e.liquidator),accountId:hn(e.account_id),repaidUsdWad:hn(e.repaid_usd_wad),bonusBps:hn(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:hn(e.account_id),totalBorrowUsdWad:hn(e.total_borrow_usd_wad),totalCollateralUsdWad:hn(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:gn(e.token),amount:hn(e.amount),usdValueWad:void 0===e.usd_value_wad?void 0:hn(e.usd_value_wad),accountId:hn(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:mn(e.hub_id),asset:gn(e.asset),amount:hn(e.amount),fee:hn(e.fee),amountSent:hn(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:gn(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:yn(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:gn(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:gn(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:gn(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:gn(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:yn(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:mn(e.max_supply_positions),maxBorrowPositions:mn(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:hn(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:gn(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:mn(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:hn(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:hn(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:mn(t.liquidation_bonus_factor_bps)}}},"position:flash_position":e=>({topic:"position:flash_position",data:{accountId:hn(e.account_id),hubId:mn(e.hub_id),asset:gn(e.asset),receiver:gn(e.receiver),caller:gn(e.caller),amount:hn(e.amount),amountReceived:hn(e.amount_received),fee:hn(e.fee)}}),"revenue:claim":e=>({topic:"revenue:claim",data:{hubId:mn(e.hub_id),asset:gn(e.asset),caller:gn(e.caller),accumulator:gn(e.accumulator),amount:hn(e.amount)}}),"account:delegate":e=>({topic:"account:delegate",data:{accountId:hn(e.account_id),owner:gn(e.owner),delegate:gn(e.delegate),granted:Boolean(e.granted)}}),"config:hub":e=>({topic:"config:hub",data:{hubId:mn(e.hub_id)}}),"config:spoke_asset":e=>{const t=e.config;return{topic:"config:spoke_asset",data:{spokeId:mn(e.spoke_id),hubId:mn(e.hub_id),asset:gn(e.asset),config:{isCollateralizable:Boolean(t.is_collateralizable),isBorrowable:Boolean(t.is_borrowable),paused:Boolean(t.paused),frozen:Boolean(t.frozen),noSeize:Boolean(t.no_seize),loanToValueBps:mn(t.loan_to_value),liquidationThresholdBps:mn(t.liquidation_threshold),liquidationBonusBps:mn(t.liquidation_bonus),liquidationFeesBps:mn(t.liquidation_fees),supplyCap:hn(t.supply_cap),borrowCap:hn(t.borrow_cap)}}}},"config:remove_spoke_asset":e=>({topic:"config:remove_spoke_asset",data:{spokeId:mn(e.spoke_id),hubId:mn(e.hub_id),asset:gn(e.asset)}}),"strategy:blend_migration":e=>({topic:"strategy:blend_migration",data:{accountId:hn(e.account_id),blendPool:gn(e.blend_pool),collateralCount:mn(e.collateral_count),supplyCount:mn(e.supply_count),debtCount:mn(e.debt_count)}}),"strategy:harvest":e=>({topic:"strategy:harvest",data:{from:gn(e.from),amount:hn(e.amount),pricePerShare:hn(e.price_per_share)}}),"governance:deploy_controller":e=>({topic:"governance:deploy_controller",data:{controller:gn(e.controller),wasmHash:yn(e.wasm_hash)}}),"governance:deploy_price_aggregator":e=>({topic:"governance:deploy_price_aggregator",data:{priceAggregator:gn(e.price_aggregator),wasmHash:yn(e.wasm_hash)}})},kn=Object.freeze(Object.keys(En));function An(e,t){const r=fn(e),n=En[r];return n?n(d(pn(t))):null}const xn=1e4;function Tn(e,t){return`${e}-${BigInt(t).toString(10)}`}function qn(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Un(e,t=0){return 1e4*e+t}function Cn(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const On=(e,t,r)=>{const n=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&n.searchParams.set(e,String(t));return n.toString()};async function $n(e,t){if(!t.baseUrl)throw new Error("Stellar quote baseUrl is required");if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=On(t.baseUrl,"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,simulate:e.simulate,referralId:e.referralId,platform:e.platform,fresh:e.fresh}),n=await fetch(r,t.fetchOptions);if(!n.ok){const e=await n.text().catch((()=>""));throw new Error(`Stellar quote server responded ${n.status} ${n.statusText} for ${r} — ${e}`)}return await n.json()}async function Nn(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=On(e.baseUrl,"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}function Pn(e,t){const r=e[t];return"function"==typeof r?r.call(e):r}function Mn(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Ln(e){return Dn(Pn(e,"bytes"))}function Dn(e){const t=e;return R.hp.from("value"in t?t.value:t)}const Fn=10,Wn=5,zn=3,Vn=Fn+Wn*N+zn*P,Xn=16384;class jn extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const Hn=(e,t)=>{throw new jn(e,t)},Gn=e=>{const t="string"==typeof e?e:e&&"object"==typeof e&&"routeXdr"in e?e.routeXdr:void 0;if("string"==typeof t&&t.length>2*Xn)return Hn("OVERSIZED",`encoded route has ${t.length} characters`);try{return Ln(ie(e))}catch(e){return Hn("MALFORMED",e instanceof Error?e.message:String(e))}},Kn=e=>{let t;try{t=p.ScVal.fromXDR(e)}catch(e){return Hn("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==Mn(t))return Hn("MALFORMED","payload must be a StrategyPayload map");const r=Pn(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===Mn(Pn(e,"key"))?Pn(Pn(e,"key"),"sym").toString():"")).join(","))return Hn("MALFORMED","payload fields must be exactly amounts, assets, ops");const[n,o,a]=r.map((e=>Pn(e,"val")));return"scvVec"!==Mn(n)||"scvVec"!==Mn(o)||"scvBytes"!==Mn(a)?Hn("MALFORMED","payload field has the wrong type"):{amounts:Pn(n,"vec")??[],assets:Pn(o,"vec")??[],ops:Ln(a)}};function Zn(e){const r=Gn(e);0===r.length&&Hn("MALFORMED","route is empty"),r.length>Xn&&Hn("OVERSIZED",`route has ${r.length} bytes, above ${Xn}`);const n=Kn(r),o=n.assets.length,a=n.amounts.length;0===o&&Hn("MALFORMED","asset registry is empty"),(o>M||a>L)&&Hn("OVERSIZED",`registries hold ${o} assets and ${a} amounts`);const s=n.assets.map(((e,r)=>"scvAddress"!==Mn(e)?Hn("MALFORMED",`assets[${r}] is not an address`):t.fromScAddress(Pn(e,"address")).toString())),i=n.amounts.map(((e,t)=>"scvI128"!==Mn(e)?Hn("MALFORMED",`amounts[${t}] is not an i128`):c(e))),u=n.ops;u.length<Fn&&Hn("MALFORMED","program header is truncated"),u.length>Vn&&Hn("OVERSIZED",`program has ${u.length} bytes, above ${Vn}`);const l=e=>{const t=u[e];return void 0===t?Hn("MALFORMED",`program byte ${e} is missing`):t},d=l(0);d!==A&&Hn("UNSUPPORTED_VERSION",`program version ${d}, expected ${A}`);const p=l(8),f=l(9);0===p&&Hn("INVALID_STRUCTURE","program has no instructions"),(p>N||f>P)&&Hn("OVERSIZED",`program declares ${p} instructions and ${f} weights`);const h=Fn+Wn*p;u.length!==h+zn*f&&Hn("MALFORMED","program length does not match its instruction and weight counts");const m=l(1),g=l(2),y=l(3);(m>=o||g>=o||y>=a)&&Hn("MALFORMED","header index is outside its registry"),m===g&&Hn("INVALID_STRUCTURE","token_in equals token_out");const w=u.readUInt32BE(4),b=[];for(let e=0;e<f;e+=1){const t=u.readUIntBE(h+zn*e,zn);(0===t||t>x)&&Hn("INVALID_STRUCTURE",`split weight ${t} outside 1..=${x}`),b.push(t)}const v=e=>s[e]??Hn("MALFORMED",`asset index ${e} is outside the registry`),S=e=>i[e]??Hn("MALFORMED",`amount index ${e} is outside the registry`),_=[];let I;for(let e=0;e<p;e+=1){const t=Fn+Wn*e,r=l(t),n=l(t+1),o=l(t+2),s=l(t+3),i=l(t+4),u=E.find((e=>k[e]===r));let c;if(u||r===T||r===q||Hn("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),n===U)c={kind:"all"};else if(n===C)void 0!==I&&I===s||Hn("INVALID_STRUCTURE",`instruction ${e} does not chain onto its predecessor`),c={kind:"prev"};else if(n>=$){const t=b[n-$];void 0===t&&Hn("MALFORMED",`instruction ${e} weight index is out of range`),c={kind:"ppm",ppm:t}}else c={kind:"fixed",amount:S(n-O)};const d=v(o);r!==T&&r!==q?(s===i&&Hn("INVALID_STRUCTURE",`instruction ${e} swaps a token for itself`),_.push({kind:"swap",venue:u,mode:c,pool:d,tokenIn:v(s),tokenOut:v(i)}),I=i):("all"!==c.kind&&Hn("MALFORMED",`liquidity instruction ${e} must use mode All`),i>=a&&Hn("MALFORMED",`instruction ${e} amount index is out of range`),_.push({kind:r===T?"burn":"mint",pool:d,shareToken:v(s),amountIndex:i}),I=r===q?s:void 0)}const B=S(y);return B<=0n&&Hn("MIN_OUT_TOO_LOW",`encoded total_min_out is ${B}`),{version:d,tokenIn:v(m),tokenOut:v(g),totalMinOut:B,referralId:w,assets:s,amounts:i,ops:_,weights:b}}function Yn(e,t){if(i.isValidContract(e))return e;if(!t)return Hn("EXPECTATION_MISSING",`token ${e} is not a contract id; pass \`network\` to derive its asset contract`);try{const n=e.indexOf(":");return("XLM"===e||"native"===e?r.native():new r(e.slice(0,n),e.slice(n+1))).contractId(B[t])}catch{return Hn("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Jn=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):Hn("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function Qn(e,t){const r=Jn(t.minOut,"expected.minOut");r<=0n&&Hn("EXPECTATION_MISSING","expected.minOut must be positive");const n=Zn(e);if(n.tokenIn!==t.tokenIn&&Hn("TOKEN_IN_MISMATCH",`route spends ${n.tokenIn}, expected ${t.tokenIn}`),n.tokenOut!==t.tokenOut&&Hn("TOKEN_OUT_MISMATCH",`route delivers ${n.tokenOut}, expected ${t.tokenOut}`),n.totalMinOut<r&&Hn("MIN_OUT_TOO_LOW",`route enforces a minimum of ${n.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Jn(t.amountIn,"expected.amountIn");for(const t of n.ops)"swap"===t.kind&&"fixed"===t.mode.kind&&t.tokenIn===n.tokenIn&&t.mode.amount>e&&Hn("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return n}const eo=e=>ne(e).toXDR("base64");function to(t,r){if(!t.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const a=new o(t.routerAddress),s=new e(t.caller,t.sourceSequence),i=ie(((e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e)(r,t.referralId));return{xdr:new u(s,{fee:t.fee??n,networkPassphrase:B[t.network]}).addOperation(a.call("execute_strategy",D(t.caller),F(t.totalIn),i)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function ro(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(oo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(oo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function no(e,t={}){const r=t.expected??{},n="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:ro(e,t),o=[e.amountOutMin,r.minOut].filter((e=>void 0!==e)).map((e=>{if("bigint"==typeof e)return e;if("string"!=typeof e||!/^\d+$/.test(e))throw new jn("MALFORMED","minimum output must be a base-unit integer string");return BigInt(e)})).reduce(((e,t)=>void 0===e||t>e?t:e),void 0);if(void 0===o)throw new jn("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return Qn(n,{tokenIn:Yn(r.tokenIn??e.from,t.network),tokenOut:Yn(r.tokenOut??e.to,t.network),minOut:o,amountIn:r.amountIn??e.amountIn}),n}const oo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function ao(e){try{const{envelopeXdr:r,networkPassphrase:n,routerAddress:o,viewer:a,operationIndex:s}=e;if(!n||!i.isValidContract(o)||new t(a).toString()!==a||"string"!=typeof r||r.length>1048576||r.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)||void 0!==s&&(!Number.isSafeInteger(s)||s<0))return null;const l=u.fromXDR(r,n),d="innerTransaction"in l?l.innerTransaction:l;if(void 0!==s&&s>=d.operations.length)return null;let p=null;for(const[e,r]of d.operations.entries()){if(void 0!==s&&e!==s)continue;if("invokeHostFunction"!==r.type)continue;const n=r.func;if("hostFunctionTypeInvokeContract"!==Mn(n))continue;const u=Pn(n,"invokeContract");if(t.fromScAddress(Pn(u,"contractAddress")).toString()!==o||"execute_strategy"!==Pn(u,"functionName").toString())continue;const l=Pn(u,"args"),[d,f,h]=l;if(3!==l.length||!d||!f||!h||"scvAddress"!==Mn(d)||"scvI128"!==Mn(f)||"scvBytes"!==Mn(h))return null;if(t.fromScAddress(Pn(d,"address")).toString()!==a)continue;const m=c(f);if(m<=0n)return null;const g=Zn(Ln(h));if(g.tokenIn===g.tokenOut||!i.isValidContract(g.tokenIn)||!i.isValidContract(g.tokenOut))return null;if(p)return null;p={tokenIn:g.tokenIn,tokenOut:g.tokenOut,amountInAtoms:m.toString(),operationIndex:e}}return p}catch{return null}}class so extends Error{code;offender;constructor(e,t,r){super(`Stellar authorization check failed [${e}]: ${t}${r?` — ${r.contract}.${r.fn}(${r.args.join(", ")})`:""}`),this.name="StellarAuthPolicyError",this.code=e,this.offender=r}}const io=e=>e&&"scvAddress"===Mn(e)?t.fromScAddress(Pn(e,"address")).toString():void 0,uo=e=>e&&"scvI128"===Mn(e)?c(e):void 0,lo=e=>e&&"scvVec"===Mn(e)?Pn(e,"vec")??[]:void 0,co=(e,t)=>{if(!e||"scvMap"!==Mn(e))return;const r=(Pn(e,"map")??[]).find((e=>"scvSymbol"===Mn(Pn(e,"key"))&&Pn(Pn(e,"key"),"sym").toString()===t));return r?Pn(r,"val"):void 0},po=e=>io(e)??uo(e)?.toString()??e.toXDR("base64"),fo=e=>({contract:t.fromScAddress(Pn(e,"contractAddress")).toString(),fn:Pn(e,"functionName").toString(),args:Pn(e,"args").map(po)}),ho=e=>{const t=Pn(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===Mn(t)?Pn(t,"contractFn"):void 0};function mo(e,r,n){const o=e.filter((e=>{const o=Pn(e,"credentials"),a=Mn(o);if("sorobanCredentialsAddress"!==a&&"sorobanCredentialsSourceAccount"!==a)throw new so("MALFORMED_TRANSACTION","unsupported authorization credentials");return("sorobanCredentialsAddress"===a?t.fromScAddress(Pn(Pn(o,"address"),"address")).toString():n??r.caller)===r.caller}));if(o.length>1)throw new so("DUPLICATE_ENTRY",`${o.length} authorization entries for ${r.caller}, expected one`);const a=o[0];if(!a)return;const s=ho(Pn(a,"rootInvocation"));if(!s)throw new so("UNEXPECTED_ROOT","root is not a contract call");const i=fo(s);if(i.contract!==r.root.contract||i.fn!==r.root.fn)throw new so("UNEXPECTED_ROOT",`expected ${r.root.contract}.${r.root.fn}`,i);const u=r.transfers.map((()=>0n)),l=(r.calls??[]).map((()=>0));for(const e of Pn(Pn(a,"rootInvocation"),"subInvocations")){const t=ho(e);if(!t)throw new so("UNEXPECTED_CALL","sub-invocation is not a contract call");const n=fo(t);if(Pn(e,"subInvocations").length>0)throw new so("NESTED_INVOCATION","sub-invocation carries its own sub-invocations",n);const o=(r.calls??[]).findIndex((e=>e.contract===n.contract&&e.fn===n.fn));if(-1!==o){const e=(r.calls??[])[o],a=e.reject(Pn(t,"args"));if(a)throw new so("UNEXPECTED_CALL",a,n);if(l[o]=(l[o]??0)+1,(l[o]??0)>e.maxCount)throw new so("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,n);continue}if("transfer"!==n.fn||3!==Pn(t,"args").length)throw new so("UNEXPECTED_CALL","only `transfer` is allowed",n);if(!r.transfers.some((e=>e.token===n.contract)))throw new so("UNEXPECTED_TOKEN","transfer on an unexpected token",n);const[a,s,i]=Pn(t,"args");if(io(a)!==r.caller)throw new so("UNEXPECTED_SENDER","transfer is not from the caller",n);const c=io(s),d=r.transfers.findIndex((e=>e.token===n.contract&&e.to===c));if(-1===d)throw new so("UNEXPECTED_RECIPIENT","transfer to an unexpected recipient",n);const p=uo(i),f=r.transfers[d],h=(u[d]??0n)+(p??0n);if(void 0===p||p<=0n||h>f.maxAmount)throw new so("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,n);u[d]=h}}const go=e=>{throw new so("MALFORMED_TRANSACTION",e)},yo=(e,t)=>{const r=new Map;for(const t of lo(e)??go("payments argument is not a vector")){const[e,n]=lo(t)??[],o=io(co(e,"asset")),a=uo(n);if(void 0===o||void 0===a||a<0n)return go("payment is not a (HubAssetKey, i128) tuple");r.set(o,(r.get(o)??0n)+a)}return[...r].map((([e,r])=>({token:e,to:t,maxAmount:r})))},wo=new Set([1,3,5]),bo=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(io(e[0])!==t)return"`from` is not the caller";if(io(e[1])!==r||io(e[2])!==r)return"`spender` and `to` must be the lending controller";const n=lo(e[3]);if(!n)return"requests is not a vector";for(const e of n){const t=co(e,"request_type");if(!t||"scvU32"!==Mn(t)||!wo.has(Pn(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function vo(e,t,r){const{contract:n,fn:o}=fo(t),a=Pn(t,"args"),s={caller:e,root:{contract:n,fn:o},transfers:[]};if(n===r.governance)return s;if(n===r.aggregatorRouter){if("execute_strategy"!==o)return s;const t=uo(a[1]);if(io(a[0])!==e||void 0===t||"scvBytes"!==Mn(a[2]))return go("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=Zn(Ln(a[2]));return s.transfers=[{token:r.tokenIn,to:n,maxAmount:t}],s}if(n!==r.lendingController)throw new so("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${n}; pass an explicit policy`);if(io(a[0])!==e)throw new so("CALLER_MISMATCH",`${o} is not invoked for ${e}`);switch(o){case"supply":s.transfers=yo(a[3],r.lendingPool);break;case"repay":case"liquidate":s.transfers=yo(a[2],r.lendingPool);break;case"multiply":{const e=a[8];e&&"scvVoid"!==Mn(e)&&(s.transfers=yo(p.ScVal.scvVec([e]),n));break}case"migrate_from_blend":{const t=io(a[4])??go("blend_pool is not an address");s.calls=[bo(t,e,n)];break}}return s}const So=e=>{let t;try{t=p.TransactionEnvelope.fromXDR(e,"base64")}catch{return go("not a transaction envelope")}if("envelopeTypeTx"!==Mn(t))return go("expected a regular (v1) transaction");const r=Pn(Pn(t,"v1"),"tx"),n=Pn(r,"operations")[0];if(!n||1!==Pn(r,"operations").length)return go("expected exactly one operation");const o=Pn(n,"body");if("invokeHostFunction"!==Mn(o))return go("operation is not a contract invocation");const a=Pn(o,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==Mn(Pn(a,"hostFunction"))?go("host function is not a contract call"):{source:(s=Pn(n,"sourceAccount")??Pn(r,"sourceAccount"),i.encodeEd25519PublicKey(Dn("keyTypeMuxedEd25519"===Mn(s)?Pn(Pn(s,"med25519"),"ed25519"):Pn(s,"ed25519")))),op:a,call:Pn(Pn(a,"hostFunction"),"invokeContract")};var s};function _o(e,t){const r=So(e);if(void 0!==t.builtXdr&&Pn(So(t.builtXdr).op,"hostFunction").toXDR("base64")!==Pn(r.op,"hostFunction").toXDR("base64"))throw new so("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",fo(r.call));const n=t.policy??vo(t.caller,r.call,{...I(t.network),...t.deployment});mo(Pn(r.op,"auth"),n,r.source)}function Io(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function Bo(e,t,r){const n=r?.instructionLeeway??2e7;if(!Number.isInteger(n)||n<0||n>4294967295)throw new Error("instructionLeeway must be an integer from 0 to 4294967295");const o=u.fromXDR(t,r?.network?B[r.network]:"");try{const t=await e.simulateTransaction(o,{cpuInstructions:n});if(l.Api.isSimulationError(t))throw new Error(t.error);return l.assembleTransaction(o,t).build().toXDR()}catch(e){if(r?.invokedContractId)throw Io(r.invokedContractId,e);throw e}}async function Ro(e,t,r){return Bo(e,t.xdr,r)}function Eo(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function ko(e,t){return new Uint8Array(0)}const Ao=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return R.hp.from(t,"hex")};function xo(t){const r=new e(t.caller,t.sourceSequence),n=new o(t.forwarderAddress).call("mint_and_forward",p.ScVal.scvBytes(Ao(t.message)),p.ScVal.scvBytes(Ao(t.attestation)));return{xdr:new u(r,{fee:t.fee??"10000000",networkPassphrase:B[t.network]}).addOperation(n).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const To=10n**27n,qo=10n**18n,Uo=10000n,Co=27,Oo=18;function $o(e,t="value"){let r;if("bigint"==typeof e)r=e;else if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Stellar math: ${t} must be a safe integer, got ${e}`);r=BigInt(e)}else{const n=e.trim();if(!/^-?\d+$/.test(n))throw new Error(`Stellar math: ${t} must be a decimal integer string, got "${e}"`);r=BigInt(n)}if(r<0n)throw new Error(`Stellar math: ${t} must be non-negative, got ${r}`);return r}function No(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function Po(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");const n=e*t,o=n/r;return n%r===0n?o:o+1n}function Mo(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function Lo(e,t){if(0n===t)throw new Error("Stellar math: division by zero");const r=e/t;return e%t>=t/2n+t%2n?r+1n:r}const Do=e=>10n**BigInt(e);function Fo(e,t,r){return t===r?e:r>t?e*Do(r-t):e/Do(t-r)}function Wo(e,t,r){if(t===r)return e;if(r>t)return e*Do(r-t);const n=Do(t-r),o=e/n;return e%n===0n?o:o+1n}function zo(e,t,r){return t===r?e:r>t?e*Do(r-t):Lo(e,Do(t-r))}const Vo={floor:No,ceil:Po,halfUp:Mo},Xo={floor:Fo,ceil:Wo,halfUp:zo};function jo(e,t,r,n){return Xo[n](Vo[n](e,t,To),Co,r)}function Ho(e,t,r){return jo($o(e,"scaledRay"),$o(t,"indexRay"),r,"floor")}function Go(e,t,r){return jo($o(e,"scaledRay"),$o(t,"indexRay"),r,"ceil")}function Ko(e,t,r){return jo($o(e,"scaledRay"),$o(t,"indexRay"),r,"halfUp")}function Zo(e,t){if(t>Co)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return Fo(e,t,Co)}function Yo(e,t,r,n){const o=Vo[n](e,t,To),a=Xo[n](o,Co,Oo);return Vo[n](a,r,qo)}function Jo(e,t,r,n){const o=Xo[n](Zo(e,t),Co,Oo);return Vo[n](o,r,qo)}const Qo=e=>Number(e)/1e18,ea=e=>Number(e)/1e27,ta=(e,t)=>Number(e)/10**t;function ra(e,t){if(!Number.isFinite(e)||e<=0||e>=1e21)return 0n;const r=e.toFixed(t),[n="0",o=""]=r.split(".");return BigInt(n+o.padEnd(t,"0"))}const na=e=>ra(e,Oo),oa=(e,t)=>Mo(e,t,To),aa=(e,t)=>Mo(e,To,t);function sa(e,t){return 0n===t?0n:aa(e,t)}function ia(e,t){const r=e>To?To:e,n=$o(t.baseRateRay,"irm.baseRateRay"),o=$o(t.slope1Ray,"irm.slope1Ray"),a=$o(t.slope2Ray,"irm.slope2Ray"),s=$o(t.slope3Ray,"irm.slope3Ray"),i=$o(t.midUtilizationRay,"irm.midUtilizationRay"),u=$o(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),l=$o(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<i)c=n+aa(oa(r,o),i);else if(r<u){const e=u-i;c=n+o+aa(oa(r-i,a),e)}else{const e=To-u;c=n+o+a+(0n===e?0n:aa(oa(r-u,s),e))}return c>l?l:c}function ua(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:Mo(oa(e,t),Uo-BigInt(r),Uo)}const la=e=>ea(e),ca=e=>Math.expm1(ea(e)),da=5n*qo,pa=(e,t,r)=>`${e}:${t}:${r}`;function fa(e,t,r,n){const o=Array.isArray(e)?e:void 0,a=o?o.find((e=>e.spokeId===t&&e.hubId===r&&e.asset===n)):e[pa(t,r,n)]??Object.values(e).find((e=>e.spokeId===t&&e.hubId===r&&e.asset===n));if(!a)throw new Error(`Stellar math: no reserve for ${pa(t,r,n)}`);return a}const ha=/^0*[1-9]\d*$/,ma=e=>"string"==typeof e&&ha.test(e)?BigInt(e).toString():null,ga=(e,t)=>`${e}:${t}`;function ya(e){const t=new Map,r=new Map,n=new Set,o=new Set;for(const a of e?.indexes??[]){const e=ga(a.hubId,a.asset),s=ma(a.supplyIndex),i=ma(a.borrowIndex),u=ma(a.usdPrice),l=t.get(e),c=l&&ma(l.supplyIndex)===s&&ma(l.borrowIndex)===i&&ma(l.usdPrice)===u;null==s||null==i||null==u||l&&!c?n.add(e):l||t.set(e,a);const d=!1===a.valid||!0===a.stale||!0===a.deviation,p=r.get(a.asset);null==u||d||void 0!==p&&p.toString()!==u?o.add(a.asset):void 0===p&&r.set(a.asset,BigInt(u))}for(const e of n)t.delete(e);for(const e of o)r.delete(e);return{indexes:t,prices:r,rejectedIndexKeys:n,rejectedAssets:o}}const wa=(e,t)=>No(e,BigInt(t),Uo);function ba(e,t,r,n){const o="supply"===e.side,a=Math.min(e.entryLtvBps,e.entryLiquidationThresholdBps);return{side:e.side,hubId:e.hubId,asset:e.asset,decimals:e.decimals,scaledRay:e.scaledRay.toString(),indexRay:e.indexRay.toString(),usdPriceWad:e.priceWad.toString(),usdPrice:Qo(e.priceWad),amountBase:t.toString(),amountShort:ta(t,e.decimals),usdWad:r.toString(),usd:Qo(r),gateUsdWad:n.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:o?wa(n,a).toString():"0",liquidationWeightedUsdWad:o?wa(n,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function va(e){if("supply"===e.side)return ba(e,jo(e.scaledRay,e.indexRay,e.decimals,"floor"),Yo(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),Yo(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=jo(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=Yo(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ba(e,t,r,r)}function Sa(e,t,r,n){const o=Zo(t,r);return"supply"===e?No(o,To,n):Po(o,To,n)}function _a(e,t,r,n){const o=Zo(t,r);return"supply"===e?Po(o,To,n):No(o,To,n)}function Ia(e,t){return va({...e,scaledRay:Sa(e.side,t,e.decimals,e.indexRay)})}const Ba=(...e)=>{for(const t of e){const e=ma(t);if(null!=e)return BigInt(e)}return To};function Ra(e,t,r,n){const o=$o("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===o)return null;const a=n.indexes.get(ga(t.hubId,t.asset)),s=n.prices.get(t.asset),i="supply"===e?Ba(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):Ba(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),u=s??na(r.usdPrice);return va({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:o,indexRay:i,priceWad:u,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==a&&void 0!==s})}const Ea=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function ka(e,t,r,n,o){const a=Ea(t,(e=>e.usdWad)),s=Ea(t,(e=>e.ltvWeightedUsdWad)),i=Ea(t,(e=>e.liquidationWeightedUsdWad)),u=Ea(r,(e=>e.usdWad)),l=0n===u?null:No(i,qo,u),c=0n===i?0:Number(u)/Number(i)*100,d=s<n||s<=u?0n:s-u;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:a.toString(),totalCollateralUsd:Qo(a),ltvWeightedCollateralUsdWad:s.toString(),ltvWeightedCollateralUsd:Qo(s),liquidationWeightedCollateralUsdWad:i.toString(),liquidationWeightedCollateralUsd:Qo(i),totalDebtUsdWad:u.toString(),totalDebtUsd:Qo(u),healthFactorWad:null===l?null:l.toString(),healthFactor:null===l?null:Qo(l),healthPercent:c,borrowLimitUsdWad:s.toString(),borrowLimitUsd:Qo(s),availableBorrowUsdWad:d.toString(),availableBorrowUsd:Qo(d),minBorrowCollateralUsdWad:n.toString(),minBorrowCollateralUsd:Qo(n),isLiquidatable:null!==l&&l<qo,liveDataValid:o}}function Aa(e){const{positions:t,reserves:r,liveState:n}=e,o=t[0];if(!o)throw new Error("Stellar math: computeAccountRisk needs at least one position row");for(const e of t)if(e.accountId!==o.accountId)throw new Error(`Stellar math: computeAccountRisk received mixed account ids (${o.accountId}, ${e.accountId})`);const a=ya(n),s=[],i=[];for(const e of t){const t=fa(r,e.spokeId,e.hubId,e.asset),n=Ra("supply",e,t,a);n&&s.push(n);const o=Ra("borrow",e,t,a);o&&i.push(o)}const u=null!=n?.minBorrowCollateralUsdWad?$o(n.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):da,l=void 0!==n&&[...s,...i].every((e=>e.liveDataUsed));return ka({accountId:o.accountId,owner:o.owner,spokeId:o.spokeId,mode:o.positionMode},s,i,u,l)}const xa=200n,Ta=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),qa=e=>e<0n?0n:e,Ua=(e,t,r,n)=>({amountBase:e.amount,amountShort:ta(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:n}),Ca=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function Oa(e){const t=e.assetDecimals,r=$o(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:ra(e.hubPool.suppliedShort,t),borrowedBase:ra(e.hubPool.borrowedShort,t),cashBase:ra(e.availableLiquidityShort,t),spokeSuppliedBase:ra(e.suppliedShort,t),spokeBorrowedBase:ra(e.borrowedShort,t),maxUtilizationRay:r>=To?null:r}}const $a=(e,t)=>e<=0n?null:Number(t)/Number(e);function Na(e,t){if(e<=0n||!t(0n))return 0n;let r=0n,n=e+1n;for(;n-r>1n;){const e=(r+n)/2n;t(e)?r=e:n=e}return r}const Pa=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Ma(e,t,r){if(t.paused)return Ca("paused");if(t.frozen)return Ca("frozen");if(!t.isBorrowable)return Ca("cap");const n=t.assetDecimals,o=Oa(t),a=Pa(e.borrows,t),s=ya(r).indexes.get(ga(t.hubId,t.asset)),i=a?BigInt(a.indexRay):$o(s?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),u=a?BigInt(a.usdPriceWad):function(e,t){return ya(t).prices.get(e.asset)??na(e.usdPrice)}(t,r),l=a?BigInt(a.scaledRay):0n,c=BigInt(e.totalDebtUsdWad)-(a?BigInt(a.usdWad):0n),d=BigInt(e.ltvWeightedCollateralUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=[];if(d<p)f.push({amount:0n,reason:"minCollateral"});else{const t=d-BigInt(e.totalDebtUsdWad),r=t<=0n||u<=0n?0n:No(t,10n**BigInt(n),u),o=e=>c+Yo(l+Sa("borrow",e,n,i),i,u,"ceil");f.push({amount:0n===r?0n:Na(r+16n,(e=>o(e)<=d)),reason:"ltv"})}f.push({amount:qa($o(t.borrowCap,"borrowCap")-o.spokeBorrowedBase),reason:"cap"});const h=Mo(o.suppliedBase,200n,Uo);f.push({amount:qa(o.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const n=Zo(e.suppliedBase,t);return 0n===n?null:Na(qa(No(e.suppliedBase,r,To)-e.borrowedBase)+16n,(o=>sa(Zo(e.borrowedBase+o,t),n)<=r))}(o,n);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=Ta(f);return Ua(g,n,!1,$a(o.suppliedBase,o.borrowedBase+g.amount))}function La(e,t,r){if(t.paused)return Ca("paused");const n=Pa(e.supplies,t);if(!n)return Ca(null);const o=n.decimals,a=Oa(t),s=BigInt(n.scaledRay),i=BigInt(n.indexRay),u=BigInt(n.usdPriceWad),l=BigInt(n.amountBase),c=jo(s,i,o,"halfUp"),d=BigInt(e.totalDebtUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=BigInt(Math.min(n.entryLtvBps,n.entryLiquidationThresholdBps)),h=[];let m=!0;if(d>0n&&f>0n){const t=d>p?d:p,r=p>d?"minCollateral":"healthFactor",a=BigInt(e.ltvWeightedCollateralUsdWad)-BigInt(n.ltvWeightedUsdWad);if(a<t){m=!1;const e=t-a,l=Po(e,Uo,f),d=BigInt(n.gateUsdWad)-l,p=d<=0n?0n:No(d,10n**BigInt(o),u),g=c>0n?c-1n:0n,y=p+16n>g?g:p+16n,w=e=>{const t=_a("supply",e,o,i);return No(Yo(t>=s?0n:s-t,i,u,"floor"),f,Uo)};h.push({amount:Na(y,(t=>w(t)>=e)),reason:r})}}h.push({amount:l,reason:null}),h.push({amount:a.cashBase,reason:"liquidity"});const g=function(e,t){const r=e.maxUtilizationRay;if(null===r||0n===e.borrowedBase)return null;if(0n===r)return 0n;const n=Po(e.borrowedBase,To,r),o=e.suppliedBase<n?0n:e.suppliedBase-n+16n,a=Zo(e.borrowedBase,t);return Na(o>e.suppliedBase?e.suppliedBase:o,(n=>{const o=Zo(e.suppliedBase-n,t);return o>0n&&sa(a,o)<=r}))}(a,o);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=Ta(h),w=m&&y.amount>=l;return Ua(y,o,w,$a(a.suppliedBase-y.amount,a.borrowedBase))}function Da(e){if(e.paused)return Ca("paused");if(e.frozen)return Ca("frozen");const t=e.assetDecimals,r=Oa(e),n={amount:qa($o(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return Ua(n,t,!1,$a(r.suppliedBase+n.amount,r.borrowedBase))}function Fa(e,t,r){if(t.paused)return Ca("paused");const n=Pa(e.borrows,t);if(!n)return Ca(null);const o=n.decimals,a=Oa(t),s=BigInt(n.amountBase),i=void 0===r?null:$o(r,"walletBalance"),u=null!==i&&i<s?{amount:i,reason:"liquidity"}:{amount:s,reason:null};return Ua(u,o,u.amount>=s,$a(a.suppliedBase,qa(a.borrowedBase-u.amount)))}const Wa=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,za=e=>{if("bigint"==typeof e)return e;const t=e.trim();if(!/^-?\d+$/.test(t))throw new Error(`Stellar math: delta amountBase must be an integer string, got "${e}"`);return BigInt(t)};function Va(e,t){const r=[...e.supplies],n=[...e.borrows];for(const e of t){const t="supply"===e.side?r:n,o=t.findIndex((t=>Wa(t,e))),a=-1===o?void 0:t[o],s=za(e.amountBase);let i;if(a){const e={side:a.side,hubId:a.hubId,asset:a.asset,decimals:a.decimals,indexRay:BigInt(a.indexRay),priceWad:BigInt(a.usdPriceWad),entryLtvBps:a.entryLtvBps,entryLiquidationThresholdBps:a.entryLiquidationThresholdBps,entryLiquidationBonusBps:a.entryLiquidationBonusBps,entryLiquidationFeesBps:a.entryLiquidationFeesBps,liveDataUsed:a.liveDataUsed},t=BigInt(a.scaledRay);let r;if(s>=0n)r=t+Sa(e.side,s,e.decimals,e.indexRay);else{const n=-s,o=n>=("supply"===e.side?jo(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:_a(e.side,n,e.decimals,e.indexRay);r=o>=t?0n:t-o}i=0n===r?null:va({...e,scaledRay:r})}else i=s<=0n?null:Ia(Xa(e),s);-1===o?i&&t.push(i):i?t[o]=i:t.splice(o,1)}return ka({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,n,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Xa(e){const t=e.reserve;if(!t)throw new Error(`Stellar math: projectAccountRisk needs \`reserve\` for a new ${e.side} position on ${e.hubId}:${e.asset}`);return{side:e.side,hubId:e.hubId,asset:e.asset,decimals:t.assetDecimals,indexRay:$o("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:na(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function ja(e,t=0n,r=0n){const n=e.assetDecimals,o=e=>e<0n?0n:e,a=o(ra(e.hubPool.suppliedShort,n)+za(t)),s=sa(Zo(o(ra(e.hubPool.borrowedShort,n)+za(r)),n),Zo(a,n)),i=ia(s,e.irm),u=ua(s,i,e.irm.reserveFactorBps);return{utilization:ea(s),utilizationRay:s.toString(),borrowAprRay:i.toString(),supplyAprRay:u.toString(),borrowApr:la(i),supplyApr:la(u),borrowApy:ca(i),supplyApy:ca(u)}}const Ha={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},5:{name:"PoolAlreadyDeployed",message:"Singleton pool, controller, or price aggregator already recorded."},6:{name:"InvalidAsset",message:"Invalid asset address."},7:{name:"AssetsAreTheSame",message:"Same market or token where distinct HubAssetKeys or underlying assets, respectively, are required."},8:{name:"WrongToken",message:"Params.asset_id differs from the market's asset."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},13:{name:"AccountNotInMarket",message:"Caller lacks the account's position NFT, or the account has no metadata."},14:{name:"AmountMustBePositive",message:"The amount must be greater than zero."},16:{name:"InvalidPayments",message:"Payments or route list empty when required, non-empty when forbidden, or over the view limit."},18:{name:"NotSmartContract",message:"Address is not a deployed contract."},24:{name:"AccountNotFound",message:"Account id has no state, or its NFT owner is unresolvable."},25:{name:"AccountModeMismatch",message:"Account mode differs from the call's required mode."},27:{name:"AggregatorNotSet",message:"Swap or price aggregator not configured."},29:{name:"PositionLimitsNotSet",message:"No position limits stored."},30:{name:"PoolNotInitialized",message:"Pool or controller unset, or market params/state missing."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},33:{name:"MathOverflow",message:"Checked arithmetic overflow or failed narrowing conversion."},34:{name:"InternalError",message:"Internal invariant failed. Report it."},36:{name:"InvalidPositionLimits",message:"Supply or borrow limit is zero or above POSITION_LIMIT_MAX (5)."},38:{name:"SpotOnlyNotProductionSafe",message:"Every oracle source reads an unsmoothed spot market."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},40:{name:"TimelockOperationExpired",message:"Scheduled operation's grace period elapsed."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},42:{name:"BlendPoolNotApproved",message:"Blend pool not approved."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},45:{name:"RegistryCapReached",message:"Account already has MAX_DELEGATES (16)."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},47:{name:"BorrowRoundsToZeroShares",message:"Positive borrow mints zero scaled debt shares."},48:{name:"CannotRemoveLastProposer",message:"Revoke would leave no proposer."},49:{name:"WithdrawRoundsToZeroShares",message:"Positive withdrawal burns zero scaled supply shares."},50:{name:"NetSettleRoundsToZeroShares",message:"Positive net settlement burns zero shares."},51:{name:"SupplyRoundsToZeroShares",message:"Positive supply mints zero scaled shares."},52:{name:"RepayRoundsToZeroShares",message:"Positive net repayment burns zero scaled debt shares."},53:{name:"PositionNftNotSet",message:"NFT address unset on a path needing it, such as account creation. Ownership lookup can return #24 instead."},54:{name:"PositionNftAlreadyDeployed",message:"Position-NFT address already recorded."},55:{name:"DivisionByZero",message:"Fixed-point multiply-divide with zero denominator."},100:{name:"InsufficientCollateral",message:"Post-operation LTV-weighted collateral below total debt, or health factor below 1 WAD."},101:{name:"HealthFactorTooHigh",message:"Target has no debt or health factor >= 1 WAD; not liquidatable."},102:{name:"HealthFactorTooLow",message:"Update_account_threshold with has_risks = true ends below 1.05 WAD. A gated liquidation-tuple refresh skips a tuple that fails its hypothetical health-factor check."},104:{name:"NotCollateral",message:"Spoke listing disallows the asset as collateral."},107:{name:"AssetNotBorrowable",message:"Spoke listing disallows borrowing the asset."},109:{name:"PositionLimitExceeded",message:"New slot exceeds the position limit, or a sub-3-decimal supply leg would coexist with another supply slot."},110:{name:"PositionNotFound",message:"Reserved code; no longer emitted."},111:{name:"InvalidPositionMode",message:"Mode is not Multiply, Long, or Short."},112:{name:"InsufficientLiquidity",message:"Market cash below the draw, or the draw breaks the liquidation buffer."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},114:{name:"CannotCleanBadDebt",message:"Account fails the bad-debt gate."},115:{name:"WithdrawLessThanFee",message:"Liquidation protocol fee exceeds the gross withdrawal."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},118:{name:"OptUtilTooHigh",message:"Optimal utilization >= 100%."},119:{name:"InvalidReserveFactor",message:"Reserve factor >= 100%."},120:{name:"DebtPositionNotFound",message:"No debt position for that hub asset."},121:{name:"CollateralPositionNotFound",message:"No supply position for that hub asset."},122:{name:"CannotCloseWithRemainingDebt",message:"Close_position with borrow positions open."},123:{name:"PoolInsolvent",message:"Supplier claims exceed cash plus debt, or zero supply with debt outstanding."},126:{name:"MinBorrowCollateralNotMet",message:"With debt outstanding, LTV-weighted collateral below the USD floor, or a sub-3-decimal supply leg under 2 raw units after floor conversion."},127:{name:"UtilizationAboveMax",message:"Post-operation utilization above max_utilization."},128:{name:"BaseRateNegative",message:"Negative base borrow rate."},129:{name:"SlopeNonMonotonic",message:"Rate slopes do not increase monotonically."},130:{name:"MaxRateBelowBase",message:"Max borrow rate not strictly above base."},131:{name:"MaxBorrowRateTooHigh",message:"Max borrow rate exceeds MAX_BORROW_RATE_RAY (200% APR)."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},133:{name:"SelfLiquidationNotAllowed",message:"SeizeMode::Credit(id) receiver is the liquidated account. Owners may still liquidate their own account."},134:{name:"InvalidLiquidationCurve",message:"Curve bounds fail validation."},135:{name:"FullCloseRequired",message:"Retired; no error site."},201:{name:"InvalidAggregator",message:"Proposed aggregator is not a deployed contract."},204:{name:"InvalidOracleTokenType",message:"Reflector asset given as string; only address or symbol accepted."},205:{name:"UnsafePriceNotAllowed",message:"Two legs disagree beyond tolerance, or only one produced a reading."},206:{name:"PriceFeedStale",message:"Observation exceeds its staleness budget. Timestamps over 60 s ahead are dropped; the error then depends on remaining sources."},208:{name:"BadLastTolerance",message:"Upper ratio outside 10150..12500 (excess over BPS outside 150..2500 bps), or lower ratio is not the required rounded reciprocal."},210:{name:"NoLastPrice",message:"No readable source, or an Aquarius LP read failed (for example, reserves or shares)."},211:{name:"NoAccumulator",message:"Controller has no revenue accumulator."},212:{name:"ReflectorHistoryEmpty",message:"Reflector returns no price history."},216:{name:"OracleNotConfigured",message:"No oracle for the price key, or the response omits a requested asset."},217:{name:"InvalidPrice",message:"Price <= 0, or LP fair-value math non-representable."},218:{name:"InvalidStalenessConfig",message:"Max_stale_seconds out of range or below the source's guaranteed freshness."},219:{name:"TwapInsufficientObservations",message:"Record count zero or below the smoothing minimum, or history too short, too long, or denser than feed resolution."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},222:{name:"InvalidOracleResolution",message:"Reflector resolution below minimum, above max_stale_seconds, or implying a TWAP span above it."},223:{name:"SanityBoundViolated",message:"Price outside the stored sanity band."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."},226:{name:"SanityBandTooWideForSingleSource",message:"Band exceeds the tighter limit for single-source, LP, or dual-source oracles with identical provider trust sets."},227:{name:"SanityBandMustTighten",message:"Set_sanity_band would widen the band. Widen via timelocked ConfigureAssetOracle."},228:{name:"TwapRecordsOutOfRange",message:"Record count above MAX_TWAP_RECORDS (12)."},229:{name:"OracleDepthExceeded",message:"Composition nests deeper than MAX_RESOLUTION_DEPTH (3)."},230:{name:"FactorOutOfBounds",message:"Scaled source's factor price outside its min/max."},231:{name:"SourceCountOutOfRange",message:"Zero or over two sources, or Aquarius LP combined with another source."},232:{name:"IndependenceNotDeclared",message:"Sources violate RequireDisjoint, or AllowShared is empty or not exactly the shared providers."},234:{name:"UnsupportedAquariusPool",message:"Aquarius pool of wrong type, or zero reserve or total shares."},235:{name:"InsufficientAquariusLiquidity",message:"Pool value below min_pool_value_wad."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},310:{name:"SpokeMismatch",message:"Account's spoke differs from the targeted spoke."},311:{name:"SpokeSupplyCapReached",message:"Supply would exceed the spoke supply cap."},312:{name:"SpokeBorrowCapReached",message:"Borrow would exceed the spoke borrow cap."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},319:{name:"SpokeFlagsEpochMismatch",message:"RelaxSpokeAssetFlags epoch is stale or wrong; checked at proposal and execution."},400:{name:"FlashLoanOngoing",message:"Flash loan in progress; re-entrant calls refused."},401:{name:"FlashloanNotEnabled",message:"Market is_flashloanable is false."},402:{name:"InvalidFlashloanRepay",message:"Allowance below principal plus fee, or a pool balance check after payout, callback, or repayment fails."},409:{name:"StrategyFeeExceeds",message:"Strategy fee exceeds the borrowed amount."},412:{name:"InvalidFlashloanReceiver",message:"Receiver not a deployed Wasm contract, or a controller payout targets the controller or pool."},500:{name:"ConvertStepsRequired",message:"Multiply initial payment is neither collateral nor debt asset, with no convert_swap."},501:{name:"RouterOverspend",message:"Controller input balance rose during the swap, or router spent over amount_in."},502:{name:"NoSwapOutput",message:"Swap produced no positive measured output."},503:{name:"CollateralRequired",message:"Flash_position collateral list has no positive minimum. Empty list raises #16."},504:{name:"CollateralMinimumNotMet",message:"Measured deposit below its minimum, or none positive."},505:{name:"FlashPositionClosed",message:"Flash_position ended without supply or positive debt in its debt market."}},Ga=/Error\(Contract,\s*#(\d+)\)/,Ka=/contract:(C[A-Z2-7]{55})[^\n]*?Error\(Contract,\s*#(\d+)\)/g,Za=/\[xoxno-invoked:(C[A-Z2-7]{55})\]/,Ya=/contract:C[A-Z2-7]{55}/;function Ja(e,t){let r;if(t?.contracts?.length)r=((e,t)=>{for(const r of e.matchAll(Ka))if(t.has(r[1]))return Number(r[2]);if(Ya.test(e))return null;const r=e.match(Za),n=e.match(Ga);return r&&t.has(r[1])&&n?Number(n[1]):null})(e,new Set(t.contracts));else{const t=e.match(Ga);r=t?Number(t[1]):null}if(null===r)return null;const n=Ha[r];return n?{code:r,...n}:null}export{Uo as BPS,da as DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD,xa as LIQUIDATION_BUFFER_BPS,To as RAY,Co as RAY_DECIMALS,ur as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,kn as STELLAR_LENDING_TOPICS,S as STELLAR_NETWORKS,B as STELLAR_NETWORK_PASSPHRASE,Xn as STELLAR_ROUTE_MAX_BYTES,xn as SYNTHETIC_EVENT_ORDER_STRIDE,so as StellarAuthPolicyError,jn as StellarRouteVerificationError,qo as WAD,Oo as WAD_DECIMALS,v as XOXNOClient,ka as aggregateAccountRisk,ia as annualBorrowRateRay,mo as assertStellarAuthEntries,_o as assertStellarPreparedTxAuth,Zo as baseToRay,ta as baseToShort,Jo as baseValueWad,ya as buildLiveSnapshot,ko as buildSameTokenRepaySwapSteps,Vt as buildStellarAcceptOwnershipTx,sr as buildStellarAddRewardsTx,Kt as buildStellarApproveBlendPoolTx,he as buildStellarBorrowBatchTx,me as buildStellarBorrowTx,xo as buildStellarCctpForwardTx,ar as buildStellarClaimRevenueTx,nr as buildStellarCreateLiquidityPoolTx,rn as buildStellarExecuteCancellerResetTx,to as buildStellarExecuteStrategyTx,Re as buildStellarFlashLoanTx,sn as buildStellarGovernanceAddSpokeImmediateTx,an as buildStellarGovernanceCreateHubImmediateTx,Kr as buildStellarGovernanceExecuteGovernanceUpgradeTx,Yr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,Jr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,Qr as buildStellarGovernanceExecuteTransferGovOwnTx,Gr as buildStellarGovernanceExecuteTx,Zr as buildStellarGovernanceExecuteUpdateDelayTx,ln as buildStellarGovernancePauseTx,un as buildStellarGovernanceRevokeRoleImmediateTx,on as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,nn as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ft as buildStellarGrantRoleTx,Tn as buildStellarLendingIdentifier,ve as buildStellarLiquidateTx,_e as buildStellarLiquidationEstimateTx,Ee as buildStellarMigrateFromBlendTx,Mt as buildStellarMigrateTx,ke as buildStellarMultiplyTx,Lt as buildStellarPauseTx,Br as buildStellarProposeAddAssetToSpokeTx,_r as buildStellarProposeAddSpokeTx,Ur as buildStellarProposeApproveBlendPoolTx,Tr as buildStellarProposeApproveTokenTx,tn as buildStellarProposeCancellerResetTx,Fr as buildStellarProposeConfigureAssetOracleTx,Sr as buildStellarProposeCreateHubTx,Or as buildStellarProposeCreateLiquidityPoolTx,Nr as buildStellarProposeDeployPoolTx,Rr as buildStellarProposeEditAssetInSpokeTx,Wr as buildStellarProposeEditOracleToleranceTx,zr as buildStellarProposeGovernanceUpgradeTx,Xr as buildStellarProposeGrantGovernanceRoleTx,Lr as buildStellarProposeMigrateControllerTx,Er as buildStellarProposeRemoveAssetFromSpokeTx,Ir as buildStellarProposeRemoveSpokeTx,Cr as buildStellarProposeRevokeBlendPoolTx,jr as buildStellarProposeRevokeGovernanceRoleTx,qr as buildStellarProposeRevokeTokenTx,br as buildStellarProposeSetAccumulatorTx,xr as buildStellarProposeSetMinBorrowCollatTx,vr as buildStellarProposeSetPositionLimitsTx,Ar as buildStellarProposeSetPositionManagerTx,wr as buildStellarProposeSetPriceAggregatorTx,kr as buildStellarProposeSetSpokeLiquidationCurveTx,yr as buildStellarProposeSetSwapAggregatorTx,Dr as buildStellarProposeTransferCtrlOwnershipTx,Hr as buildStellarProposeTransferGovOwnTx,cn as buildStellarProposeUnpauseTx,Vr as buildStellarProposeUpdateDelayTx,Mr as buildStellarProposeUpgradeControllerTx,$r as buildStellarProposeUpgradePoolParamsTx,Pr as buildStellarProposeUpgradePoolTx,rr as buildStellarRenewAccountTx,we as buildStellarRepayBatchTx,Te as buildStellarRepayDebtWithCollateralTx,be as buildStellarRepayTx,Zt as buildStellarRevokeBlendPoolTx,Wt as buildStellarRevokeRoleTx,Ht as buildStellarSetAccumulatorTx,er as buildStellarSetOracleSanityBoundsTx,Jt as buildStellarSetOracleToleranceTx,Yt as buildStellarSetOracleTx,Gt as buildStellarSetPositionLimitsTx,jt as buildStellarSetPriceAggregatorTx,Qt as buildStellarSetSpokeAssetFlagsTx,Xt as buildStellarSetSwapAggregatorTx,pe as buildStellarSupplyBatchTx,fe as buildStellarSupplyTx,xe as buildStellarSwapCollateralTx,Ae as buildStellarSwapDebtTx,zt as buildStellarTransferOwnershipTx,Dt as buildStellarUnpauseTx,ir as buildStellarUpdateAccountThresholdTx,tr as buildStellarUpdateIndexesTx,Pt as buildStellarUpgradeControllerTx,or as buildStellarUpgradeLiquidityPoolParamsTx,ge as buildStellarWithdrawBatchTx,ye as buildStellarWithdrawTx,ce as buildTx,_a as burnShares,Aa as computeAccountRisk,An as decodeStellarLendingEvent,Se as decodeStellarLiquidateReturn,Be as decodeStellarLiquidationEstimate,Zn as decodeStellarRouteBytes,ao as decodeStellarSwapEnvelope,ua as depositRateRay,Lo as divByIntHalfUp,Nt as encodeAssetOracle,Rt as encodeInterestRateModel,Et as encodeMarketParamsRaw,kt as encodePositionLimits,At as encodePriceKey,eo as encodeStrategyPayloadToRouteXdr,qn as extractEventOrder,Xe as getStellarAccountPositions,gt as getStellarActiveUsersSeries,$n as getStellarAggregatorQuote,Fe as getStellarAsset,Qe as getStellarAssetGraph,Ke as getStellarAssetMarkets,Ge as getStellarAssetPage,Ne as getStellarAssets,ct as getStellarCampaignLeaderboard,_t as getStellarCampaignMe,wt as getStellarDefiLlamaDimensions,I as getStellarDeployment,$e as getStellarDetailedMarkets,ft as getStellarFeeRevenueSeries,at as getStellarGovernanceProposals,lt as getStellarHolderDistribution,We as getStellarHub,et as getStellarHubGraph,Ye as getStellarHubHolders,Pe as getStellarHubs,Ce as getStellarLendingContext,Oe as getStellarLendingLiveState,ut as getStellarLiquidationsLeaderboard,ht as getStellarLiquidationsSeries,it as getStellarParticipantCounts,St as getStellarPnlByScope,st as getStellarPositionsLeaderboard,vt as getStellarPositionsPnl,Nn as getStellarQuoteTokens,yt as getStellarRateSpreadSeries,De as getStellarReserve,rt as getStellarReserveGraph,Ze as getStellarReserveHolders,Le as getStellarReserves,pt as getStellarRevenueSeries,ze as getStellarSpoke,tt as getStellarSpokeGraph,Je as getStellarSpokeHolders,Me as getStellarSpokes,dt as getStellarStatsHistory,nt as getStellarUserActivity,ot as getStellarUserActivityPage,bt as getStellarUserHistory,Ve as getStellarUserPositions,mt as getStellarVolumeSeries,He as getStellarWalletBalance,je as getStellarWalletTokens,ga as liveIndexKey,ro as mapQuoteResponseToStrategyPayload,no as mapQuoteResponseToStrategySwap,Ja as mapSorobanError,Cn as mapStellarPositionActivityType,Ma as maxBorrow,Fa as maxRepay,Da as maxSupply,La as maxWithdraw,Sa as mintShares,Po as mulDivCeil,No as mulDivFloor,Mo as mulDivHalfUp,ra as numberToScaled,na as numberToWad,le as parseStellarTokenAmount,Yo as positionValueWad,Ro as prepareStellarBuiltTx,Bo as prepareStellarTxXdr,Va as projectAccountRisk,ja as projectReserveApy,ca as rayAprToApy,la as rayAprToNumber,ea as rayToNumber,Wo as rescaleCeil,Fo as rescaleFloor,zo as rescaleHalfUp,pa as reserveKey,fa as resolveReserve,vo as stellarAuthPolicyForInvocation,fn as stellarLendingDispatchKey,It as stellarLendingRead,_ as stellarNetworks,Yn as stellarTokenContractId,Un as syntheticEventOrder,Io as tagStellarInvokedContractError,dn as toBase64Xdr,$o as toBigInt,Eo as toStellarPositionMode,jo as unscale,Go as unscaleBorrowCeil,Ko as unscaleHalfUp,Ho as unscaleSupplyFloor,sa as utilizationRay,Ia as valueBasePosition,va as valueScaledPosition,Qn as verifyStellarRouteBytes,Qo as wadToNumber};export const createStellarLendingReadClient=Bt.gm;export const lendingAssetsSchema=Bt.IY;export const lendingPositionsSchema=Bt.Vd;