@xoxno/sdk-js 1.0.228 → 1.0.229

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.cjs.LICENSE.txt */
2
- "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{var e={526(e,t){"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=s(e),i=a[0],l=a[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,i,l)),c=0,d=l>0?i-4:i;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)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===l&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===l&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,a=[],i=16383,s=0,u=n-o;s<u;s+=i)a.push(l(e,s,s+i>u?u:s+i));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+/",i=0;i<64;++i)r[i]=a[i],n[a.charCodeAt(i)]=i;function s(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 l(e,t,n){for(var o,a,i=[],s=t;s<n;s+=3)o=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(r[(a=o)>>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const n=r(526),o=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const i=2147483647;function s(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(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 u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=s(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 l.from(n,t,r);const o=function(e){if(l.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?s(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 l.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),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(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,l.prototype),n}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function m(e,t){if(l.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 G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return j(e).length;default:if(o)return n?-1:G(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 k(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return _(this,t,r);case"latin1":case"binary":return A(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=l.from(t,n)),l.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,i=1,s=e.length,l=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;i=2,s/=2,l/=2,r/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){let n=-1;for(a=r;a<s;a++)if(u(e,a)===u(t,-1===n?0:a-n)){if(-1===n&&(n=a),a-n+1===l)return n*i}else-1!==n&&(a-=a-n),n=-1}else for(r+l>s&&(r=s-l),a=r;a>=0;a--){let r=!0;for(let n=0;n<l;n++)if(u(e,a+n)!==u(t,n)){r=!1;break}if(r)return a}return-1}function S(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 i;for(n>a/2&&(n=a/2),i=0;i<n;++i){const n=parseInt(t.substr(2*i,2),16);if(Z(n))return i;e[r+i]=n}return i}function v(e,t,r,n){return H(G(t,e.length-r),e,r,n)}function I(e,t,r,n){return H(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 x(e,t,r,n){return H(j(t),e,r,n)}function T(e,t,r,n){return H(function(e,t){let r,n,o;const a=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)r=e.charCodeAt(i),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 B(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o<r;){const t=e[o];let a=null,i=t>239?4:t>223?3:t>191?2:1;if(o+i<=r){let r,n,s,l;switch(i){case 1:t<128&&(a=t);break;case 2:r=e[o+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(l=(15&t)<<12|(63&r)<<6|63&n,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(l=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),o+=i}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=E));return r}(n)}l.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}}(),l.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(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?s(e):void 0!==t?"string"==typeof r?s(e).fill(t,r):s(e).fill(t):s(e)}(e,t,r)},l.allocUnsafe=function(e){return d(e)},l.allocUnsafeSlow=function(e){return d(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.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},l.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}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=l.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?(l.isBuffer(t)||(t=l.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},l.byteLength=m,l.prototype._isBuffer=!0,l.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},l.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},l.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},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?B(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.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&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,r,n,o){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.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),i=(r>>>=0)-(t>>>=0);const s=Math.min(a,i),u=this.slice(n,o),c=e.slice(t,r);for(let e=0;e<s;++e)if(u[e]!==c[e]){a=u[e],i=c[e];break}return a<i?-1:i<a?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.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 S(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return I(this,e,t,r);case"base64":return x(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function _(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 A(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 k(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 P(e,t,r,n,o,a){if(!l.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){F(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 i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,r}function C(e,t,r,n,o){F(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 i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=i,i>>=8,e[r+2]=i,i>>=8,e[r+1]=i,i>>=8,e[r]=i,r+8}function $(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 L(e,t,r,n,a){return t=+t,r>>>=0,a||$(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function N(e,t,r,n,a){return t=+t,r>>>=0,a||$(e,0,r,8),o.write(e,t,r,n,52,8),r+8}l.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,l.prototype),n},l.prototype.readUintLE=l.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},l.prototype.readUintBE=l.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},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.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]},l.prototype.readUint32BE=l.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])},l.prototype.readBigUInt64LE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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))})),l.prototype.readBigUInt64BE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.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},l.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},l.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.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},l.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},l.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},l.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]},l.prototype.readBigInt64LE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.prototype.readBigInt64BE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(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},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(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},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=J((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=J((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=0,a=1,i=0;for(this[t]=255&e;++o<r&&(a*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/a|0)-i&255;return t+r},l.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=r-1,a=1,i=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/a|0)-i&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=J((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=J((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return N(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return N(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,n){if(!l.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},l.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&&!l.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=l.isBuffer(e)?e:l.from(e,n),i=a.length;if(0===i)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=a[o%i]}return this};const M={};function D(e,t,r){M[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 W(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 F(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 M.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||z(t,e.length-(r+1))}(n,o,a)}function V(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function z(e,t,r){if(Math.floor(e)!==e)throw V(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.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=W(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=W(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function G(e,t){let r;t=t||1/0;const n=e.length;let o=null;const a=[];for(let i=0;i<n;++i){if(r=e.charCodeAt(i),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+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 j(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 H(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,i,s=8*o-n-1,l=(1<<s)-1,u=l>>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+=s;c>0;a=256*a+e[t+d],d+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+e[t+d],d+=p,c-=8);if(0===a)a=1-u;else{if(a===l)return i?NaN:1/0*(f?-1:1);i+=Math.pow(2,n),a-=u}return(f?-1:1)*i*Math.pow(2,a-n)},t.write=function(e,t,r,n,o,a){var i,s,l,u=8*a-o-1,c=(1<<u)-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?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-i))<1&&(i--,l*=2),(t+=i+d>=1?p/l:p*Math.pow(2,1-d))*l>=2&&(i++,l/=2),i+d>=c?(s=0,i=c):i+d>=1?(s=(t*l-1)*Math.pow(2,o),i+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),i=0));o>=8;e[r+f]=255&s,f+=h,s/=256,o-=8);for(i=i<<o|s,u+=o;u>0;e[r+f]=255&i,f+=h,i/=256,u-=8);e[r+f-h]|=128*m}},468(e,t,r){"use strict";r.d(t,{createStellarLendingReadClient:()=>b,lendingAssetsSchema:()=>y,lendingPositionsSchema:()=>g});const n={type:"string"},o={type:"number"},a={type:"boolean"},i={...n,nullable:!0},s={...o,nullable:!0},l={...n,enum:["mainnet","testnet"]},u={...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:s,logoUrl:i},p=c({valid:a,stale:a,deviation:a,timestamp:s}),f=c({...d,hubId:o,hubName:n,amountRaw:{...i,description:"Integer token base units, never scaled shares."},amount:i,apy:{...s,description:"Fraction: 0.05 means 5%."},priceUsd:s,valueUsd:s,priceStatus:p,indexRay:i,indexedAt:o,indexedLedger:o}),h=c({amountRaw:i,amount:i,usd:s}),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:l,spokeId:s,spokeName:i,supplied:{type:"array",items:f},borrow:{type:"array",items:f},hasDebt:{...a,nullable:!0,description:"Null when account rows are unavailable."},healthFactor:{...s,description:"Null without debt or when risk inputs are unavailable."},borrowLimitUsd:s,availableBorrowUsd:{...s,description:"Account headroom, before per-market constraints."},netApy:{...s,description:"Net annual yield divided by positive net equity; fraction."},dataStatus:u})},y={type:"array",items:c({...d,hubId:o,hubName:n,network:l,supplyApy:{...s,description:"Fraction: 0.05 means 5%."},borrowApy:{...s,description:"Fraction: 0.05 means 5%."},priceUsd:s,priceStatus:p,spokes:{type:"array",items:m},dataStatus:u,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,i=!1;for(const e of o[2].matchAll(/;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\.)*)"|([\w!#$%&'*+.^`|~:/-]+))\s*/g))if("rel"===e[1].toLowerCase()){if(i)throw new Error("Duplicate pagination link relation");i=!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 i=new Set,s=[];for(;;){if(i.has(a.href))throw new Error("Pagination Link cycle");i.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");s.push(...t);const l=w(e.headers.get("Link"));if(!l)break;const u=new URL(l,a);if(u.origin!==o.origin||u.pathname!==o.pathname||u.username||u.password||u.hash)throw new Error("Pagination Link must stay on the same API endpoint");a=u}return s}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)}}}},387(e,t,r){"use strict";r.d(t,{GW:()=>a});var n,o=r(564);!function(e){e.MAINNET="1",e.DEVNET="D"}(n||(n={}));class a{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=n.MAINNET,apiUrl:r,...a}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=a,this.config=t==n.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:o.s0,FM_SC:o.ZZ,DR_SC:o.sM,KG_SC:o.KL,Staking_SC:o.V,Manager_SC:o.Rh,P2P_SC:o.EP}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:o.cM,FM_SC:o.ZZ,DR_SC:o.sM,KG_SC:o.KL,Staking_SC:o.J6,Manager_SC:o.Ff,P2P_SC:o.gx}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:n,cache:o,debug:a,timeout:i,...s}=this.init,{next:l,cache:u,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("&"),S=`${this.apiUrl}${e}${b.length?`?${b}`:""}`,{revalidate:v,...I}=n??{},{revalidate:x,...T}=l??{},R="GET"!==f||g?void 0:x??v,B="GET"!==f||g||R?void 0:u??o,E=h.body,_=d??i??(null==E?3e4:0),A=_>0?AbortSignal.timeout(_):void 0,k=h.signal??s.signal,q=A&&k?AbortSignal.any([k,A]):A??k,U={...s,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:B,next:{...I,...T,revalidate:R}};(c??a)&&console.debug("SDK fetch: ",S,U);const P=await fetch(S,U).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${S}: ${e.message}`),{cause:e});throw e})),O=await P.text();if(!P.ok){let e;try{e=JSON.parse(O)}catch{e={message:O}}const t=[S,P.status,P.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(O)}catch{return O}}}},564(e,t,r){"use strict";r.d(t,{EP:()=>u,Ff:()=>p,J6:()=>d,KL:()=>i,Rh:()=>l,V:()=>s,ZZ:()=>o,cM:()=>c,gx:()=>f,s0:()=>n,sM:()=>a});const n="erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",o="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",a="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",i="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e",s="erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",l="erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",u="erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6",c="erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",d="erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",p="erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",f="erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";r.r(n),r.d(n,{BPS:()=>bo,DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD:()=>Jo,LIQUIDATION_BUFFER_BPS:()=>ga,RAY:()=>yo,RAY_DECIMALS:()=>So,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Ft,STELLAR_LENDING_TOPICS:()=>fn,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_ROUTE_MAX_BYTES:()=>qn,SYNTHETIC_EVENT_ORDER_STRIDE:()=>mn,StellarAuthPolicyError:()=>jn,StellarRouteVerificationError:()=>Un,WAD:()=>wo,WAD_DECIMALS:()=>vo,XOXNOClient:()=>e.GW,aggregateAccountRisk:()=>ha,annualBorrowRateRay:()=>Ho,assertStellarAuthEntries:()=>to,assertStellarPreparedTxAuth:()=>lo,baseToRay:()=>Lo,baseToShort:()=>Fo,baseValueWad:()=>Mo,buildLiveSnapshot:()=>oa,buildSameTokenRepaySwapSteps:()=>ho,buildStellarAcceptOwnershipTx:()=>Tt,buildStellarAddRewardsTx:()=>Dt,buildStellarApproveBlendPoolTx:()=>At,buildStellarBorrowBatchTx:()=>J,buildStellarBorrowTx:()=>Q,buildStellarCctpForwardTx:()=>go,buildStellarClaimRevenueTx:()=>Mt,buildStellarCreateLiquidityPoolTx:()=>Lt,buildStellarExecuteCancellerResetTx:()=>Fr,buildStellarExecuteStrategyTx:()=>Fn,buildStellarFlashLoanTx:()=>ie,buildStellarGovernanceAddSpokeImmediateTx:()=>Gr,buildStellarGovernanceCreateHubImmediateTx:()=>Xr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>Cr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Lr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Nr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Mr,buildStellarGovernanceExecuteTx:()=>Or,buildStellarGovernanceExecuteUpdateDelayTx:()=>$r,buildStellarGovernancePauseTx:()=>Hr,buildStellarGovernanceRevokeRoleImmediateTx:()=>jr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>zr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Vr,buildStellarGrantRoleTx:()=>vt,buildStellarLendingIdentifier:()=>gn,buildStellarLiquidateTx:()=>oe,buildStellarMigrateFromBlendTx:()=>se,buildStellarMigrateTx:()=>wt,buildStellarMultiplyTx:()=>le,buildStellarPauseTx:()=>bt,buildStellarProposeAddAssetToSpokeTx:()=>cr,buildStellarProposeAddSpokeTx:()=>lr,buildStellarProposeApproveBlendPoolTx:()=>wr,buildStellarProposeApproveTokenTx:()=>gr,buildStellarProposeCancellerResetTx:()=>Wr,buildStellarProposeConfigureAssetOracleTx:()=>Er,buildStellarProposeCreateHubTx:()=>sr,buildStellarProposeCreateLiquidityPoolTx:()=>Sr,buildStellarProposeDeployPoolTx:()=>Ir,buildStellarProposeEditAssetInSpokeTx:()=>dr,buildStellarProposeEditOracleToleranceTx:()=>_r,buildStellarProposeGovernanceUpgradeTx:()=>Ar,buildStellarProposeGrantGovernanceRoleTx:()=>qr,buildStellarProposeMigrateControllerTx:()=>Rr,buildStellarProposeRemoveAssetFromSpokeTx:()=>pr,buildStellarProposeRemoveSpokeTx:()=>ur,buildStellarProposeRevokeBlendPoolTx:()=>br,buildStellarProposeRevokeGovernanceRoleTx:()=>Ur,buildStellarProposeRevokeTokenTx:()=>yr,buildStellarProposeSetAccumulatorTx:()=>ar,buildStellarProposeSetMinBorrowCollatTx:()=>mr,buildStellarProposeSetPositionLimitsTx:()=>ir,buildStellarProposeSetPositionManagerTx:()=>hr,buildStellarProposeSetPriceAggregatorTx:()=>or,buildStellarProposeSetSpokeLiquidationCurveTx:()=>fr,buildStellarProposeSetSwapAggregatorTx:()=>nr,buildStellarProposeTransferCtrlOwnershipTx:()=>Br,buildStellarProposeTransferGovOwnTx:()=>Pr,buildStellarProposeUnpauseTx:()=>Kr,buildStellarProposeUpdateDelayTx:()=>kr,buildStellarProposeUpgradeControllerTx:()=>Tr,buildStellarProposeUpgradePoolParamsTx:()=>vr,buildStellarProposeUpgradePoolTx:()=>xr,buildStellarRenewAccountTx:()=>$t,buildStellarRepayBatchTx:()=>re,buildStellarRepayDebtWithCollateralTx:()=>de,buildStellarRepayTx:()=>ne,buildStellarRevokeBlendPoolTx:()=>kt,buildStellarRevokeRoleTx:()=>It,buildStellarSetAccumulatorTx:()=>Et,buildStellarSetOracleSanityBoundsTx:()=>Ot,buildStellarSetOracleToleranceTx:()=>Ut,buildStellarSetOracleTx:()=>qt,buildStellarSetPositionLimitsTx:()=>_t,buildStellarSetPriceAggregatorTx:()=>Bt,buildStellarSetSpokeAssetFlagsTx:()=>Pt,buildStellarSetSwapAggregatorTx:()=>Rt,buildStellarSupplyBatchTx:()=>Z,buildStellarSupplyTx:()=>Y,buildStellarSwapCollateralTx:()=>ce,buildStellarSwapDebtTx:()=>ue,buildStellarTransferOwnershipTx:()=>xt,buildStellarUnpauseTx:()=>St,buildStellarUpdateAccountThresholdTx:()=>Wt,buildStellarUpdateIndexesTx:()=>Ct,buildStellarUpgradeControllerTx:()=>yt,buildStellarUpgradeLiquidityPoolParamsTx:()=>Nt,buildStellarWithdrawBatchTx:()=>ee,buildStellarWithdrawTx:()=>te,buildTx:()=>H,burnShares:()=>ua,computeAccountRisk:()=>ma,createStellarLendingReadClient:()=>ot.createStellarLendingReadClient,decodeStellarLendingEvent:()=>hn,decodeStellarLiquidateReturn:()=>ae,decodeStellarRouteBytes:()=>$n,decodeStellarSwapEnvelope:()=>Gn,depositRateRay:()=>Ko,divByIntHalfUp:()=>Bo,encodeAssetOracle:()=>gt,encodeInterestRateModel:()=>at,encodeMarketParamsRaw:()=>it,encodePositionLimits:()=>st,encodePriceKey:()=>lt,encodeStrategyPayloadToRouteXdr:()=>Wn,extractEventOrder:()=>yn,getStellarAccountPositions:()=>Be,getStellarActiveUsersSeries:()=>Ze,getStellarAggregatorQuote:()=>vn,getStellarAsset:()=>Ie,getStellarAssetGraph:()=>Pe,getStellarAssetMarkets:()=>Ae,getStellarAssetPage:()=>_e,getStellarAssets:()=>ye,getStellarCampaignLeaderboard:()=>ze,getStellarCampaignMe:()=>rt,getStellarDefiLlamaDimensions:()=>Je,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>ge,getStellarFeeRevenueSeries:()=>je,getStellarGovernanceProposals:()=>Me,getStellarHolderDistribution:()=>Ve,getStellarHub:()=>xe,getStellarHubGraph:()=>Oe,getStellarHubHolders:()=>qe,getStellarHubs:()=>we,getStellarLendingContext:()=>he,getStellarLendingLiveState:()=>me,getStellarLiquidationsLeaderboard:()=>Fe,getStellarLiquidationsSeries:()=>He,getStellarParticipantCounts:()=>We,getStellarPnlByScope:()=>tt,getStellarPositionsLeaderboard:()=>De,getStellarPositionsPnl:()=>et,getStellarQuoteTokens:()=>In,getStellarRateSpreadSeries:()=>Ye,getStellarReserve:()=>ve,getStellarReserveGraph:()=>$e,getStellarReserveHolders:()=>ke,getStellarReserves:()=>Se,getStellarRevenueSeries:()=>Ge,getStellarSpoke:()=>Te,getStellarSpokeGraph:()=>Ce,getStellarSpokeHolders:()=>Ue,getStellarSpokes:()=>be,getStellarStatsHistory:()=>Xe,getStellarUserActivity:()=>Le,getStellarUserActivityPage:()=>Ne,getStellarUserHistory:()=>Qe,getStellarUserPositions:()=>Re,getStellarVolumeSeries:()=>Ke,getStellarWalletBalance:()=>Ee,lendingAssetsSchema:()=>ot.lendingAssetsSchema,lendingPositionsSchema:()=>ot.lendingPositionsSchema,liveIndexKey:()=>na,mapQuoteResponseToStrategyPayload:()=>Vn,mapQuoteResponseToStrategySwap:()=>zn,mapSorobanError:()=>$a,mapStellarPositionActivityType:()=>bn,maxBorrow:()=>Ba,maxRepay:()=>Aa,maxSupply:()=>_a,maxWithdraw:()=>Ea,mintShares:()=>la,mulDivCeil:()=>To,mulDivFloor:()=>xo,mulDivHalfUp:()=>Ro,numberToScaled:()=>Vo,numberToWad:()=>zo,parseStellarTokenAmount:()=>j,positionValueWad:()=>No,prepareStellarBuiltTx:()=>po,prepareStellarTxXdr:()=>co,projectAccountRisk:()=>Ua,projectReserveApy:()=>Oa,rayAprToApy:()=>Yo,rayAprToNumber:()=>Zo,rayToNumber:()=>Wo,rescaleCeil:()=>Ao,rescaleFloor:()=>_o,rescaleHalfUp:()=>ko,reserveKey:()=>Qo,resolveReserve:()=>ea,stellarAuthPolicyForInvocation:()=>io,stellarLendingDispatchKey:()=>Jr,stellarLendingRead:()=>nt,stellarNetworks:()=>o,stellarTokenContractId:()=>Ln,syntheticEventOrder:()=>wn,tagStellarInvokedContractError:()=>uo,toBase64Xdr:()=>Zr,toBigInt:()=>Io,toStellarPositionMode:()=>fo,unscale:()=>Po,unscaleBorrowCeil:()=>Co,unscaleHalfUp:()=>$o,unscaleSupplyFloor:()=>Oo,utilizationRay:()=>jo,valueBasePosition:()=>ca,valueScaledPosition:()=>sa,verifyStellarRouteBytes:()=>Mn,wadToNumber:()=>Do});var e=r(387);const t={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:"CAALOOTIDXCX7D7FMQIBSSAJLPKOM3GMXS4UUSTDIG42JCRRJHOPUHOP",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},o=t;function a(e){return t["testnet"===e?"stellarTestnet":"stellarMainnet"]}const i={mainnet:t.stellarMainnet.passphrase,testnet:t.stellarTestnet.passphrase},s=require("@stellar/stellar-sdk");var l=r(287);const u=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],c={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},d=1,p=1e6,f=5,h=6,m=0,g=1,y=2,w=128,b=48,S=32,v=256,I=w-y,x=e=>new s.Address(e).toScVal(),T=e=>new s.ScInt(e).toI128(),R=e=>s.xdr.ScVal.scvU32(e),B=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.ScInt("string"==typeof e?e:e.toString()).toU64()},E=e=>s.xdr.ScVal.scvBool(e),_=e=>s.xdr.ScVal.scvString(e),A=e=>s.xdr.ScVal.scvSymbol(e),k=()=>s.xdr.ScVal.scvVoid(),q=e=>s.xdr.ScVal.scvVec(e),U=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,n=l.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 s.xdr.ScVal.scvBytes(n)},P=(e,t)=>null==e?k():t(e),O=e=>s.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,s.xdr.ScVal.scvVec([x(t),T(r)]);var t,r}))),C=(e,t)=>M({asset:x(t),hub_id:R(e)}),$=(e,t,r)=>s.xdr.ScVal.scvVec([C(e,t),T(r)]),L=e=>s.xdr.ScVal.scvVec(e.map((e=>$(e.hubId,e.asset,e.amount)))),N=e=>{if("Transfer"===e)return q([A("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 q([A("Credit"),B(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},M=e=>{const t=Object.keys(e).sort().map((t=>new s.xdr.ScMapEntry({key:A(t),val:e[t]})));return s.xdr.ScVal.scvMap(t)};class D{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>=v)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>=I)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>=S)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>p)throw new Error(`Stellar builder: split weight ${e} outside 1..=${p}`);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(c[r.venue],0===n?t:g,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>p)throw new Error(`Stellar builder: split weights for one token sum to ${a}, above ${p}`);const i=a===p;let s=p;o.forEach(((e,n)=>{r[e]=!0;const a=t[e];let l;if(n+1===o.length&&i)l=m;else{if(0===s)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(a.splitPpm*p/s);s-=Math.min(a.splitPpm,s),l=w+this.weight(e)}this.emitPath(a,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>b)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts ${b}`);const n=[d,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 l.hp.from(n)}get assetList(){return this.assets}get amountList(){return this.amounts}}const W=e=>{const t=new D(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(f,m,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,[i,s]=e.preSwapFromA?[o,a]:[a,o];t.emit(c.Aquarius,y+t.amount(r),t.asset(e.mintPool),t.asset(i),t.asset(s))}t.emit(h,m,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 M({amounts:s.xdr.ScVal.scvVec(t.amountList.map((e=>T(e)))),assets:s.xdr.ScVal.scvVec(t.assetList.map((e=>x(e)))),ops:s.xdr.ScVal.scvBytes(t.toBytes(r,n,o))})},F=e=>{const t=l.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 s.xdr.ScVal.scvBytes(t)},V=()=>s.xdr.ScVal.scvBytes(l.hp.alloc(0)),z=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 l.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=l.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},X=e=>{if("string"==typeof e)return F(z(e));if(e instanceof Uint8Array)return 0===e.length?V():F(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?F(z(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?F(z(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?F(z(e.bytes)):0===e.bytes.length?V():F(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||!u.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>p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${n}, above ${p}`);if(!t.mintPool&&n!==p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to ${p}, got ${n}`)}return t})(e),s.xdr.ScVal.scvBytes(l.hp.from(W(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},G=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=l.hp.from(t,"hex");return s.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return s.xdr.ScVal.scvBytes(l.hp.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function j(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.Soroban.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 H(e,t,r){if(!e.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const n=new s.Contract(e.controllerAddress),o=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(n.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function K(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return R(e)}function Z(e,t){const r=t.accountNonce??0;return H(e,"supply",[x(e.caller),B(r),K(t.spokeId),L([...t.assets])])}function Y(e,t){return Z(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function J(e,t){return H(e,"borrow",[x(e.caller),B(t.accountNonce),L([...t.borrows]),P(t.to,x)])}function Q(e,t){return J(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function ee(e,t){return H(e,"withdraw",[x(e.caller),B(t.accountNonce),L([...t.withdrawals]),P(t.to,x)])}function te(e,t){return ee(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function re(e,t){return H(e,"repay",[x(e.caller),B(t.accountNonce),L([...t.payments])])}function ne(e,t){return re(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function oe(e,t){return H(e,"liquidate",[x(e.caller),B(t.accountNonce),L([...t.debtPayments]),N(t.seizeMode??"Transfer")])}function ae(e){const t=(0,s.scValToNative)(s.xdr.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 H(e,"flash_loan",[x(e.caller),C(t.hubId,t.asset),T(t.amount),x(t.receiver),G(t.data)])}function se(e,t){return H(e,"migrate_from_blend",[x(e.caller),B(t.accountId),K(t.spokeId),R(t.hubId),x(t.blendPool),q(t.collateralTokens.map(x)),q(t.supplyTokens.map(x)),O(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function le(e,t){const r=t.accountNonce??0;return H(e,"multiply",[x(e.caller),B(r),K(t.spokeId),C(t.collateral.hubId,t.collateral.asset),T(t.debtToFlashLoan),C(t.debt.hubId,t.debt.asset),R(t.mode),X(t.steps),P(t.initialPayment,(e=>$(e.hubId,e.asset,e.amount))),P(t.convertSwap,X)])}function ue(e,t){return H(e,"swap_debt",[x(e.caller),B(t.accountNonce),C(t.existingDebt.hubId,t.existingDebt.asset),T(t.newDebtAmount),C(t.newDebt.hubId,t.newDebt.asset),X(t.steps)])}function ce(e,t){return H(e,"swap_collateral",[x(e.caller),B(t.accountNonce),C(t.current.hubId,t.current.asset),T(t.fromAmount),C(t.newCollateral.hubId,t.newCollateral.asset),X(t.steps)])}function de(e,t){return H(e,"repay_debt_with_collateral",[x(e.caller),B(t.accountNonce),C(t.collateral.hubId,t.collateral.asset),T(t.collateralAmount),C(t.debt.hubId,t.debt.asset),X(t.steps),E(t.closePosition)])}const pe="/stellar-lending",fe=encodeURIComponent,he=(e,t)=>e.fetchWithTimeout(`${pe}/context`,t),me=(e,t)=>e.fetchWithTimeout(`${pe}/live-state`,t),ge=(e,t)=>e.fetchWithTimeout(`${pe}/markets/detailed`,t),ye=(e,t)=>e.fetchWithTimeout(`${pe}/assets`,t),we=(e,t)=>e.fetchWithTimeout(`${pe}/hubs`,t),be=(e,t)=>e.fetchWithTimeout(`${pe}/spokes`,t),Se=(e,t={},r)=>e.fetchWithTimeout(`${pe}/reserves`,{...r,params:{...t}}),ve=(e,t,r,n,o)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}`,o),Ie=(e,t,r)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}`,r),xe=(e,t,r)=>e.fetchWithTimeout(`${pe}/hubs/${t}`,r),Te=(e,t,r)=>e.fetchWithTimeout(`${pe}/spokes/${t}`,r),Re=(e,t,r)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/positions`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${pe}/accounts/${fe(t)}/positions`,r),Ee=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/assets/${fe(r)}/balance`,n),_e=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/page`,{...n,params:{...r}}),Ae=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/markets`,{...n,params:{side:r}}),ke=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}/holders`,{...a,params:{side:o}}),qe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/hubs/${t}/holders`,{...n,params:{side:r}}),Ue=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/spokes/${t}/holders`,{...n,params:{side:r}}),Pe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/graph`,{...n,params:{...r}}),Oe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/hubs/${t}/graph`,{...n,params:{...r}}),Ce=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/spokes/${t}/graph`,{...n,params:{...r}}),$e=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}/graph`,{...a,params:{...o}}),Le=(e,t,r={},n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/activity`,{...n,params:{...r}}),Ne=(e,t,r={},n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/activity/page`,{...n,params:{...r}}),Me=(e,t={},r)=>e.fetchWithTimeout(`${pe}/governance/proposals`,{...r,params:{...t}}),De=(e,t={},r)=>e.fetchWithTimeout(`${pe}/positions`,{...r,params:{...t}}),We=(e,t={},r)=>e.fetchWithTimeout(`${pe}/participants`,{...r,params:{...t}}),Fe=(e,t={},r)=>e.fetchWithTimeout(`${pe}/liquidations/leaderboard`,{...r,params:{...t}}),Ve=(e,t={},r)=>e.fetchWithTimeout(`${pe}/distribution`,{...r,params:{...t}}),ze=(e,t={},r)=>e.fetchWithTimeout(`${pe}/campaign/leaderboard`,{...r,params:{...t}}),Xe=(e,t,r)=>e.fetchWithTimeout(`${pe}/stats/history`,{...r,params:{...t}}),Ge=(e,t,r)=>e.fetchWithTimeout(`${pe}/revenue`,{...r,params:{...t}}),je=(e,t,r)=>e.fetchWithTimeout(`${pe}/revenue/fees`,{...r,params:{...t}}),He=(e,t,r)=>e.fetchWithTimeout(`${pe}/liquidations`,{...r,params:{...t}}),Ke=(e,t,r)=>e.fetchWithTimeout(`${pe}/volume`,{...r,params:{...t}}),Ze=(e,t,r)=>e.fetchWithTimeout(`${pe}/active-users`,{...r,params:{...t}}),Ye=(e,t,r)=>e.fetchWithTimeout(`${pe}/rate-spread`,{...r,params:{...t}}),Je=(e,t,r)=>e.fetchWithTimeout(`${pe}/defillama`,{...r,params:{...t}}),Qe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/history`,{...n,params:{...r}}),et=(e,t,r)=>e.fetchWithTimeout(`${pe}/pnl`,{...r,params:{accountId:t}}),tt=(e,t,r)=>e.fetchWithTimeout(`${pe}/pnl/scope`,{...r,params:{scope:t}}),rt=(e,t,r)=>e.fetchWithTimeout(`${pe}/campaign/me`,{...r,params:{owner:t}}),nt=e=>({context:t=>he(e,t),liveState:t=>me(e,t),marketsDetailed:t=>ge(e,t),assets:t=>ye(e,t),hubs:t=>we(e,t),spokes:t=>be(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?Se(e,t,r):Se(e,{},t),reserve:(t,r,n,o)=>ve(e,t,r,n,o),asset:(t,r)=>Ie(e,t,r),hub:(t,r)=>xe(e,t,r),spoke:(t,r)=>Te(e,t,r),userPositions:(t,r)=>Re(e,t,r),accountPositions:(t,r)=>Be(e,t,r),walletBalance:(t,r,n)=>Ee(e,t,r,n),assetPage:(t,r,n)=>_e(e,t,r,n),assetMarkets:(t,r,n)=>Ae(e,t,r,n),reserveHolders:(t,r,n,o,a)=>ke(e,t,r,n,o,a),hubHolders:(t,r,n)=>qe(e,t,r,n),spokeHolders:(t,r,n)=>Ue(e,t,r,n),assetGraph:(t,r,n)=>Pe(e,t,r,n),hubGraph:(t,r,n)=>Oe(e,t,r,n),spokeGraph:(t,r,n)=>Ce(e,t,r,n),reserveGraph:(t,r,n,o,a)=>$e(e,t,r,n,o,a),userActivity:(t,r={},n)=>Le(e,t,r,n),userActivityPage:(t,r={},n)=>Ne(e,t,r,n),governanceProposals:(t={},r)=>Me(e,t,r),positionsLeaderboard:(t={},r)=>De(e,t,r),participants:(t={},r)=>We(e,t,r),liquidationsLeaderboard:(t={},r)=>Fe(e,t,r),distribution:(t={},r)=>Ve(e,t,r),campaignLeaderboard:(t={},r)=>ze(e,t,r),statsHistory:(t,r)=>Xe(e,t,r),revenue:(t,r)=>Ge(e,t,r),feeRevenue:(t,r)=>je(e,t,r),liquidations:(t,r)=>He(e,t,r),volume:(t,r)=>Ke(e,t,r),activeUsers:(t,r)=>Ze(e,t,r),rateSpread:(t,r)=>Ye(e,t,r),defillama:(t,r)=>Je(e,t,r),userHistory:(t,r,n)=>Qe(e,t,r,n),positionsPnl:(t,r)=>et(e,t,r),pnlByScope:(t,r)=>tt(e,t,r),campaignMe:(t,r)=>rt(e,t,r)});var ot=r(468);const at=e=>M({base_borrow_rate:T(e.baseBorrowRateRay),max_borrow_rate:T(e.maxBorrowRateRay),max_utilization:T(e.maxUtilizationRay),mid_utilization:T(e.midUtilizationRay),optimal_utilization:T(e.optimalUtilizationRay),reserve_factor:R(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),it=e=>M({asset_decimals:R(e.assetDecimals),asset_id:x(e.assetId),base_borrow_rate:T(e.baseBorrowRateRay),flashloan_fee:R(e.flashloanFeeBps),is_flashloanable:E(e.isFlashloanable),max_borrow_rate:T(e.maxBorrowRateRay),max_utilization:T(e.maxUtilizationRay),mid_utilization:T(e.midUtilizationRay),optimal_utilization:T(e.optimalUtilizationRay),reserve_factor:R(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),st=e=>M({max_borrow_positions:R(e.maxBorrowPositions),max_supply_positions:R(e.maxSupplyPositions)}),lt=e=>{if("Token"in e&&e.Token)return q([A("Token"),x(e.Token)]);if("Ref"in e&&e.Ref)return q([A("Ref"),A(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},ut=e=>{if("Stellar"in e)return q([A("Stellar"),x(e.Stellar)]);if("Symbol"in e)return q([A("Symbol"),A(e.Symbol)]);if("String"in e)return q([A("String"),_(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},ct=e=>{if("Spot"===e)return q([A("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return q([A("Twap"),R(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},dt=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return q([A(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},pt=e=>{if("Market"===e||"Fundamental"===e)return q([A(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},ft=e=>{if("Reflector"in e){const t=e.Reflector;return q([A("Reflector"),M({asset:ut(t.asset),contract:x(t.contract),read_mode:ct(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return q([A("MultiFeed"),M({contract:x(t.contract),feed_id:_(t.feedId),kind:dt(t.kind),nature:pt(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},ht=e=>{const t=e;return M({decimals:R(t.decimals),max_stale_seconds:B(t.maxStaleSeconds),provider:ft(t.provider)})},mt=e=>{if("RequireDisjoint"===e)return q([A("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return q([A("AllowShared"),q(t.map((e=>M({contract:x(e.contract),kind:dt(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},gt=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 M({asset_decimals:R(Number(t.assetDecimals)),independence:mt(t.independence),max_price_stale_seconds:B(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:T(String(t.maxSanityPriceWad)),min_sanity_price_wad:T(String(t.minSanityPriceWad)),sources:q(r.map((e=>(e=>{if("Feed"in e)return q([A("Feed"),ht(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return q([A("Scaled"),M({factor:ht(t.factor),max_factor_wad:T(t.maxFactorWad),min_factor_wad:T(t.minFactorWad),quote:lt(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return q([A("LpShare"),M({key_a:lt(t.keyA),key_b:lt(t.keyB),kind:q([A(t.kind||"ConstantProduct")]),pool:x(t.pool),reserve_a_decimals:R(t.reserveADecimals),reserve_b_decimals:R(t.reserveBDecimals),share_decimals:R(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:M({lower_ratio_bps:R(o),upper_ratio_bps:R(n)})})};function yt(e,t){return H(e,"upgrade",[U(t.wasmHash)])}function wt(e,t){return H(e,"migrate",[R(t.newVersion)])}function bt(e){return H(e,"pause",[])}function St(e){return H(e,"unpause",[])}function vt(e,t){return H(e,"grant_role",[x(t.account),A(t.role)])}function It(e,t){return H(e,"revoke_role",[x(t.account),A(t.role)])}function xt(e,t){return H(e,"transfer_ownership",[x(t.newOwner),R(t.liveUntilLedger)])}function Tt(e){return H(e,"accept_ownership",[])}function Rt(e,t){return H(e,"set_swap_aggregator",[x(t.aggregator)])}function Bt(e,t){return H(e,"set_price_aggregator",[x(t.aggregator)])}function Et(e,t){return H(e,"set_accumulator",[x(t.accumulator)])}function _t(e,t){return H(e,"set_position_limits",[st(t)])}function At(e,t){return H(e,"approve_blend_pool",[x(t.pool)])}function kt(e,t){return H(e,"revoke_blend_pool",[x(t.pool)])}function qt(e,t){return H(e,"set_oracle",[lt(t.key),gt(t.oracle)])}function Ut(e,t){const r=t.toleranceBps,n=t.upperRatioBps??1e4+r,o=t.lowerRatioBps??Math.max(1,Math.floor(1e8/n));return H(e,"set_tolerance",[lt(t.key),M({lower_ratio_bps:R(o),upper_ratio_bps:R(n)})])}function Pt(e,t){return H(e,"set_spoke_asset_flags",[R(t.spokeId),C(t.hubId,t.asset),E(t.paused),E(t.frozen),E(t.noSeize)])}function Ot(e,t){return H(e,"set_oracle_sanity_bounds",[x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Ct(e,t){return H(e,"update_indexes",[x(e.caller),q(t.assets.map((e=>C(e.hubId,e.asset))))])}function $t(e,t){return H(e,"renew_account",[x(e.caller),B(t.accountNonce)])}function Lt(e,t){return H(e,"create_liquidity_pool",[R(t.hubId),x(t.asset),it(t.params)])}function Nt(e,t){return H(e,"upgrade_liquidity_pool_params",[C(t.hubId,t.asset),at(t.params)])}function Mt(e,t){return H(e,"claim_revenue",[x(e.caller),q(t.assets.map((e=>C(e.hubId,e.asset))))])}function Dt(e,t){return H(e,"add_rewards",[x(e.caller),L(t.rewards)])}function Wt(e,t){return H(e,"update_account_threshold",[x(e.caller),E(t.hasRisks),q(t.accountNonces.map((e=>B(e))))])}const Ft="00".repeat(32),Vt=e=>{if("string"==typeof e)return U(e);const t=l.hp.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return s.xdr.ScVal.scvBytes(t)},zt=(e,...t)=>q([A(e),...t]),Xt=e=>M({asset:x(e.asset),hub_id:R(e.hubId),params:it(e.params)}),Gt=e=>M({hub_asset:C(e.hubId,e.asset),params:at(e.params)}),jt=e=>M({new_owner:x(e.newOwner),live_until_ledger:R(e.liveUntilLedger)}),Ht=e=>M({key:lt(e.key),oracle:gt(e.oracle)}),Kt=e=>M({asset:x(e.asset),bonus:R(e.bonus),borrow_cap:T(e.borrowCap),can_borrow:E(e.canBorrow),can_collateral:E(e.canCollateral),frozen:E(e.frozen),hub_id:R(e.hubId),paused:E(e.paused),liquidation_fees:R(e.liquidationFees),ltv:R(e.ltv),no_seize:E(e.noSeize),spoke_id:R(e.spokeId),supply_cap:T(e.supplyCap),threshold:R(e.threshold)}),Zt=e=>M({hub_asset:C(e.hubId,e.asset),spoke_id:R(e.spokeId)}),Yt=e=>M({hf_for_max_bonus_wad:T(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:R(e.liquidationBonusFactorBps),spoke_id:R(e.spokeId),target_hf_wad:T(e.targetHfWad)}),Jt=e=>M({key:lt(e.key),tolerance:R(e.tolerance)}),Qt=e=>M({account:x(e.account),role:A(e.role)});function er(e,t,r){if(!e.governanceAddress)throw new Error("Stellar governanceAddress is required");const n=new s.Contract(e.governanceAddress),o=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(n.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const tr=(e,t,r)=>er(e,"propose",[x(e.caller),t,Vt(r)]),rr=(e,t,r)=>er(e,"execute_self",[k(),t,Vt(r)]);function nr(e,t,r){return tr(e,zt("SetSwapAggregator",x(t.aggregator)),r)}function or(e,t,r){return tr(e,zt("SetPriceAggregator",x(t.aggregator)),r)}function ar(e,t,r){return tr(e,zt("SetAccumulator",x(t.accumulator)),r)}function ir(e,t,r){return tr(e,zt("SetPositionLimits",st(t)),r)}function sr(e,t){return tr(e,zt("CreateHub"),t)}function lr(e,t){return tr(e,zt("AddSpoke"),t)}function ur(e,t,r){return tr(e,zt("RemoveSpoke",R(t.spokeId)),r)}function cr(e,t,r){return tr(e,zt("AddAssetToSpoke",Kt(t)),r)}function dr(e,t,r){return tr(e,zt("EditAssetInSpoke",Kt(t)),r)}function pr(e,t,r){return tr(e,zt("RemoveAssetFromSpoke",Zt(t)),r)}function fr(e,t,r){return tr(e,zt("SetSpokeLiquidationCurve",Yt(t)),r)}function hr(e,t,r){return tr(e,zt("SetPositionManager",x(t.manager),E(t.isActive)),r)}function mr(e,t,r){return tr(e,zt("SetMinBorrowCollateralUsd",T(t.floorWad)),r)}function gr(e,t,r){return tr(e,zt("ApproveToken",x(t.token)),r)}function yr(e,t,r){return tr(e,zt("RevokeToken",x(t.token)),r)}function wr(e,t,r){return tr(e,zt("ApproveBlendPool",x(t.pool)),r)}function br(e,t,r){return tr(e,zt("RevokeBlendPool",x(t.pool)),r)}function Sr(e,t,r){return tr(e,zt("CreateLiquidityPool",Xt(t)),r)}function vr(e,t,r){return tr(e,zt("UpgradeLiquidityPoolParams",Gt(t)),r)}function Ir(e,t,r){return tr(e,zt("DeployPool",U(t.wasmHash)),r)}function xr(e,t,r){return tr(e,zt("UpgradePool",U(t.wasmHash)),r)}function Tr(e,t,r){return tr(e,zt("UpgradeController",U(t.wasmHash)),r)}function Rr(e,t,r){return tr(e,zt("MigrateController",R(t.newVersion)),r)}function Br(e,t,r){return tr(e,zt("TransferCtrlOwnership",jt(t)),r)}function Er(e,t,r){return tr(e,zt("ConfigureAssetOracle",Ht(t)),r)}function _r(e,t,r){return tr(e,zt("EditOracleTolerance",Jt(t)),r)}function Ar(e,t,r){return tr(e,zt("UpgradeGov",U(t.wasmHash)),r)}function kr(e,t,r){return tr(e,zt("UpdateGovDelay",R(t.newDelay)),r)}function qr(e,t,r){return tr(e,zt("GrantGovRole",Qt(t)),r)}function Ur(e,t,r){return tr(e,zt("RevokeGovRole",Qt(t)),r)}function Pr(e,t,r){return tr(e,zt("TransferGovOwnership",jt(t)),r)}function Or(e,t){const r=q(t.argsXdr.map((e=>s.xdr.ScVal.fromXDR(e,"base64")))),n=Vt(t.predecessor??Ft);return er(e,"execute",[k(),x(t.target),A(t.functionName),r,n,Vt(t.salt)])}function Cr(e,t,r){return rr(e,zt("UpgradeGov",U(t.wasmHash)),r)}function $r(e,t,r){return rr(e,zt("UpdateGovDelay",R(t.newDelay)),r)}function Lr(e,t,r){return rr(e,zt("GrantGovRole",Qt(t)),r)}function Nr(e,t,r){return rr(e,zt("RevokeGovRole",Qt(t)),r)}function Mr(e,t,r){return rr(e,zt("TransferGovOwnership",jt(t)),r)}const Dr=e=>q(e.map(x));function Wr(e,t,r){return er(e,"propose_canceller_reset",[Dr(t.newCancellers),Vt(r)])}function Fr(e,t,r){return er(e,"execute_canceller_reset",[P(t.executor,x),Dr(t.newCancellers),Vt(r)])}function Vr(e,t){return er(e,"set_spoke_asset_flags",[x(e.caller),R(t.spokeId),C(t.hubId,t.asset),E(t.paused),E(t.frozen),E(t.noSeize)])}function zr(e,t){return er(e,"set_oracle_sanity_bounds",[x(e.caller),x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Xr(e){return er(e,"create_hub",[x(e.caller)])}function Gr(e){return er(e,"add_spoke",[x(e.caller)])}function jr(e,t){return er(e,"revoke_role_immediate",[x(t.account),A(t.role)])}function Hr(e){return er(e,"pause",[x(e.caller)])}function Kr(e,t){return tr(e,zt("Unpause"),t)}const Zr=e=>e.toXDR("base64"),Yr=e=>s.xdr.ScVal.fromXDR(e,"base64"),Jr=e=>e.map((e=>String((0,s.scValToNative)(Yr(e))))).join(":"),Qr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),en=e=>Number(e),tn=e=>String(e),rn=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),nn=["None","Multiply","Long","Short"],on=["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"],an=e=>Array.isArray(e)?e:[],sn=(e,t)=>{const r="Borrow"===t;return{action:(n=e[0],on[en(n)]??Qr(n)),positionType:t,hubId:en(e[1]),asset:tn(e[2]),scaledAmountRay:Qr(e[3]),indexRay:Qr(e[4]),amount:Qr(e[5]),liquidationThresholdBps:r?void 0:en(e[6]),liquidationBonusBps:r?void 0:en(e[7]),loanToValueBps:r?void 0:en(e[8]),liquidationFeesBps:r?void 0:en(e[9])};var n},ln=e=>{return{owner:tn(e[0]),spokeId:en(e[1]),mode:(t=e[2],nn[en(t)]??"None")};var t},un=e=>Array.isArray(e)?e[1]:void 0,cn=e=>{const t=(r=e,Array.isArray(r)?tn(r[0]):tn(r));var r;if("Token"===t)return{Token:tn(un(e))};if("Ref"===t)return{Ref:tn(un(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:tn(t.Token)};if(void 0!==t.Ref)return{Ref:tn(t.Ref)}}return{Token:tn(e)}},dn=e=>{const t=e.tolerance??{};return{assetDecimals:en(e.asset_decimals),maxPriceStaleSeconds:en(e.max_price_stale_seconds),sources:an(e.sources).map((e=>e)),tolerance:{upperRatio:en(t.upper_ratio_bps),lowerRatio:en(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Qr(e.min_sanity_price_wad),maxSanityPriceWad:Qr(e.max_sanity_price_wad)}},pn={"market:create":e=>({topic:"market:create",data:{hubId:en(e.hub_id),baseAsset:tn(e.base_asset),maxBorrowRate:Qr(e.max_borrow_rate),baseBorrowRate:Qr(e.base_borrow_rate),slope1:Qr(e.slope1),slope2:Qr(e.slope2),slope3:Qr(e.slope3),midUtilization:Qr(e.mid_utilization),optimalUtilization:Qr(e.optimal_utilization),maxUtilization:Qr(e.max_utilization),reserveFactor:en(e.reserve_factor),marketAddress:tn(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:tn(e.asset),maxBorrowRateRay:Qr(e.max_borrow_rate),baseBorrowRateRay:Qr(e.base_borrow_rate),slope1Ray:Qr(e.slope1),slope2Ray:Qr(e.slope2),slope3Ray:Qr(e.slope3),midUtilizationRay:Qr(e.mid_utilization),optimalUtilizationRay:Qr(e.optimal_utilization),maxUtilizationRay:Qr(e.max_utilization),reserveFactorBps:en(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:an(e).map((e=>{return t=an(e),{hubId:en(t[0]),asset:tn(t[1]),timestamp:en(t[2]),supplyIndexRay:Qr(t[3]),borrowIndexRay:Qr(t[4]),cash:Qr(t[5]),suppliedRay:Qr(t[6]),borrowedRay:Qr(t[7]),revenueRay:Qr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:an(e).map((e=>{const t=e;return{hubId:en(t.hub_id),asset:tn(t.asset),params:(r=t.params,{maxBorrowRateRay:Qr(r.max_borrow_rate),baseBorrowRateRay:Qr(r.base_borrow_rate),slope1Ray:Qr(r.slope1),slope2Ray:Qr(r.slope2),slope3Ray:Qr(r.slope3),midUtilizationRay:Qr(r.mid_utilization),optimalUtilizationRay:Qr(r.optimal_utilization),maxUtilizationRay:Qr(r.max_utilization),reserveFactorBps:en(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:en(r.flashloan_fee),assetId:tn(r.asset_id),assetDecimals:en(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=an(e);return{topic:"position:batch_update",data:{accountId:Qr(t[0]),accountAttributes:ln(an(t[1])),updates:[...an(t[2]).map((e=>sn(an(e),"Deposit"))),...an(t[3]).map((e=>sn(an(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:en(e.hub_id),asset:tn(e.asset),receiver:tn(e.receiver),caller:tn(e.caller),amount:Qr(e.amount),fee:Qr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:cn(e.key),oracle:dn(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:tn(e.asset),oracle:dn(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:tn(e.liquidator),accountId:Qr(e.account_id),repaidUsdWad:Qr(e.repaid_usd_wad),bonusBps:Qr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Qr(e.account_id),totalBorrowUsdWad:Qr(e.total_borrow_usd_wad),totalCollateralUsdWad:Qr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:tn(e.token),amount:Qr(e.amount),usdValueWad:Qr(e.usd_value_wad),accountId:Qr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:en(e.hub_id),asset:tn(e.asset),amount:Qr(e.amount),fee:Qr(e.fee),amountSent:Qr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:tn(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:rn(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:tn(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:tn(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:tn(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:tn(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:rn(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:en(e.max_supply_positions),maxBorrowPositions:en(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Qr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:tn(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:en(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Qr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Qr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:en(t.liquidation_bonus_factor_bps)}}}},fn=Object.freeze(Object.keys(pn));function hn(e,t){const r=Jr(e),n=pn[r];return n?n((0,s.scValToNative)(Yr(t))):null}const mn=1e4;function gn(e,t){return`${e}-${BigInt(t).toString(10)}`}function yn(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function wn(e,t=0){return e*mn+t}function bn(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 Sn=(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 vn(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=Sn(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 In(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=Sn(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 xn(e,t){const r=e[t];return"function"==typeof r?r.call(e):r}function Tn(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Rn(e){return Bn(xn(e,"bytes"))}function Bn(e){const t=e;return l.hp.from("value"in t?t.value:t)}const En=10,_n=5,An=3,kn=En+_n*b+An*S,qn=16384;class Un extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const Pn=(e,t)=>{throw new Un(e,t)},On=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*qn)return Pn("OVERSIZED",`encoded route has ${t.length} characters`);try{return Rn(X(e))}catch(e){return Pn("MALFORMED",e instanceof Error?e.message:String(e))}},Cn=e=>{let t;try{t=s.xdr.ScVal.fromXDR(e)}catch(e){return Pn("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==Tn(t))return Pn("MALFORMED","payload must be a StrategyPayload map");const r=xn(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===Tn(xn(e,"key"))?xn(xn(e,"key"),"sym").toString():"")).join(","))return Pn("MALFORMED","payload fields must be exactly amounts, assets, ops");const[n,o,a]=r.map((e=>xn(e,"val")));return"scvVec"!==Tn(n)||"scvVec"!==Tn(o)||"scvBytes"!==Tn(a)?Pn("MALFORMED","payload field has the wrong type"):{amounts:xn(n,"vec")??[],assets:xn(o,"vec")??[],ops:Rn(a)}};function $n(e){const t=On(e);0===t.length&&Pn("MALFORMED","route is empty"),t.length>qn&&Pn("OVERSIZED",`route has ${t.length} bytes, above ${qn}`);const r=Cn(t),n=r.assets.length,o=r.amounts.length;0===n&&Pn("MALFORMED","asset registry is empty"),(n>v||o>I)&&Pn("OVERSIZED",`registries hold ${n} assets and ${o} amounts`);const a=r.assets.map(((e,t)=>"scvAddress"!==Tn(e)?Pn("MALFORMED",`assets[${t}] is not an address`):s.Address.fromScAddress(xn(e,"address")).toString())),i=r.amounts.map(((e,t)=>"scvI128"!==Tn(e)?Pn("MALFORMED",`amounts[${t}] is not an i128`):(0,s.scValToBigInt)(e))),l=r.ops;l.length<En&&Pn("MALFORMED","program header is truncated"),l.length>kn&&Pn("OVERSIZED",`program has ${l.length} bytes, above ${kn}`);const c=e=>{const t=l[e];return void 0===t?Pn("MALFORMED",`program byte ${e} is missing`):t},x=c(0);x!==d&&Pn("UNSUPPORTED_VERSION",`program version ${x}, expected ${d}`);const T=c(8),R=c(9);0===T&&Pn("INVALID_STRUCTURE","program has no instructions"),(T>b||R>S)&&Pn("OVERSIZED",`program declares ${T} instructions and ${R} weights`);const B=En+_n*T;l.length!==B+An*R&&Pn("MALFORMED","program length does not match its instruction and weight counts");const E=c(1),_=c(2),A=c(3);(E>=n||_>=n||A>=o)&&Pn("MALFORMED","header index is outside its registry"),E===_&&Pn("INVALID_STRUCTURE","token_in equals token_out");const k=l.readUInt32BE(4),q=[];for(let e=0;e<R;e+=1){const t=l.readUIntBE(B+An*e,An);(0===t||t>p)&&Pn("INVALID_STRUCTURE",`split weight ${t} outside 1..=${p}`),q.push(t)}const U=e=>a[e]??Pn("MALFORMED",`asset index ${e} is outside the registry`),P=e=>i[e]??Pn("MALFORMED",`amount index ${e} is outside the registry`),O=[];let C;for(let e=0;e<T;e+=1){const t=En+_n*e,r=c(t),n=c(t+1),a=c(t+2),i=c(t+3),s=c(t+4);let l;if(r>h&&Pn("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),n===m)l={kind:"all"};else if(n===g)void 0!==C&&C===i||Pn("INVALID_STRUCTURE",`instruction ${e} does not chain onto its predecessor`),l={kind:"prev"};else if(n>=w){const t=q[n-w];void 0===t&&Pn("MALFORMED",`instruction ${e} weight index is out of range`),l={kind:"ppm",ppm:t}}else l={kind:"fixed",amount:P(n-y)};const d=U(a);r!==f&&r!==h?(i===s&&Pn("INVALID_STRUCTURE",`instruction ${e} swaps a token for itself`),O.push({kind:"swap",venue:u[r],mode:l,pool:d,tokenIn:U(i),tokenOut:U(s)}),C=s):("all"!==l.kind&&Pn("MALFORMED",`liquidity instruction ${e} must use mode All`),s>=o&&Pn("MALFORMED",`instruction ${e} amount index is out of range`),O.push({kind:r===f?"burn":"mint",pool:d,shareToken:U(i),amountIndex:s}),C=r===h?i:void 0)}const $=P(A);return $<=0n&&Pn("MIN_OUT_TOO_LOW",`encoded total_min_out is ${$}`),{version:x,tokenIn:U(E),tokenOut:U(_),totalMinOut:$,referralId:k,assets:a,amounts:i,ops:O,weights:q}}function Ln(e,t){if(s.StrKey.isValidContract(e))return e;if(!t)return Pn("EXPECTATION_MISSING",`token ${e} is not a contract id; pass \`network\` to derive its asset contract`);try{const r=e.indexOf(":");return("XLM"===e||"native"===e?s.Asset.native():new s.Asset(e.slice(0,r),e.slice(r+1))).contractId(i[t])}catch{return Pn("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Nn=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):Pn("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function Mn(e,t){const r=Nn(t.minOut,"expected.minOut");r<=0n&&Pn("EXPECTATION_MISSING","expected.minOut must be positive");const n=$n(e);if(n.tokenIn!==t.tokenIn&&Pn("TOKEN_IN_MISMATCH",`route spends ${n.tokenIn}, expected ${t.tokenIn}`),n.tokenOut!==t.tokenOut&&Pn("TOKEN_OUT_MISMATCH",`route delivers ${n.tokenOut}, expected ${t.tokenOut}`),n.totalMinOut<r&&Pn("MIN_OUT_TOO_LOW",`route enforces a minimum of ${n.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Nn(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&&Pn("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return n}const Dn=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Wn=e=>W(e).toXDR("base64");function Fn(e,t){if(!e.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const r=new s.Contract(e.routerAddress),n=new s.Account(e.caller,e.sourceSequence),o=X(Dn(t,e.referralId));return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(r.call("execute_strategy",x(e.caller),T(e.totalIn),o)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function Vn(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(Xn),splitPpm:e.splitPpm}))):[{hops:e.hops.map(Xn),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function zn(e,t={}){const r=t.expected??{},n="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:Vn(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 Un("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 Un("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return Mn(n,{tokenIn:Ln(r.tokenIn??e.from,t.network),tokenOut:Ln(r.tokenOut??e.to,t.network),minOut:o,amountIn:r.amountIn??e.amountIn}),n}const Xn=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Gn(e){try{const{envelopeXdr:t,networkPassphrase:r,routerAddress:n,viewer:o,operationIndex:a}=e;if(!r||!s.StrKey.isValidContract(n)||new s.Address(o).toString()!==o||"string"!=typeof t||t.length>1048576||t.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||void 0!==a&&(!Number.isSafeInteger(a)||a<0))return null;const i=s.TransactionBuilder.fromXDR(t,r),l="innerTransaction"in i?i.innerTransaction:i;if(void 0!==a&&a>=l.operations.length)return null;let u=null;for(const[e,t]of l.operations.entries()){if(void 0!==a&&e!==a)continue;if("invokeHostFunction"!==t.type)continue;const r=t.func;if("hostFunctionTypeInvokeContract"!==Tn(r))continue;const i=xn(r,"invokeContract");if(s.Address.fromScAddress(xn(i,"contractAddress")).toString()!==n||"execute_strategy"!==xn(i,"functionName").toString())continue;const l=xn(i,"args"),[c,d,p]=l;if(3!==l.length||!c||!d||!p||"scvAddress"!==Tn(c)||"scvI128"!==Tn(d)||"scvBytes"!==Tn(p))return null;if(s.Address.fromScAddress(xn(c,"address")).toString()!==o)continue;const f=(0,s.scValToBigInt)(d);if(f<=0n)return null;const h=$n(Rn(p));if(h.tokenIn===h.tokenOut||!s.StrKey.isValidContract(h.tokenIn)||!s.StrKey.isValidContract(h.tokenOut))return null;if(u)return null;u={tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountInAtoms:f.toString(),operationIndex:e}}return u}catch{return null}}class jn 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 Hn=e=>e&&"scvAddress"===Tn(e)?s.Address.fromScAddress(xn(e,"address")).toString():void 0,Kn=e=>e&&"scvI128"===Tn(e)?(0,s.scValToBigInt)(e):void 0,Zn=e=>e&&"scvVec"===Tn(e)?xn(e,"vec")??[]:void 0,Yn=(e,t)=>{if(!e||"scvMap"!==Tn(e))return;const r=(xn(e,"map")??[]).find((e=>"scvSymbol"===Tn(xn(e,"key"))&&xn(xn(e,"key"),"sym").toString()===t));return r?xn(r,"val"):void 0},Jn=e=>Hn(e)??Kn(e)?.toString()??e.toXDR("base64"),Qn=e=>({contract:s.Address.fromScAddress(xn(e,"contractAddress")).toString(),fn:xn(e,"functionName").toString(),args:xn(e,"args").map(Jn)}),eo=e=>{const t=xn(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===Tn(t)?xn(t,"contractFn"):void 0};function to(e,t,r){const n=e.filter((e=>{const n=xn(e,"credentials"),o=Tn(n);if("sorobanCredentialsAddress"!==o&&"sorobanCredentialsSourceAccount"!==o)throw new jn("MALFORMED_TRANSACTION","unsupported authorization credentials");return("sorobanCredentialsAddress"===o?s.Address.fromScAddress(xn(xn(n,"address"),"address")).toString():r??t.caller)===t.caller}));if(n.length>1)throw new jn("DUPLICATE_ENTRY",`${n.length} authorization entries for ${t.caller}, expected one`);const o=n[0];if(!o)return;const a=eo(xn(o,"rootInvocation"));if(!a)throw new jn("UNEXPECTED_ROOT","root is not a contract call");const i=Qn(a);if(i.contract!==t.root.contract||i.fn!==t.root.fn)throw new jn("UNEXPECTED_ROOT",`expected ${t.root.contract}.${t.root.fn}`,i);const l=t.transfers.map((()=>0n)),u=(t.calls??[]).map((()=>0));for(const e of xn(xn(o,"rootInvocation"),"subInvocations")){const r=eo(e);if(!r)throw new jn("UNEXPECTED_CALL","sub-invocation is not a contract call");const n=Qn(r);if(xn(e,"subInvocations").length>0)throw new jn("NESTED_INVOCATION","sub-invocation carries its own sub-invocations",n);const o=(t.calls??[]).findIndex((e=>e.contract===n.contract&&e.fn===n.fn));if(-1!==o){const e=(t.calls??[])[o],a=e.reject(xn(r,"args"));if(a)throw new jn("UNEXPECTED_CALL",a,n);if(u[o]=(u[o]??0)+1,(u[o]??0)>e.maxCount)throw new jn("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,n);continue}if("transfer"!==n.fn||3!==xn(r,"args").length)throw new jn("UNEXPECTED_CALL","only `transfer` is allowed",n);if(!t.transfers.some((e=>e.token===n.contract)))throw new jn("UNEXPECTED_TOKEN","transfer on an unexpected token",n);const[a,i,s]=xn(r,"args");if(Hn(a)!==t.caller)throw new jn("UNEXPECTED_SENDER","transfer is not from the caller",n);const c=Hn(i),d=t.transfers.findIndex((e=>e.token===n.contract&&e.to===c));if(-1===d)throw new jn("UNEXPECTED_RECIPIENT","transfer to an unexpected recipient",n);const p=Kn(s),f=t.transfers[d],h=(l[d]??0n)+(p??0n);if(void 0===p||p<=0n||h>f.maxAmount)throw new jn("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,n);l[d]=h}}const ro=e=>{throw new jn("MALFORMED_TRANSACTION",e)},no=(e,t)=>{const r=new Map;for(const t of Zn(e)??ro("payments argument is not a vector")){const[e,n]=Zn(t)??[],o=Hn(Yn(e,"asset")),a=Kn(n);if(void 0===o||void 0===a||a<0n)return ro("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})))},oo=new Set([1,3,5]),ao=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(Hn(e[0])!==t)return"`from` is not the caller";if(Hn(e[1])!==r||Hn(e[2])!==r)return"`spender` and `to` must be the lending controller";const n=Zn(e[3]);if(!n)return"requests is not a vector";for(const e of n){const t=Yn(e,"request_type");if(!t||"scvU32"!==Tn(t)||!oo.has(xn(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function io(e,t,r){const{contract:n,fn:o}=Qn(t),a=xn(t,"args"),i={caller:e,root:{contract:n,fn:o},transfers:[]};if(n===r.governance)return i;if(n===r.aggregatorRouter){if("execute_strategy"!==o)return i;const t=Kn(a[1]);if(Hn(a[0])!==e||void 0===t||"scvBytes"!==Tn(a[2]))return ro("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=$n(Rn(a[2]));return i.transfers=[{token:r.tokenIn,to:n,maxAmount:t}],i}if(n!==r.lendingController)throw new jn("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${n}; pass an explicit policy`);if(Hn(a[0])!==e)throw new jn("CALLER_MISMATCH",`${o} is not invoked for ${e}`);switch(o){case"supply":i.transfers=no(a[3],r.lendingPool);break;case"repay":case"liquidate":i.transfers=no(a[2],r.lendingPool);break;case"multiply":{const e=a[8];e&&"scvVoid"!==Tn(e)&&(i.transfers=no(s.xdr.ScVal.scvVec([e]),n));break}case"migrate_from_blend":{const t=Hn(a[4])??ro("blend_pool is not an address");i.calls=[ao(t,e,n)];break}}return i}const so=e=>{let t;try{t=s.xdr.TransactionEnvelope.fromXDR(e,"base64")}catch{return ro("not a transaction envelope")}if("envelopeTypeTx"!==Tn(t))return ro("expected a regular (v1) transaction");const r=xn(xn(t,"v1"),"tx"),n=xn(r,"operations")[0];if(!n||1!==xn(r,"operations").length)return ro("expected exactly one operation");const o=xn(n,"body");if("invokeHostFunction"!==Tn(o))return ro("operation is not a contract invocation");const a=xn(o,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==Tn(xn(a,"hostFunction"))?ro("host function is not a contract call"):{source:(i=xn(n,"sourceAccount")??xn(r,"sourceAccount"),s.StrKey.encodeEd25519PublicKey(Bn("keyTypeMuxedEd25519"===Tn(i)?xn(xn(i,"med25519"),"ed25519"):xn(i,"ed25519")))),op:a,call:xn(xn(a,"hostFunction"),"invokeContract")};var i};function lo(e,t){const r=so(e);if(void 0!==t.builtXdr&&xn(so(t.builtXdr).op,"hostFunction").toXDR("base64")!==xn(r.op,"hostFunction").toXDR("base64"))throw new jn("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",Qn(r.call));const n=t.policy??io(t.caller,r.call,{...a(t.network),...t.deployment});to(xn(r.op,"auth"),n,r.source)}function uo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function co(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=s.TransactionBuilder.fromXDR(t,r?.network?i[r.network]:"");try{const t=await e.simulateTransaction(o,{cpuInstructions:n});if(s.rpc.Api.isSimulationError(t))throw new Error(t.error);return s.rpc.assembleTransaction(o,t).build().toXDR()}catch(e){if(r?.invokedContractId)throw uo(r.invokedContractId,e);throw e}}async function po(e,t,r){return co(e,t.xdr,r)}function fo(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 ho(e,t){return new Uint8Array(0)}const mo=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 l.hp.from(t,"hex")};function go(e){const t=new s.Account(e.caller,e.sourceSequence),r=new s.Contract(e.forwarderAddress).call("mint_and_forward",s.xdr.ScVal.scvBytes(mo(e.message)),s.xdr.ScVal.scvBytes(mo(e.attestation)));return{xdr:new s.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const yo=10n**27n,wo=10n**18n,bo=10000n,So=27,vo=18;function Io(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 xo(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function To(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 Ro(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function Bo(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 Eo=e=>10n**BigInt(e);function _o(e,t,r){return t===r?e:r>t?e*Eo(r-t):e/Eo(t-r)}function Ao(e,t,r){if(t===r)return e;if(r>t)return e*Eo(r-t);const n=Eo(t-r),o=e/n;return e%n===0n?o:o+1n}function ko(e,t,r){return t===r?e:r>t?e*Eo(r-t):Bo(e,Eo(t-r))}const qo={floor:xo,ceil:To,halfUp:Ro},Uo={floor:_o,ceil:Ao,halfUp:ko};function Po(e,t,r,n){return Uo[n](qo[n](e,t,yo),So,r)}function Oo(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"floor")}function Co(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"ceil")}function $o(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"halfUp")}function Lo(e,t){if(t>So)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return _o(e,t,So)}function No(e,t,r,n){const o=qo[n](e,t,yo),a=Uo[n](o,So,vo);return qo[n](a,r,wo)}function Mo(e,t,r,n){const o=Uo[n](Lo(e,t),So,vo);return qo[n](o,r,wo)}const Do=e=>Number(e)/1e18,Wo=e=>Number(e)/1e27,Fo=(e,t)=>Number(e)/10**t;function Vo(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 zo=e=>Vo(e,vo),Xo=(e,t)=>Ro(e,t,yo),Go=(e,t)=>Ro(e,yo,t);function jo(e,t){return 0n===t?0n:Go(e,t)}function Ho(e,t){const r=e>yo?yo:e,n=Io(t.baseRateRay,"irm.baseRateRay"),o=Io(t.slope1Ray,"irm.slope1Ray"),a=Io(t.slope2Ray,"irm.slope2Ray"),i=Io(t.slope3Ray,"irm.slope3Ray"),s=Io(t.midUtilizationRay,"irm.midUtilizationRay"),l=Io(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),u=Io(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<s)c=n+Go(Xo(r,o),s);else if(r<l){const e=l-s;c=n+o+Go(Xo(r-s,a),e)}else{const e=yo-l;c=n+o+a+(0n===e?0n:Go(Xo(r-l,i),e))}return c>u?u:c}function Ko(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:Ro(Xo(e,t),bo-BigInt(r),bo)}const Zo=e=>Wo(e),Yo=e=>Math.expm1(Wo(e)),Jo=5n*wo,Qo=(e,t,r)=>`${e}:${t}:${r}`;function ea(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[Qo(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 ${Qo(t,r,n)}`);return a}const ta=/^0*[1-9]\d*$/,ra=e=>"string"==typeof e&&ta.test(e)?BigInt(e).toString():null,na=(e,t)=>`${e}:${t}`;function oa(e){const t=new Map,r=new Map,n=new Set,o=new Set;for(const a of e?.indexes??[]){const e=na(a.hubId,a.asset),i=ra(a.supplyIndex),s=ra(a.borrowIndex),l=ra(a.usdPrice),u=t.get(e),c=u&&ra(u.supplyIndex)===i&&ra(u.borrowIndex)===s&&ra(u.usdPrice)===l;null==i||null==s||null==l||u&&!c?n.add(e):u||t.set(e,a);const d=!1===a.valid||!0===a.stale||!0===a.deviation,p=r.get(a.asset);null==l||d||void 0!==p&&p.toString()!==l?o.add(a.asset):void 0===p&&r.set(a.asset,BigInt(l))}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 aa=(e,t)=>xo(e,BigInt(t),bo);function ia(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:Do(e.priceWad),amountBase:t.toString(),amountShort:Fo(t,e.decimals),usdWad:r.toString(),usd:Do(r),gateUsdWad:n.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:o?aa(n,a).toString():"0",liquidationWeightedUsdWad:o?aa(n,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function sa(e){if("supply"===e.side)return ia(e,Po(e.scaledRay,e.indexRay,e.decimals,"floor"),No(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),No(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Po(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=No(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ia(e,t,r,r)}function la(e,t,r,n){const o=Lo(t,r);return"supply"===e?xo(o,yo,n):To(o,yo,n)}function ua(e,t,r,n){const o=Lo(t,r);return"supply"===e?To(o,yo,n):xo(o,yo,n)}function ca(e,t){return sa({...e,scaledRay:la(e.side,t,e.decimals,e.indexRay)})}const da=(...e)=>{for(const t of e){const e=ra(t);if(null!=e)return BigInt(e)}return yo};function pa(e,t,r,n){const o=Io("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===o)return null;const a=n.indexes.get(na(t.hubId,t.asset)),i=n.prices.get(t.asset),s="supply"===e?da(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):da(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),l=i??zo(r.usdPrice);return sa({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:o,indexRay:s,priceWad:l,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==a&&void 0!==i})}const fa=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function ha(e,t,r,n,o){const a=fa(t,(e=>e.usdWad)),i=fa(t,(e=>e.ltvWeightedUsdWad)),s=fa(t,(e=>e.liquidationWeightedUsdWad)),l=fa(r,(e=>e.usdWad)),u=0n===l?null:xo(s,wo,l),c=0n===s?0:Number(l)/Number(s)*100,d=i<n||i<=l?0n:i-l;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:a.toString(),totalCollateralUsd:Do(a),ltvWeightedCollateralUsdWad:i.toString(),ltvWeightedCollateralUsd:Do(i),liquidationWeightedCollateralUsdWad:s.toString(),liquidationWeightedCollateralUsd:Do(s),totalDebtUsdWad:l.toString(),totalDebtUsd:Do(l),healthFactorWad:null===u?null:u.toString(),healthFactor:null===u?null:Do(u),healthPercent:c,borrowLimitUsdWad:i.toString(),borrowLimitUsd:Do(i),availableBorrowUsdWad:d.toString(),availableBorrowUsd:Do(d),minBorrowCollateralUsdWad:n.toString(),minBorrowCollateralUsd:Do(n),isLiquidatable:null!==u&&u<wo,liveDataValid:o}}function ma(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=oa(n),i=[],s=[];for(const e of t){const t=ea(r,e.spokeId,e.hubId,e.asset),n=pa("supply",e,t,a);n&&i.push(n);const o=pa("borrow",e,t,a);o&&s.push(o)}const l=null!=n?.minBorrowCollateralUsdWad?Io(n.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):Jo,u=void 0!==n&&[...i,...s].every((e=>e.liveDataUsed));return ha({accountId:o.accountId,owner:o.owner,spokeId:o.spokeId,mode:o.positionMode},i,s,l,u)}const ga=200n,ya=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),wa=e=>e<0n?0n:e,ba=(e,t,r,n)=>({amountBase:e.amount,amountShort:Fo(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:n}),Sa=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function va(e){const t=e.assetDecimals,r=Io(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:Vo(e.hubPool.suppliedShort,t),borrowedBase:Vo(e.hubPool.borrowedShort,t),cashBase:Vo(e.availableLiquidityShort,t),spokeSuppliedBase:Vo(e.suppliedShort,t),spokeBorrowedBase:Vo(e.borrowedShort,t),maxUtilizationRay:r>=yo?null:r}}const Ia=(e,t)=>e<=0n?null:Number(t)/Number(e);function xa(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 Ta=16n,Ra=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Ba(e,t,r){if(t.paused)return Sa("paused");if(t.frozen)return Sa("frozen");if(!t.isBorrowable)return Sa("cap");const n=t.assetDecimals,o=va(t),a=Ra(e.borrows,t),i=oa(r).indexes.get(na(t.hubId,t.asset)),s=a?BigInt(a.indexRay):Io(i?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),l=a?BigInt(a.usdPriceWad):function(e,t){return oa(t).prices.get(e.asset)??zo(e.usdPrice)}(t,r),u=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||l<=0n?0n:xo(t,10n**BigInt(n),l),o=e=>c+No(u+la("borrow",e,n,s),s,l,"ceil");f.push({amount:0n===r?0n:xa(r+Ta,(e=>o(e)<=d)),reason:"ltv"})}f.push({amount:wa(Io(t.borrowCap,"borrowCap")-o.spokeBorrowedBase),reason:"cap"});const h=Ro(o.suppliedBase,ga,bo);f.push({amount:wa(o.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const n=Lo(e.suppliedBase,t);return 0n===n?null:xa(wa(xo(e.suppliedBase,r,yo)-e.borrowedBase)+Ta,(o=>jo(Lo(e.borrowedBase+o,t),n)<=r))}(o,n);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=ya(f);return ba(g,n,!1,Ia(o.suppliedBase,o.borrowedBase+g.amount))}function Ea(e,t,r){if(t.paused)return Sa("paused");const n=Ra(e.supplies,t);if(!n)return Sa(null);const o=n.decimals,a=va(t),i=BigInt(n.scaledRay),s=BigInt(n.indexRay),l=BigInt(n.usdPriceWad),u=BigInt(n.amountBase),c=Po(i,s,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,u=To(e,bo,f),d=BigInt(n.gateUsdWad)-u,p=d<=0n?0n:xo(d,10n**BigInt(o),l),g=c>0n?c-1n:0n,y=p+Ta>g?g:p+Ta,w=e=>{const t=ua("supply",e,o,s);return xo(No(t>=i?0n:i-t,s,l,"floor"),f,bo)};h.push({amount:xa(y,(t=>w(t)>=e)),reason:r})}}h.push({amount:u,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=To(e.borrowedBase,yo,r),o=e.suppliedBase<n?0n:e.suppliedBase-n+Ta,a=Lo(e.borrowedBase,t);return xa(o>e.suppliedBase?e.suppliedBase:o,(n=>{const o=Lo(e.suppliedBase-n,t);return o>0n&&jo(a,o)<=r}))}(a,o);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=ya(h),w=m&&y.amount>=u;return ba(y,o,w,Ia(a.suppliedBase-y.amount,a.borrowedBase))}function _a(e){if(e.paused)return Sa("paused");if(e.frozen)return Sa("frozen");const t=e.assetDecimals,r=va(e),n={amount:wa(Io(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return ba(n,t,!1,Ia(r.suppliedBase+n.amount,r.borrowedBase))}function Aa(e,t,r){if(t.paused)return Sa("paused");const n=Ra(e.borrows,t);if(!n)return Sa(null);const o=n.decimals,a=va(t),i=BigInt(n.amountBase),s=void 0===r?null:Io(r,"walletBalance"),l=null!==s&&s<i?{amount:s,reason:"liquidity"}:{amount:i,reason:null};return ba(l,o,l.amount>=i,Ia(a.suppliedBase,wa(a.borrowedBase-l.amount)))}const ka=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,qa=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 Ua(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=>ka(t,e))),a=-1===o?void 0:t[o],i=qa(e.amountBase);let s;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(i>=0n)r=t+la(e.side,i,e.decimals,e.indexRay);else{const n=-i,o=n>=("supply"===e.side?Po(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:ua(e.side,n,e.decimals,e.indexRay);r=o>=t?0n:t-o}s=0n===r?null:sa({...e,scaledRay:r})}else s=i<=0n?null:ca(Pa(e),i);-1===o?s&&t.push(s):s?t[o]=s:t.splice(o,1)}return ha({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,n,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Pa(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:Io("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:zo(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function Oa(e,t=0n,r=0n){const n=e.assetDecimals,o=e=>e<0n?0n:e,a=o(Vo(e.hubPool.suppliedShort,n)+qa(t)),i=jo(Lo(o(Vo(e.hubPool.borrowedShort,n)+qa(r)),n),Lo(a,n)),s=Ho(i,e.irm),l=Ko(i,s,e.irm.reserveFactorBps);return{utilization:Wo(i),utilizationRay:i.toString(),borrowAprRay:s.toString(),supplyAprRay:l.toString(),borrowApr:Zo(s),supplyApr:Zo(l),borrowApy:Yo(s),supplyApy:Yo(l)}}const Ca={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."},6:{name:"InvalidAsset",message:"Invalid asset address."},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."},14:{name:"AmountMustBePositive",message:"The amount must be greater than zero."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},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."},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."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},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."}};function $a(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),n=Ca[r];return n?{code:r,...n}:null}})(),module.exports=n})();
2
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{var e={526(e,t){"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=s(e),i=a[0],l=a[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,i,l)),c=0,d=l>0?i-4:i;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)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===l&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===l&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,a=[],i=16383,s=0,u=n-o;s<u;s+=i)a.push(l(e,s,s+i>u?u:s+i));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+/",i=0;i<64;++i)r[i]=a[i],n[a.charCodeAt(i)]=i;function s(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 l(e,t,n){for(var o,a,i=[],s=t;s<n;s+=3)o=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(r[(a=o)>>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const n=r(526),o=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const i=2147483647;function s(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(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 u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=s(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 l.from(n,t,r);const o=function(e){if(l.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?s(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 l.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),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(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,l.prototype),n}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function m(e,t){if(l.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 G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return j(e).length;default:if(o)return n?-1:G(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 k(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return _(this,t,r);case"latin1":case"binary":return A(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=l.from(t,n)),l.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,i=1,s=e.length,l=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;i=2,s/=2,l/=2,r/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){let n=-1;for(a=r;a<s;a++)if(u(e,a)===u(t,-1===n?0:a-n)){if(-1===n&&(n=a),a-n+1===l)return n*i}else-1!==n&&(a-=a-n),n=-1}else for(r+l>s&&(r=s-l),a=r;a>=0;a--){let r=!0;for(let n=0;n<l;n++)if(u(e,a+n)!==u(t,n)){r=!1;break}if(r)return a}return-1}function S(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 i;for(n>a/2&&(n=a/2),i=0;i<n;++i){const n=parseInt(t.substr(2*i,2),16);if(Z(n))return i;e[r+i]=n}return i}function v(e,t,r,n){return H(G(t,e.length-r),e,r,n)}function I(e,t,r,n){return H(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 x(e,t,r,n){return H(j(t),e,r,n)}function T(e,t,r,n){return H(function(e,t){let r,n,o;const a=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)r=e.charCodeAt(i),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 B(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o<r;){const t=e[o];let a=null,i=t>239?4:t>223?3:t>191?2:1;if(o+i<=r){let r,n,s,l;switch(i){case 1:t<128&&(a=t);break;case 2:r=e[o+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(l=(15&t)<<12|(63&r)<<6|63&n,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(l=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),o+=i}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=E));return r}(n)}l.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}}(),l.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(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?s(e):void 0!==t?"string"==typeof r?s(e).fill(t,r):s(e).fill(t):s(e)}(e,t,r)},l.allocUnsafe=function(e){return d(e)},l.allocUnsafeSlow=function(e){return d(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.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},l.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}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=l.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?(l.isBuffer(t)||(t=l.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},l.byteLength=m,l.prototype._isBuffer=!0,l.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},l.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},l.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},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?B(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.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&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,r,n,o){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.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),i=(r>>>=0)-(t>>>=0);const s=Math.min(a,i),u=this.slice(n,o),c=e.slice(t,r);for(let e=0;e<s;++e)if(u[e]!==c[e]){a=u[e],i=c[e];break}return a<i?-1:i<a?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.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 S(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return I(this,e,t,r);case"base64":return x(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function _(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 A(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 k(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 P(e,t,r,n,o,a){if(!l.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){F(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 i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,r}function C(e,t,r,n,o){F(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 i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=i,i>>=8,e[r+2]=i,i>>=8,e[r+1]=i,i>>=8,e[r]=i,r+8}function $(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 L(e,t,r,n,a){return t=+t,r>>>=0,a||$(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function N(e,t,r,n,a){return t=+t,r>>>=0,a||$(e,0,r,8),o.write(e,t,r,n,52,8),r+8}l.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,l.prototype),n},l.prototype.readUintLE=l.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},l.prototype.readUintBE=l.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},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.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]},l.prototype.readUint32BE=l.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])},l.prototype.readBigUInt64LE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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))})),l.prototype.readBigUInt64BE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.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},l.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},l.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.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},l.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},l.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},l.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]},l.prototype.readBigInt64LE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.prototype.readBigInt64BE=J((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(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)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(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},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(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},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=J((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=J((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=0,a=1,i=0;for(this[t]=255&e;++o<r&&(a*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/a|0)-i&255;return t+r},l.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=r-1,a=1,i=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/a|0)-i&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=J((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=J((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return N(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return N(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,n){if(!l.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},l.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&&!l.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=l.isBuffer(e)?e:l.from(e,n),i=a.length;if(0===i)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=a[o%i]}return this};const M={};function D(e,t,r){M[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 W(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 F(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 M.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||z(t,e.length-(r+1))}(n,o,a)}function V(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function z(e,t,r){if(Math.floor(e)!==e)throw V(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.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=W(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=W(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function G(e,t){let r;t=t||1/0;const n=e.length;let o=null;const a=[];for(let i=0;i<n;++i){if(r=e.charCodeAt(i),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+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 j(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 H(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,i,s=8*o-n-1,l=(1<<s)-1,u=l>>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+=s;c>0;a=256*a+e[t+d],d+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+e[t+d],d+=p,c-=8);if(0===a)a=1-u;else{if(a===l)return i?NaN:1/0*(f?-1:1);i+=Math.pow(2,n),a-=u}return(f?-1:1)*i*Math.pow(2,a-n)},t.write=function(e,t,r,n,o,a){var i,s,l,u=8*a-o-1,c=(1<<u)-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?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-i))<1&&(i--,l*=2),(t+=i+d>=1?p/l:p*Math.pow(2,1-d))*l>=2&&(i++,l/=2),i+d>=c?(s=0,i=c):i+d>=1?(s=(t*l-1)*Math.pow(2,o),i+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),i=0));o>=8;e[r+f]=255&s,f+=h,s/=256,o-=8);for(i=i<<o|s,u+=o;u>0;e[r+f]=255&i,f+=h,i/=256,u-=8);e[r+f-h]|=128*m}},468(e,t,r){"use strict";r.d(t,{createStellarLendingReadClient:()=>b,lendingAssetsSchema:()=>y,lendingPositionsSchema:()=>g});const n={type:"string"},o={type:"number"},a={type:"boolean"},i={...n,nullable:!0},s={...o,nullable:!0},l={...n,enum:["mainnet","testnet"]},u={...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:s,logoUrl:i},p=c({valid:a,stale:a,deviation:a,timestamp:s}),f=c({...d,hubId:o,hubName:n,amountRaw:{...i,description:"Integer token base units, never scaled shares."},amount:i,apy:{...s,description:"Fraction: 0.05 means 5%."},priceUsd:s,valueUsd:s,priceStatus:p,indexRay:i,indexedAt:o,indexedLedger:o}),h=c({amountRaw:i,amount:i,usd:s}),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:l,spokeId:s,spokeName:i,supplied:{type:"array",items:f},borrow:{type:"array",items:f},hasDebt:{...a,nullable:!0,description:"Null when account rows are unavailable."},healthFactor:{...s,description:"Null without debt or when risk inputs are unavailable."},borrowLimitUsd:s,availableBorrowUsd:{...s,description:"Account headroom, before per-market constraints."},netApy:{...s,description:"Net annual yield divided by positive net equity; fraction."},dataStatus:u})},y={type:"array",items:c({...d,hubId:o,hubName:n,network:l,supplyApy:{...s,description:"Fraction: 0.05 means 5%."},borrowApy:{...s,description:"Fraction: 0.05 means 5%."},priceUsd:s,priceStatus:p,spokes:{type:"array",items:m},dataStatus:u,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,i=!1;for(const e of o[2].matchAll(/;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\.)*)"|([\w!#$%&'*+.^`|~:/-]+))\s*/g))if("rel"===e[1].toLowerCase()){if(i)throw new Error("Duplicate pagination link relation");i=!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 i=new Set,s=[];for(;;){if(i.has(a.href))throw new Error("Pagination Link cycle");i.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");s.push(...t);const l=w(e.headers.get("Link"));if(!l)break;const u=new URL(l,a);if(u.origin!==o.origin||u.pathname!==o.pathname||u.username||u.password||u.hash)throw new Error("Pagination Link must stay on the same API endpoint");a=u}return s}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)}}}},387(e,t,r){"use strict";r.d(t,{GW:()=>a});var n,o=r(564);!function(e){e.MAINNET="1",e.DEVNET="D"}(n||(n={}));class a{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=n.MAINNET,apiUrl:r,...a}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=a,this.config=t==n.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:o.s0,FM_SC:o.ZZ,DR_SC:o.sM,KG_SC:o.KL,Staking_SC:o.V,Manager_SC:o.Rh,P2P_SC:o.EP}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:o.cM,FM_SC:o.ZZ,DR_SC:o.sM,KG_SC:o.KL,Staking_SC:o.J6,Manager_SC:o.Ff,P2P_SC:o.gx}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:n,cache:o,debug:a,timeout:i,...s}=this.init,{next:l,cache:u,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("&"),S=`${this.apiUrl}${e}${b.length?`?${b}`:""}`,{revalidate:v,...I}=n??{},{revalidate:x,...T}=l??{},R="GET"!==f||g?void 0:x??v,B="GET"!==f||g||R?void 0:u??o,E=h.body,_=d??i??(null==E?3e4:0),A=_>0?AbortSignal.timeout(_):void 0,k=h.signal??s.signal,q=A&&k?AbortSignal.any([k,A]):A??k,U={...s,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:B,next:{...I,...T,revalidate:R}};(c??a)&&console.debug("SDK fetch: ",S,U);const P=await fetch(S,U).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${S}: ${e.message}`),{cause:e});throw e})),O=await P.text();if(!P.ok){let e;try{e=JSON.parse(O)}catch{e={message:O}}const t=[S,P.status,P.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(O)}catch{return O}}}},564(e,t,r){"use strict";r.d(t,{EP:()=>u,Ff:()=>p,J6:()=>d,KL:()=>i,Rh:()=>l,V:()=>s,ZZ:()=>o,cM:()=>c,gx:()=>f,s0:()=>n,sM:()=>a});const n="erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",o="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",a="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",i="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e",s="erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",l="erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",u="erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6",c="erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",d="erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",p="erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",f="erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";r.r(n),r.d(n,{BPS:()=>bo,DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD:()=>Jo,LIQUIDATION_BUFFER_BPS:()=>ga,RAY:()=>yo,RAY_DECIMALS:()=>So,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Ft,STELLAR_LENDING_TOPICS:()=>fn,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_ROUTE_MAX_BYTES:()=>qn,SYNTHETIC_EVENT_ORDER_STRIDE:()=>mn,StellarAuthPolicyError:()=>jn,StellarRouteVerificationError:()=>Un,WAD:()=>wo,WAD_DECIMALS:()=>vo,XOXNOClient:()=>e.GW,aggregateAccountRisk:()=>ha,annualBorrowRateRay:()=>Ho,assertStellarAuthEntries:()=>to,assertStellarPreparedTxAuth:()=>lo,baseToRay:()=>Lo,baseToShort:()=>Fo,baseValueWad:()=>Mo,buildLiveSnapshot:()=>oa,buildSameTokenRepaySwapSteps:()=>ho,buildStellarAcceptOwnershipTx:()=>Tt,buildStellarAddRewardsTx:()=>Dt,buildStellarApproveBlendPoolTx:()=>At,buildStellarBorrowBatchTx:()=>J,buildStellarBorrowTx:()=>Q,buildStellarCctpForwardTx:()=>go,buildStellarClaimRevenueTx:()=>Mt,buildStellarCreateLiquidityPoolTx:()=>Lt,buildStellarExecuteCancellerResetTx:()=>Fr,buildStellarExecuteStrategyTx:()=>Fn,buildStellarFlashLoanTx:()=>ie,buildStellarGovernanceAddSpokeImmediateTx:()=>Gr,buildStellarGovernanceCreateHubImmediateTx:()=>Xr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>Cr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Lr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Nr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Mr,buildStellarGovernanceExecuteTx:()=>Or,buildStellarGovernanceExecuteUpdateDelayTx:()=>$r,buildStellarGovernancePauseTx:()=>Hr,buildStellarGovernanceRevokeRoleImmediateTx:()=>jr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>zr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Vr,buildStellarGrantRoleTx:()=>vt,buildStellarLendingIdentifier:()=>gn,buildStellarLiquidateTx:()=>oe,buildStellarMigrateFromBlendTx:()=>se,buildStellarMigrateTx:()=>wt,buildStellarMultiplyTx:()=>le,buildStellarPauseTx:()=>bt,buildStellarProposeAddAssetToSpokeTx:()=>cr,buildStellarProposeAddSpokeTx:()=>lr,buildStellarProposeApproveBlendPoolTx:()=>wr,buildStellarProposeApproveTokenTx:()=>gr,buildStellarProposeCancellerResetTx:()=>Wr,buildStellarProposeConfigureAssetOracleTx:()=>Er,buildStellarProposeCreateHubTx:()=>sr,buildStellarProposeCreateLiquidityPoolTx:()=>Sr,buildStellarProposeDeployPoolTx:()=>Ir,buildStellarProposeEditAssetInSpokeTx:()=>dr,buildStellarProposeEditOracleToleranceTx:()=>_r,buildStellarProposeGovernanceUpgradeTx:()=>Ar,buildStellarProposeGrantGovernanceRoleTx:()=>qr,buildStellarProposeMigrateControllerTx:()=>Rr,buildStellarProposeRemoveAssetFromSpokeTx:()=>pr,buildStellarProposeRemoveSpokeTx:()=>ur,buildStellarProposeRevokeBlendPoolTx:()=>br,buildStellarProposeRevokeGovernanceRoleTx:()=>Ur,buildStellarProposeRevokeTokenTx:()=>yr,buildStellarProposeSetAccumulatorTx:()=>ar,buildStellarProposeSetMinBorrowCollatTx:()=>mr,buildStellarProposeSetPositionLimitsTx:()=>ir,buildStellarProposeSetPositionManagerTx:()=>hr,buildStellarProposeSetPriceAggregatorTx:()=>or,buildStellarProposeSetSpokeLiquidationCurveTx:()=>fr,buildStellarProposeSetSwapAggregatorTx:()=>nr,buildStellarProposeTransferCtrlOwnershipTx:()=>Br,buildStellarProposeTransferGovOwnTx:()=>Pr,buildStellarProposeUnpauseTx:()=>Kr,buildStellarProposeUpdateDelayTx:()=>kr,buildStellarProposeUpgradeControllerTx:()=>Tr,buildStellarProposeUpgradePoolParamsTx:()=>vr,buildStellarProposeUpgradePoolTx:()=>xr,buildStellarRenewAccountTx:()=>$t,buildStellarRepayBatchTx:()=>re,buildStellarRepayDebtWithCollateralTx:()=>de,buildStellarRepayTx:()=>ne,buildStellarRevokeBlendPoolTx:()=>kt,buildStellarRevokeRoleTx:()=>It,buildStellarSetAccumulatorTx:()=>Et,buildStellarSetOracleSanityBoundsTx:()=>Ot,buildStellarSetOracleToleranceTx:()=>Ut,buildStellarSetOracleTx:()=>qt,buildStellarSetPositionLimitsTx:()=>_t,buildStellarSetPriceAggregatorTx:()=>Bt,buildStellarSetSpokeAssetFlagsTx:()=>Pt,buildStellarSetSwapAggregatorTx:()=>Rt,buildStellarSupplyBatchTx:()=>Z,buildStellarSupplyTx:()=>Y,buildStellarSwapCollateralTx:()=>ce,buildStellarSwapDebtTx:()=>ue,buildStellarTransferOwnershipTx:()=>xt,buildStellarUnpauseTx:()=>St,buildStellarUpdateAccountThresholdTx:()=>Wt,buildStellarUpdateIndexesTx:()=>Ct,buildStellarUpgradeControllerTx:()=>yt,buildStellarUpgradeLiquidityPoolParamsTx:()=>Nt,buildStellarWithdrawBatchTx:()=>ee,buildStellarWithdrawTx:()=>te,buildTx:()=>H,burnShares:()=>ua,computeAccountRisk:()=>ma,createStellarLendingReadClient:()=>ot.createStellarLendingReadClient,decodeStellarLendingEvent:()=>hn,decodeStellarLiquidateReturn:()=>ae,decodeStellarRouteBytes:()=>$n,decodeStellarSwapEnvelope:()=>Gn,depositRateRay:()=>Ko,divByIntHalfUp:()=>Bo,encodeAssetOracle:()=>gt,encodeInterestRateModel:()=>at,encodeMarketParamsRaw:()=>it,encodePositionLimits:()=>st,encodePriceKey:()=>lt,encodeStrategyPayloadToRouteXdr:()=>Wn,extractEventOrder:()=>yn,getStellarAccountPositions:()=>Be,getStellarActiveUsersSeries:()=>Ze,getStellarAggregatorQuote:()=>vn,getStellarAsset:()=>Ie,getStellarAssetGraph:()=>Pe,getStellarAssetMarkets:()=>Ae,getStellarAssetPage:()=>_e,getStellarAssets:()=>ye,getStellarCampaignLeaderboard:()=>ze,getStellarCampaignMe:()=>rt,getStellarDefiLlamaDimensions:()=>Je,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>ge,getStellarFeeRevenueSeries:()=>je,getStellarGovernanceProposals:()=>Me,getStellarHolderDistribution:()=>Ve,getStellarHub:()=>xe,getStellarHubGraph:()=>Oe,getStellarHubHolders:()=>qe,getStellarHubs:()=>we,getStellarLendingContext:()=>he,getStellarLendingLiveState:()=>me,getStellarLiquidationsLeaderboard:()=>Fe,getStellarLiquidationsSeries:()=>He,getStellarParticipantCounts:()=>We,getStellarPnlByScope:()=>tt,getStellarPositionsLeaderboard:()=>De,getStellarPositionsPnl:()=>et,getStellarQuoteTokens:()=>In,getStellarRateSpreadSeries:()=>Ye,getStellarReserve:()=>ve,getStellarReserveGraph:()=>$e,getStellarReserveHolders:()=>ke,getStellarReserves:()=>Se,getStellarRevenueSeries:()=>Ge,getStellarSpoke:()=>Te,getStellarSpokeGraph:()=>Ce,getStellarSpokeHolders:()=>Ue,getStellarSpokes:()=>be,getStellarStatsHistory:()=>Xe,getStellarUserActivity:()=>Le,getStellarUserActivityPage:()=>Ne,getStellarUserHistory:()=>Qe,getStellarUserPositions:()=>Re,getStellarVolumeSeries:()=>Ke,getStellarWalletBalance:()=>Ee,lendingAssetsSchema:()=>ot.lendingAssetsSchema,lendingPositionsSchema:()=>ot.lendingPositionsSchema,liveIndexKey:()=>na,mapQuoteResponseToStrategyPayload:()=>Vn,mapQuoteResponseToStrategySwap:()=>zn,mapSorobanError:()=>$a,mapStellarPositionActivityType:()=>bn,maxBorrow:()=>Ba,maxRepay:()=>Aa,maxSupply:()=>_a,maxWithdraw:()=>Ea,mintShares:()=>la,mulDivCeil:()=>To,mulDivFloor:()=>xo,mulDivHalfUp:()=>Ro,numberToScaled:()=>Vo,numberToWad:()=>zo,parseStellarTokenAmount:()=>j,positionValueWad:()=>No,prepareStellarBuiltTx:()=>po,prepareStellarTxXdr:()=>co,projectAccountRisk:()=>Ua,projectReserveApy:()=>Oa,rayAprToApy:()=>Yo,rayAprToNumber:()=>Zo,rayToNumber:()=>Wo,rescaleCeil:()=>Ao,rescaleFloor:()=>_o,rescaleHalfUp:()=>ko,reserveKey:()=>Qo,resolveReserve:()=>ea,stellarAuthPolicyForInvocation:()=>io,stellarLendingDispatchKey:()=>Jr,stellarLendingRead:()=>nt,stellarNetworks:()=>o,stellarTokenContractId:()=>Ln,syntheticEventOrder:()=>wn,tagStellarInvokedContractError:()=>uo,toBase64Xdr:()=>Zr,toBigInt:()=>Io,toStellarPositionMode:()=>fo,unscale:()=>Po,unscaleBorrowCeil:()=>Co,unscaleHalfUp:()=>$o,unscaleSupplyFloor:()=>Oo,utilizationRay:()=>jo,valueBasePosition:()=>ca,valueScaledPosition:()=>sa,verifyStellarRouteBytes:()=>Mn,wadToNumber:()=>Do});var e=r(387);const t={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:"CAALOOTIDXCX7D7FMQIBSSAJLPKOM3GMXS4UUSTDIG42JCRRJHOPUHOP",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},o=t;function a(e){return t["testnet"===e?"stellarTestnet":"stellarMainnet"]}const i={mainnet:t.stellarMainnet.passphrase,testnet:t.stellarTestnet.passphrase},s=require("@stellar/stellar-sdk");var l=r(287);const u=["Soroswap","Aquarius","Phoenix","Sushi","CometDex","Curve"],c={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4,Curve:7},d=1,p=1e6,f=5,h=6,m=0,g=1,y=2,w=128,b=48,S=32,v=256,I=w-y,x=e=>new s.Address(e).toScVal(),T=e=>new s.ScInt(e).toI128(),R=e=>s.xdr.ScVal.scvU32(e),B=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.ScInt("string"==typeof e?e:e.toString()).toU64()},E=e=>s.xdr.ScVal.scvBool(e),_=e=>s.xdr.ScVal.scvString(e),A=e=>s.xdr.ScVal.scvSymbol(e),k=()=>s.xdr.ScVal.scvVoid(),q=e=>s.xdr.ScVal.scvVec(e),U=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,n=l.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 s.xdr.ScVal.scvBytes(n)},P=(e,t)=>null==e?k():t(e),O=e=>s.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,s.xdr.ScVal.scvVec([x(t),T(r)]);var t,r}))),C=(e,t)=>M({asset:x(t),hub_id:R(e)}),$=(e,t,r)=>s.xdr.ScVal.scvVec([C(e,t),T(r)]),L=e=>s.xdr.ScVal.scvVec(e.map((e=>$(e.hubId,e.asset,e.amount)))),N=e=>{if("Transfer"===e)return q([A("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 q([A("Credit"),B(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},M=e=>{const t=Object.keys(e).sort().map((t=>new s.xdr.ScMapEntry({key:A(t),val:e[t]})));return s.xdr.ScVal.scvMap(t)};class D{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>=v)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>=I)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>=S)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>p)throw new Error(`Stellar builder: split weight ${e} outside 1..=${p}`);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(c[r.venue],0===n?t:g,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>p)throw new Error(`Stellar builder: split weights for one token sum to ${a}, above ${p}`);const i=a===p;let s=p;o.forEach(((e,n)=>{r[e]=!0;const a=t[e];let l;if(n+1===o.length&&i)l=m;else{if(0===s)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(a.splitPpm*p/s);s-=Math.min(a.splitPpm,s),l=w+this.weight(e)}this.emitPath(a,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>b)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts ${b}`);const n=[d,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 l.hp.from(n)}get assetList(){return this.assets}get amountList(){return this.amounts}}const W=e=>{const t=new D(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(f,m,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,[i,s]=e.preSwapFromA?[o,a]:[a,o];t.emit(c.Aquarius,y+t.amount(r),t.asset(e.mintPool),t.asset(i),t.asset(s))}t.emit(h,m,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 M({amounts:s.xdr.ScVal.scvVec(t.amountList.map((e=>T(e)))),assets:s.xdr.ScVal.scvVec(t.assetList.map((e=>x(e)))),ops:s.xdr.ScVal.scvBytes(t.toBytes(r,n,o))})},F=e=>{const t=l.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 s.xdr.ScVal.scvBytes(t)},V=()=>s.xdr.ScVal.scvBytes(l.hp.alloc(0)),z=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 l.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=l.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},X=e=>{if("string"==typeof e)return F(z(e));if(e instanceof Uint8Array)return 0===e.length?V():F(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?F(z(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?F(z(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?F(z(e.bytes)):0===e.bytes.length?V():F(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||!u.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>p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${n}, above ${p}`);if(!t.mintPool&&n!==p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to ${p}, got ${n}`)}return t})(e),s.xdr.ScVal.scvBytes(l.hp.from(W(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},G=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=l.hp.from(t,"hex");return s.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return s.xdr.ScVal.scvBytes(l.hp.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function j(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.Soroban.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 H(e,t,r){if(!e.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const n=new s.Contract(e.controllerAddress),o=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(n.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function K(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return R(e)}function Z(e,t){const r=t.accountNonce??0;return H(e,"supply",[x(e.caller),B(r),K(t.spokeId),L([...t.assets])])}function Y(e,t){return Z(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function J(e,t){return H(e,"borrow",[x(e.caller),B(t.accountNonce),L([...t.borrows]),P(t.to,x)])}function Q(e,t){return J(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function ee(e,t){return H(e,"withdraw",[x(e.caller),B(t.accountNonce),L([...t.withdrawals]),P(t.to,x)])}function te(e,t){return ee(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function re(e,t){return H(e,"repay",[x(e.caller),B(t.accountNonce),L([...t.payments])])}function ne(e,t){return re(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function oe(e,t){return H(e,"liquidate",[x(e.caller),B(t.accountNonce),L([...t.debtPayments]),N(t.seizeMode??"Transfer")])}function ae(e){const t=(0,s.scValToNative)(s.xdr.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 H(e,"flash_loan",[x(e.caller),C(t.hubId,t.asset),T(t.amount),x(t.receiver),G(t.data)])}function se(e,t){return H(e,"migrate_from_blend",[x(e.caller),B(t.accountId),K(t.spokeId),R(t.hubId),x(t.blendPool),q(t.collateralTokens.map(x)),q(t.supplyTokens.map(x)),O(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function le(e,t){const r=t.accountNonce??0;return H(e,"multiply",[x(e.caller),B(r),K(t.spokeId),C(t.collateral.hubId,t.collateral.asset),T(t.debtToFlashLoan),C(t.debt.hubId,t.debt.asset),R(t.mode),X(t.steps),P(t.initialPayment,(e=>$(e.hubId,e.asset,e.amount))),P(t.convertSwap,X)])}function ue(e,t){return H(e,"swap_debt",[x(e.caller),B(t.accountNonce),C(t.existingDebt.hubId,t.existingDebt.asset),T(t.newDebtAmount),C(t.newDebt.hubId,t.newDebt.asset),X(t.steps)])}function ce(e,t){return H(e,"swap_collateral",[x(e.caller),B(t.accountNonce),C(t.current.hubId,t.current.asset),T(t.fromAmount),C(t.newCollateral.hubId,t.newCollateral.asset),X(t.steps)])}function de(e,t){return H(e,"repay_debt_with_collateral",[x(e.caller),B(t.accountNonce),C(t.collateral.hubId,t.collateral.asset),T(t.collateralAmount),C(t.debt.hubId,t.debt.asset),X(t.steps),E(t.closePosition)])}const pe="/stellar-lending",fe=encodeURIComponent,he=(e,t)=>e.fetchWithTimeout(`${pe}/context`,t),me=(e,t)=>e.fetchWithTimeout(`${pe}/live-state`,t),ge=(e,t)=>e.fetchWithTimeout(`${pe}/markets/detailed`,t),ye=(e,t)=>e.fetchWithTimeout(`${pe}/assets`,t),we=(e,t)=>e.fetchWithTimeout(`${pe}/hubs`,t),be=(e,t)=>e.fetchWithTimeout(`${pe}/spokes`,t),Se=(e,t={},r)=>e.fetchWithTimeout(`${pe}/reserves`,{...r,params:{...t}}),ve=(e,t,r,n,o)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}`,o),Ie=(e,t,r)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}`,r),xe=(e,t,r)=>e.fetchWithTimeout(`${pe}/hubs/${t}`,r),Te=(e,t,r)=>e.fetchWithTimeout(`${pe}/spokes/${t}`,r),Re=(e,t,r)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/positions`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${pe}/accounts/${fe(t)}/positions`,r),Ee=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/assets/${fe(r)}/balance`,n),_e=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/page`,{...n,params:{...r}}),Ae=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/markets`,{...n,params:{side:r}}),ke=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}/holders`,{...a,params:{side:o}}),qe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/hubs/${t}/holders`,{...n,params:{side:r}}),Ue=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/spokes/${t}/holders`,{...n,params:{side:r}}),Pe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/assets/${fe(t)}/graph`,{...n,params:{...r}}),Oe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/hubs/${t}/graph`,{...n,params:{...r}}),Ce=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/spokes/${t}/graph`,{...n,params:{...r}}),$e=(e,t,r,n,o,a)=>e.fetchWithTimeout(`${pe}/reserves/${t}/${r}/${fe(n)}/graph`,{...a,params:{...o}}),Le=(e,t,r={},n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/activity`,{...n,params:{...r}}),Ne=(e,t,r={},n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/activity/page`,{...n,params:{...r}}),Me=(e,t={},r)=>e.fetchWithTimeout(`${pe}/governance/proposals`,{...r,params:{...t}}),De=(e,t={},r)=>e.fetchWithTimeout(`${pe}/positions`,{...r,params:{...t}}),We=(e,t={},r)=>e.fetchWithTimeout(`${pe}/participants`,{...r,params:{...t}}),Fe=(e,t={},r)=>e.fetchWithTimeout(`${pe}/liquidations/leaderboard`,{...r,params:{...t}}),Ve=(e,t={},r)=>e.fetchWithTimeout(`${pe}/distribution`,{...r,params:{...t}}),ze=(e,t={},r)=>e.fetchWithTimeout(`${pe}/campaign/leaderboard`,{...r,params:{...t}}),Xe=(e,t,r)=>e.fetchWithTimeout(`${pe}/stats/history`,{...r,params:{...t}}),Ge=(e,t,r)=>e.fetchWithTimeout(`${pe}/revenue`,{...r,params:{...t}}),je=(e,t,r)=>e.fetchWithTimeout(`${pe}/revenue/fees`,{...r,params:{...t}}),He=(e,t,r)=>e.fetchWithTimeout(`${pe}/liquidations`,{...r,params:{...t}}),Ke=(e,t,r)=>e.fetchWithTimeout(`${pe}/volume`,{...r,params:{...t}}),Ze=(e,t,r)=>e.fetchWithTimeout(`${pe}/active-users`,{...r,params:{...t}}),Ye=(e,t,r)=>e.fetchWithTimeout(`${pe}/rate-spread`,{...r,params:{...t}}),Je=(e,t,r)=>e.fetchWithTimeout(`${pe}/defillama`,{...r,params:{...t}}),Qe=(e,t,r,n)=>e.fetchWithTimeout(`${pe}/users/${fe(t)}/history`,{...n,params:{...r}}),et=(e,t,r)=>e.fetchWithTimeout(`${pe}/pnl`,{...r,params:{accountId:t}}),tt=(e,t,r)=>e.fetchWithTimeout(`${pe}/pnl/scope`,{...r,params:{scope:t}}),rt=(e,t,r)=>e.fetchWithTimeout(`${pe}/campaign/me`,{...r,params:{owner:t}}),nt=e=>({context:t=>he(e,t),liveState:t=>me(e,t),marketsDetailed:t=>ge(e,t),assets:t=>ye(e,t),hubs:t=>we(e,t),spokes:t=>be(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?Se(e,t,r):Se(e,{},t),reserve:(t,r,n,o)=>ve(e,t,r,n,o),asset:(t,r)=>Ie(e,t,r),hub:(t,r)=>xe(e,t,r),spoke:(t,r)=>Te(e,t,r),userPositions:(t,r)=>Re(e,t,r),accountPositions:(t,r)=>Be(e,t,r),walletBalance:(t,r,n)=>Ee(e,t,r,n),assetPage:(t,r,n)=>_e(e,t,r,n),assetMarkets:(t,r,n)=>Ae(e,t,r,n),reserveHolders:(t,r,n,o,a)=>ke(e,t,r,n,o,a),hubHolders:(t,r,n)=>qe(e,t,r,n),spokeHolders:(t,r,n)=>Ue(e,t,r,n),assetGraph:(t,r,n)=>Pe(e,t,r,n),hubGraph:(t,r,n)=>Oe(e,t,r,n),spokeGraph:(t,r,n)=>Ce(e,t,r,n),reserveGraph:(t,r,n,o,a)=>$e(e,t,r,n,o,a),userActivity:(t,r={},n)=>Le(e,t,r,n),userActivityPage:(t,r={},n)=>Ne(e,t,r,n),governanceProposals:(t={},r)=>Me(e,t,r),positionsLeaderboard:(t={},r)=>De(e,t,r),participants:(t={},r)=>We(e,t,r),liquidationsLeaderboard:(t={},r)=>Fe(e,t,r),distribution:(t={},r)=>Ve(e,t,r),campaignLeaderboard:(t={},r)=>ze(e,t,r),statsHistory:(t,r)=>Xe(e,t,r),revenue:(t,r)=>Ge(e,t,r),feeRevenue:(t,r)=>je(e,t,r),liquidations:(t,r)=>He(e,t,r),volume:(t,r)=>Ke(e,t,r),activeUsers:(t,r)=>Ze(e,t,r),rateSpread:(t,r)=>Ye(e,t,r),defillama:(t,r)=>Je(e,t,r),userHistory:(t,r,n)=>Qe(e,t,r,n),positionsPnl:(t,r)=>et(e,t,r),pnlByScope:(t,r)=>tt(e,t,r),campaignMe:(t,r)=>rt(e,t,r)});var ot=r(468);const at=e=>M({base_borrow_rate:T(e.baseBorrowRateRay),max_borrow_rate:T(e.maxBorrowRateRay),max_utilization:T(e.maxUtilizationRay),mid_utilization:T(e.midUtilizationRay),optimal_utilization:T(e.optimalUtilizationRay),reserve_factor:R(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),it=e=>M({asset_decimals:R(e.assetDecimals),asset_id:x(e.assetId),base_borrow_rate:T(e.baseBorrowRateRay),flashloan_fee:R(e.flashloanFeeBps),is_flashloanable:E(e.isFlashloanable),max_borrow_rate:T(e.maxBorrowRateRay),max_utilization:T(e.maxUtilizationRay),mid_utilization:T(e.midUtilizationRay),optimal_utilization:T(e.optimalUtilizationRay),reserve_factor:R(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),st=e=>M({max_borrow_positions:R(e.maxBorrowPositions),max_supply_positions:R(e.maxSupplyPositions)}),lt=e=>{if("Token"in e&&e.Token)return q([A("Token"),x(e.Token)]);if("Ref"in e&&e.Ref)return q([A("Ref"),A(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},ut=e=>{if("Stellar"in e)return q([A("Stellar"),x(e.Stellar)]);if("Symbol"in e)return q([A("Symbol"),A(e.Symbol)]);if("String"in e)return q([A("String"),_(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},ct=e=>{if("Spot"===e)return q([A("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return q([A("Twap"),R(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},dt=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return q([A(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},pt=e=>{if("Market"===e||"Fundamental"===e)return q([A(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},ft=e=>{if("Reflector"in e){const t=e.Reflector;return q([A("Reflector"),M({asset:ut(t.asset),contract:x(t.contract),read_mode:ct(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return q([A("MultiFeed"),M({contract:x(t.contract),feed_id:_(t.feedId),kind:dt(t.kind),nature:pt(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},ht=e=>{const t=e;return M({decimals:R(t.decimals),max_stale_seconds:B(t.maxStaleSeconds),provider:ft(t.provider)})},mt=e=>{if("RequireDisjoint"===e)return q([A("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return q([A("AllowShared"),q(t.map((e=>M({contract:x(e.contract),kind:dt(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},gt=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 M({asset_decimals:R(Number(t.assetDecimals)),independence:mt(t.independence),max_price_stale_seconds:B(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:T(String(t.maxSanityPriceWad)),min_sanity_price_wad:T(String(t.minSanityPriceWad)),sources:q(r.map((e=>(e=>{if("Feed"in e)return q([A("Feed"),ht(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return q([A("Scaled"),M({factor:ht(t.factor),max_factor_wad:T(t.maxFactorWad),min_factor_wad:T(t.minFactorWad),quote:lt(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return q([A("LpShare"),M({key_a:lt(t.keyA),key_b:lt(t.keyB),kind:q([A(t.kind||"ConstantProduct")]),pool:x(t.pool),reserve_a_decimals:R(t.reserveADecimals),reserve_b_decimals:R(t.reserveBDecimals),share_decimals:R(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:M({lower_ratio_bps:R(o),upper_ratio_bps:R(n)})})};function yt(e,t){return H(e,"upgrade",[U(t.wasmHash)])}function wt(e,t){return H(e,"migrate",[R(t.newVersion)])}function bt(e){return H(e,"pause",[])}function St(e){return H(e,"unpause",[])}function vt(e,t){return H(e,"grant_role",[x(t.account),A(t.role)])}function It(e,t){return H(e,"revoke_role",[x(t.account),A(t.role)])}function xt(e,t){return H(e,"transfer_ownership",[x(t.newOwner),R(t.liveUntilLedger)])}function Tt(e){return H(e,"accept_ownership",[])}function Rt(e,t){return H(e,"set_swap_aggregator",[x(t.aggregator)])}function Bt(e,t){return H(e,"set_price_aggregator",[x(t.aggregator)])}function Et(e,t){return H(e,"set_accumulator",[x(t.accumulator)])}function _t(e,t){return H(e,"set_position_limits",[st(t)])}function At(e,t){return H(e,"approve_blend_pool",[x(t.pool)])}function kt(e,t){return H(e,"revoke_blend_pool",[x(t.pool)])}function qt(e,t){return H(e,"set_oracle",[lt(t.key),gt(t.oracle)])}function Ut(e,t){const r=t.toleranceBps,n=t.upperRatioBps??1e4+r,o=t.lowerRatioBps??Math.max(1,Math.floor(1e8/n));return H(e,"set_tolerance",[lt(t.key),M({lower_ratio_bps:R(o),upper_ratio_bps:R(n)})])}function Pt(e,t){return H(e,"set_spoke_asset_flags",[R(t.spokeId),C(t.hubId,t.asset),E(t.paused),E(t.frozen),E(t.noSeize)])}function Ot(e,t){return H(e,"set_oracle_sanity_bounds",[x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Ct(e,t){return H(e,"update_indexes",[x(e.caller),q(t.assets.map((e=>C(e.hubId,e.asset))))])}function $t(e,t){return H(e,"renew_account",[x(e.caller),B(t.accountNonce)])}function Lt(e,t){return H(e,"create_liquidity_pool",[R(t.hubId),x(t.asset),it(t.params)])}function Nt(e,t){return H(e,"upgrade_liquidity_pool_params",[C(t.hubId,t.asset),at(t.params)])}function Mt(e,t){return H(e,"claim_revenue",[x(e.caller),q(t.assets.map((e=>C(e.hubId,e.asset))))])}function Dt(e,t){return H(e,"add_rewards",[x(e.caller),L(t.rewards)])}function Wt(e,t){return H(e,"update_account_threshold",[x(e.caller),E(t.hasRisks),q(t.accountNonces.map((e=>B(e))))])}const Ft="00".repeat(32),Vt=e=>{if("string"==typeof e)return U(e);const t=l.hp.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return s.xdr.ScVal.scvBytes(t)},zt=(e,...t)=>q([A(e),...t]),Xt=e=>M({asset:x(e.asset),hub_id:R(e.hubId),params:it(e.params)}),Gt=e=>M({hub_asset:C(e.hubId,e.asset),params:at(e.params)}),jt=e=>M({new_owner:x(e.newOwner),live_until_ledger:R(e.liveUntilLedger)}),Ht=e=>M({key:lt(e.key),oracle:gt(e.oracle)}),Kt=e=>M({asset:x(e.asset),bonus:R(e.bonus),borrow_cap:T(e.borrowCap),can_borrow:E(e.canBorrow),can_collateral:E(e.canCollateral),frozen:E(e.frozen),hub_id:R(e.hubId),paused:E(e.paused),liquidation_fees:R(e.liquidationFees),ltv:R(e.ltv),no_seize:E(e.noSeize),spoke_id:R(e.spokeId),supply_cap:T(e.supplyCap),threshold:R(e.threshold)}),Zt=e=>M({hub_asset:C(e.hubId,e.asset),spoke_id:R(e.spokeId)}),Yt=e=>M({hf_for_max_bonus_wad:T(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:R(e.liquidationBonusFactorBps),spoke_id:R(e.spokeId),target_hf_wad:T(e.targetHfWad)}),Jt=e=>M({key:lt(e.key),tolerance:R(e.tolerance)}),Qt=e=>M({account:x(e.account),role:A(e.role)});function er(e,t,r){if(!e.governanceAddress)throw new Error("Stellar governanceAddress is required");const n=new s.Contract(e.governanceAddress),o=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(n.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const tr=(e,t,r)=>er(e,"propose",[x(e.caller),t,Vt(r)]),rr=(e,t,r)=>er(e,"execute_self",[k(),t,Vt(r)]);function nr(e,t,r){return tr(e,zt("SetSwapAggregator",x(t.aggregator)),r)}function or(e,t,r){return tr(e,zt("SetPriceAggregator",x(t.aggregator)),r)}function ar(e,t,r){return tr(e,zt("SetAccumulator",x(t.accumulator)),r)}function ir(e,t,r){return tr(e,zt("SetPositionLimits",st(t)),r)}function sr(e,t){return tr(e,zt("CreateHub"),t)}function lr(e,t){return tr(e,zt("AddSpoke"),t)}function ur(e,t,r){return tr(e,zt("RemoveSpoke",R(t.spokeId)),r)}function cr(e,t,r){return tr(e,zt("AddAssetToSpoke",Kt(t)),r)}function dr(e,t,r){return tr(e,zt("EditAssetInSpoke",Kt(t)),r)}function pr(e,t,r){return tr(e,zt("RemoveAssetFromSpoke",Zt(t)),r)}function fr(e,t,r){return tr(e,zt("SetSpokeLiquidationCurve",Yt(t)),r)}function hr(e,t,r){return tr(e,zt("SetPositionManager",x(t.manager),E(t.isActive)),r)}function mr(e,t,r){return tr(e,zt("SetMinBorrowCollateralUsd",T(t.floorWad)),r)}function gr(e,t,r){return tr(e,zt("ApproveToken",x(t.token)),r)}function yr(e,t,r){return tr(e,zt("RevokeToken",x(t.token)),r)}function wr(e,t,r){return tr(e,zt("ApproveBlendPool",x(t.pool)),r)}function br(e,t,r){return tr(e,zt("RevokeBlendPool",x(t.pool)),r)}function Sr(e,t,r){return tr(e,zt("CreateLiquidityPool",Xt(t)),r)}function vr(e,t,r){return tr(e,zt("UpgradeLiquidityPoolParams",Gt(t)),r)}function Ir(e,t,r){return tr(e,zt("DeployPool",U(t.wasmHash)),r)}function xr(e,t,r){return tr(e,zt("UpgradePool",U(t.wasmHash)),r)}function Tr(e,t,r){return tr(e,zt("UpgradeController",U(t.wasmHash)),r)}function Rr(e,t,r){return tr(e,zt("MigrateController",R(t.newVersion)),r)}function Br(e,t,r){return tr(e,zt("TransferCtrlOwnership",jt(t)),r)}function Er(e,t,r){return tr(e,zt("ConfigureAssetOracle",Ht(t)),r)}function _r(e,t,r){return tr(e,zt("EditOracleTolerance",Jt(t)),r)}function Ar(e,t,r){return tr(e,zt("UpgradeGov",U(t.wasmHash)),r)}function kr(e,t,r){return tr(e,zt("UpdateGovDelay",R(t.newDelay)),r)}function qr(e,t,r){return tr(e,zt("GrantGovRole",Qt(t)),r)}function Ur(e,t,r){return tr(e,zt("RevokeGovRole",Qt(t)),r)}function Pr(e,t,r){return tr(e,zt("TransferGovOwnership",jt(t)),r)}function Or(e,t){const r=q(t.argsXdr.map((e=>s.xdr.ScVal.fromXDR(e,"base64")))),n=Vt(t.predecessor??Ft);return er(e,"execute",[k(),x(t.target),A(t.functionName),r,n,Vt(t.salt)])}function Cr(e,t,r){return rr(e,zt("UpgradeGov",U(t.wasmHash)),r)}function $r(e,t,r){return rr(e,zt("UpdateGovDelay",R(t.newDelay)),r)}function Lr(e,t,r){return rr(e,zt("GrantGovRole",Qt(t)),r)}function Nr(e,t,r){return rr(e,zt("RevokeGovRole",Qt(t)),r)}function Mr(e,t,r){return rr(e,zt("TransferGovOwnership",jt(t)),r)}const Dr=e=>q(e.map(x));function Wr(e,t,r){return er(e,"propose_canceller_reset",[Dr(t.newCancellers),Vt(r)])}function Fr(e,t,r){return er(e,"execute_canceller_reset",[P(t.executor,x),Dr(t.newCancellers),Vt(r)])}function Vr(e,t){return er(e,"set_spoke_asset_flags",[x(e.caller),R(t.spokeId),C(t.hubId,t.asset),E(t.paused),E(t.frozen),E(t.noSeize)])}function zr(e,t){return er(e,"set_oracle_sanity_bounds",[x(e.caller),x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Xr(e){return er(e,"create_hub",[x(e.caller)])}function Gr(e){return er(e,"add_spoke",[x(e.caller)])}function jr(e,t){return er(e,"revoke_role_immediate",[x(t.account),A(t.role)])}function Hr(e){return er(e,"pause",[x(e.caller)])}function Kr(e,t){return tr(e,zt("Unpause"),t)}const Zr=e=>e.toXDR("base64"),Yr=e=>s.xdr.ScVal.fromXDR(e,"base64"),Jr=e=>e.map((e=>String((0,s.scValToNative)(Yr(e))))).join(":"),Qr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),en=e=>Number(e),tn=e=>String(e),rn=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),nn=["None","Multiply","Long","Short"],on=["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"],an=e=>Array.isArray(e)?e:[],sn=(e,t)=>{const r="Borrow"===t;return{action:(n=e[0],on[en(n)]??Qr(n)),positionType:t,hubId:en(e[1]),asset:tn(e[2]),scaledAmountRay:Qr(e[3]),indexRay:Qr(e[4]),amount:Qr(e[5]),liquidationThresholdBps:r?void 0:en(e[6]),liquidationBonusBps:r?void 0:en(e[7]),loanToValueBps:r?void 0:en(e[8]),liquidationFeesBps:r?void 0:en(e[9])};var n},ln=e=>{return{owner:tn(e[0]),spokeId:en(e[1]),mode:(t=e[2],nn[en(t)]??"None")};var t},un=e=>Array.isArray(e)?e[1]:void 0,cn=e=>{const t=(r=e,Array.isArray(r)?tn(r[0]):tn(r));var r;if("Token"===t)return{Token:tn(un(e))};if("Ref"===t)return{Ref:tn(un(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:tn(t.Token)};if(void 0!==t.Ref)return{Ref:tn(t.Ref)}}return{Token:tn(e)}},dn=e=>{const t=e.tolerance??{};return{assetDecimals:en(e.asset_decimals),maxPriceStaleSeconds:en(e.max_price_stale_seconds),sources:an(e.sources).map((e=>e)),tolerance:{upperRatio:en(t.upper_ratio_bps),lowerRatio:en(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Qr(e.min_sanity_price_wad),maxSanityPriceWad:Qr(e.max_sanity_price_wad)}},pn={"market:create":e=>({topic:"market:create",data:{hubId:en(e.hub_id),baseAsset:tn(e.base_asset),maxBorrowRate:Qr(e.max_borrow_rate),baseBorrowRate:Qr(e.base_borrow_rate),slope1:Qr(e.slope1),slope2:Qr(e.slope2),slope3:Qr(e.slope3),midUtilization:Qr(e.mid_utilization),optimalUtilization:Qr(e.optimal_utilization),maxUtilization:Qr(e.max_utilization),reserveFactor:en(e.reserve_factor),marketAddress:tn(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:tn(e.asset),maxBorrowRateRay:Qr(e.max_borrow_rate),baseBorrowRateRay:Qr(e.base_borrow_rate),slope1Ray:Qr(e.slope1),slope2Ray:Qr(e.slope2),slope3Ray:Qr(e.slope3),midUtilizationRay:Qr(e.mid_utilization),optimalUtilizationRay:Qr(e.optimal_utilization),maxUtilizationRay:Qr(e.max_utilization),reserveFactorBps:en(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:an(e).map((e=>{return t=an(e),{hubId:en(t[0]),asset:tn(t[1]),timestamp:en(t[2]),supplyIndexRay:Qr(t[3]),borrowIndexRay:Qr(t[4]),cash:Qr(t[5]),suppliedRay:Qr(t[6]),borrowedRay:Qr(t[7]),revenueRay:Qr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:an(e).map((e=>{const t=e;return{hubId:en(t.hub_id),asset:tn(t.asset),params:(r=t.params,{maxBorrowRateRay:Qr(r.max_borrow_rate),baseBorrowRateRay:Qr(r.base_borrow_rate),slope1Ray:Qr(r.slope1),slope2Ray:Qr(r.slope2),slope3Ray:Qr(r.slope3),midUtilizationRay:Qr(r.mid_utilization),optimalUtilizationRay:Qr(r.optimal_utilization),maxUtilizationRay:Qr(r.max_utilization),reserveFactorBps:en(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:en(r.flashloan_fee),assetId:tn(r.asset_id),assetDecimals:en(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=an(e);return{topic:"position:batch_update",data:{accountId:Qr(t[0]),accountAttributes:ln(an(t[1])),updates:[...an(t[2]).map((e=>sn(an(e),"Deposit"))),...an(t[3]).map((e=>sn(an(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:en(e.hub_id),asset:tn(e.asset),receiver:tn(e.receiver),caller:tn(e.caller),amount:Qr(e.amount),fee:Qr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:cn(e.key),oracle:dn(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:tn(e.asset),oracle:dn(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:tn(e.liquidator),accountId:Qr(e.account_id),repaidUsdWad:Qr(e.repaid_usd_wad),bonusBps:Qr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Qr(e.account_id),totalBorrowUsdWad:Qr(e.total_borrow_usd_wad),totalCollateralUsdWad:Qr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:tn(e.token),amount:Qr(e.amount),usdValueWad:Qr(e.usd_value_wad),accountId:Qr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:en(e.hub_id),asset:tn(e.asset),amount:Qr(e.amount),fee:Qr(e.fee),amountSent:Qr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:tn(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:rn(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:tn(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:tn(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:tn(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:tn(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:rn(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:en(e.max_supply_positions),maxBorrowPositions:en(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Qr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:tn(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:en(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Qr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Qr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:en(t.liquidation_bonus_factor_bps)}}}},fn=Object.freeze(Object.keys(pn));function hn(e,t){const r=Jr(e),n=pn[r];return n?n((0,s.scValToNative)(Yr(t))):null}const mn=1e4;function gn(e,t){return`${e}-${BigInt(t).toString(10)}`}function yn(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function wn(e,t=0){return e*mn+t}function bn(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 Sn=(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 vn(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=Sn(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 In(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=Sn(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 xn(e,t){const r=e[t];return"function"==typeof r?r.call(e):r}function Tn(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Rn(e){return Bn(xn(e,"bytes"))}function Bn(e){const t=e;return l.hp.from("value"in t?t.value:t)}const En=10,_n=5,An=3,kn=En+_n*b+An*S,qn=16384;class Un extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const Pn=(e,t)=>{throw new Un(e,t)},On=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*qn)return Pn("OVERSIZED",`encoded route has ${t.length} characters`);try{return Rn(X(e))}catch(e){return Pn("MALFORMED",e instanceof Error?e.message:String(e))}},Cn=e=>{let t;try{t=s.xdr.ScVal.fromXDR(e)}catch(e){return Pn("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==Tn(t))return Pn("MALFORMED","payload must be a StrategyPayload map");const r=xn(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===Tn(xn(e,"key"))?xn(xn(e,"key"),"sym").toString():"")).join(","))return Pn("MALFORMED","payload fields must be exactly amounts, assets, ops");const[n,o,a]=r.map((e=>xn(e,"val")));return"scvVec"!==Tn(n)||"scvVec"!==Tn(o)||"scvBytes"!==Tn(a)?Pn("MALFORMED","payload field has the wrong type"):{amounts:xn(n,"vec")??[],assets:xn(o,"vec")??[],ops:Rn(a)}};function $n(e){const t=On(e);0===t.length&&Pn("MALFORMED","route is empty"),t.length>qn&&Pn("OVERSIZED",`route has ${t.length} bytes, above ${qn}`);const r=Cn(t),n=r.assets.length,o=r.amounts.length;0===n&&Pn("MALFORMED","asset registry is empty"),(n>v||o>I)&&Pn("OVERSIZED",`registries hold ${n} assets and ${o} amounts`);const a=r.assets.map(((e,t)=>"scvAddress"!==Tn(e)?Pn("MALFORMED",`assets[${t}] is not an address`):s.Address.fromScAddress(xn(e,"address")).toString())),i=r.amounts.map(((e,t)=>"scvI128"!==Tn(e)?Pn("MALFORMED",`amounts[${t}] is not an i128`):(0,s.scValToBigInt)(e))),l=r.ops;l.length<En&&Pn("MALFORMED","program header is truncated"),l.length>kn&&Pn("OVERSIZED",`program has ${l.length} bytes, above ${kn}`);const x=e=>{const t=l[e];return void 0===t?Pn("MALFORMED",`program byte ${e} is missing`):t},T=x(0);T!==d&&Pn("UNSUPPORTED_VERSION",`program version ${T}, expected ${d}`);const R=x(8),B=x(9);0===R&&Pn("INVALID_STRUCTURE","program has no instructions"),(R>b||B>S)&&Pn("OVERSIZED",`program declares ${R} instructions and ${B} weights`);const E=En+_n*R;l.length!==E+An*B&&Pn("MALFORMED","program length does not match its instruction and weight counts");const _=x(1),A=x(2),k=x(3);(_>=n||A>=n||k>=o)&&Pn("MALFORMED","header index is outside its registry"),_===A&&Pn("INVALID_STRUCTURE","token_in equals token_out");const q=l.readUInt32BE(4),U=[];for(let e=0;e<B;e+=1){const t=l.readUIntBE(E+An*e,An);(0===t||t>p)&&Pn("INVALID_STRUCTURE",`split weight ${t} outside 1..=${p}`),U.push(t)}const P=e=>a[e]??Pn("MALFORMED",`asset index ${e} is outside the registry`),O=e=>i[e]??Pn("MALFORMED",`amount index ${e} is outside the registry`),C=[];let $;for(let e=0;e<R;e+=1){const t=En+_n*e,r=x(t),n=x(t+1),a=x(t+2),i=x(t+3),s=x(t+4),l=u.find((e=>c[e]===r));let d;if(l||r===f||r===h||Pn("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),n===m)d={kind:"all"};else if(n===g)void 0!==$&&$===i||Pn("INVALID_STRUCTURE",`instruction ${e} does not chain onto its predecessor`),d={kind:"prev"};else if(n>=w){const t=U[n-w];void 0===t&&Pn("MALFORMED",`instruction ${e} weight index is out of range`),d={kind:"ppm",ppm:t}}else d={kind:"fixed",amount:O(n-y)};const p=P(a);r!==f&&r!==h?(i===s&&Pn("INVALID_STRUCTURE",`instruction ${e} swaps a token for itself`),C.push({kind:"swap",venue:l,mode:d,pool:p,tokenIn:P(i),tokenOut:P(s)}),$=s):("all"!==d.kind&&Pn("MALFORMED",`liquidity instruction ${e} must use mode All`),s>=o&&Pn("MALFORMED",`instruction ${e} amount index is out of range`),C.push({kind:r===f?"burn":"mint",pool:p,shareToken:P(i),amountIndex:s}),$=r===h?i:void 0)}const L=O(k);return L<=0n&&Pn("MIN_OUT_TOO_LOW",`encoded total_min_out is ${L}`),{version:T,tokenIn:P(_),tokenOut:P(A),totalMinOut:L,referralId:q,assets:a,amounts:i,ops:C,weights:U}}function Ln(e,t){if(s.StrKey.isValidContract(e))return e;if(!t)return Pn("EXPECTATION_MISSING",`token ${e} is not a contract id; pass \`network\` to derive its asset contract`);try{const r=e.indexOf(":");return("XLM"===e||"native"===e?s.Asset.native():new s.Asset(e.slice(0,r),e.slice(r+1))).contractId(i[t])}catch{return Pn("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Nn=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):Pn("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function Mn(e,t){const r=Nn(t.minOut,"expected.minOut");r<=0n&&Pn("EXPECTATION_MISSING","expected.minOut must be positive");const n=$n(e);if(n.tokenIn!==t.tokenIn&&Pn("TOKEN_IN_MISMATCH",`route spends ${n.tokenIn}, expected ${t.tokenIn}`),n.tokenOut!==t.tokenOut&&Pn("TOKEN_OUT_MISMATCH",`route delivers ${n.tokenOut}, expected ${t.tokenOut}`),n.totalMinOut<r&&Pn("MIN_OUT_TOO_LOW",`route enforces a minimum of ${n.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Nn(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&&Pn("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return n}const Dn=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Wn=e=>W(e).toXDR("base64");function Fn(e,t){if(!e.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const r=new s.Contract(e.routerAddress),n=new s.Account(e.caller,e.sourceSequence),o=X(Dn(t,e.referralId));return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(r.call("execute_strategy",x(e.caller),T(e.totalIn),o)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function Vn(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(Xn),splitPpm:e.splitPpm}))):[{hops:e.hops.map(Xn),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function zn(e,t={}){const r=t.expected??{},n="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:Vn(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 Un("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 Un("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return Mn(n,{tokenIn:Ln(r.tokenIn??e.from,t.network),tokenOut:Ln(r.tokenOut??e.to,t.network),minOut:o,amountIn:r.amountIn??e.amountIn}),n}const Xn=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Gn(e){try{const{envelopeXdr:t,networkPassphrase:r,routerAddress:n,viewer:o,operationIndex:a}=e;if(!r||!s.StrKey.isValidContract(n)||new s.Address(o).toString()!==o||"string"!=typeof t||t.length>1048576||t.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||void 0!==a&&(!Number.isSafeInteger(a)||a<0))return null;const i=s.TransactionBuilder.fromXDR(t,r),l="innerTransaction"in i?i.innerTransaction:i;if(void 0!==a&&a>=l.operations.length)return null;let u=null;for(const[e,t]of l.operations.entries()){if(void 0!==a&&e!==a)continue;if("invokeHostFunction"!==t.type)continue;const r=t.func;if("hostFunctionTypeInvokeContract"!==Tn(r))continue;const i=xn(r,"invokeContract");if(s.Address.fromScAddress(xn(i,"contractAddress")).toString()!==n||"execute_strategy"!==xn(i,"functionName").toString())continue;const l=xn(i,"args"),[c,d,p]=l;if(3!==l.length||!c||!d||!p||"scvAddress"!==Tn(c)||"scvI128"!==Tn(d)||"scvBytes"!==Tn(p))return null;if(s.Address.fromScAddress(xn(c,"address")).toString()!==o)continue;const f=(0,s.scValToBigInt)(d);if(f<=0n)return null;const h=$n(Rn(p));if(h.tokenIn===h.tokenOut||!s.StrKey.isValidContract(h.tokenIn)||!s.StrKey.isValidContract(h.tokenOut))return null;if(u)return null;u={tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountInAtoms:f.toString(),operationIndex:e}}return u}catch{return null}}class jn 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 Hn=e=>e&&"scvAddress"===Tn(e)?s.Address.fromScAddress(xn(e,"address")).toString():void 0,Kn=e=>e&&"scvI128"===Tn(e)?(0,s.scValToBigInt)(e):void 0,Zn=e=>e&&"scvVec"===Tn(e)?xn(e,"vec")??[]:void 0,Yn=(e,t)=>{if(!e||"scvMap"!==Tn(e))return;const r=(xn(e,"map")??[]).find((e=>"scvSymbol"===Tn(xn(e,"key"))&&xn(xn(e,"key"),"sym").toString()===t));return r?xn(r,"val"):void 0},Jn=e=>Hn(e)??Kn(e)?.toString()??e.toXDR("base64"),Qn=e=>({contract:s.Address.fromScAddress(xn(e,"contractAddress")).toString(),fn:xn(e,"functionName").toString(),args:xn(e,"args").map(Jn)}),eo=e=>{const t=xn(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===Tn(t)?xn(t,"contractFn"):void 0};function to(e,t,r){const n=e.filter((e=>{const n=xn(e,"credentials"),o=Tn(n);if("sorobanCredentialsAddress"!==o&&"sorobanCredentialsSourceAccount"!==o)throw new jn("MALFORMED_TRANSACTION","unsupported authorization credentials");return("sorobanCredentialsAddress"===o?s.Address.fromScAddress(xn(xn(n,"address"),"address")).toString():r??t.caller)===t.caller}));if(n.length>1)throw new jn("DUPLICATE_ENTRY",`${n.length} authorization entries for ${t.caller}, expected one`);const o=n[0];if(!o)return;const a=eo(xn(o,"rootInvocation"));if(!a)throw new jn("UNEXPECTED_ROOT","root is not a contract call");const i=Qn(a);if(i.contract!==t.root.contract||i.fn!==t.root.fn)throw new jn("UNEXPECTED_ROOT",`expected ${t.root.contract}.${t.root.fn}`,i);const l=t.transfers.map((()=>0n)),u=(t.calls??[]).map((()=>0));for(const e of xn(xn(o,"rootInvocation"),"subInvocations")){const r=eo(e);if(!r)throw new jn("UNEXPECTED_CALL","sub-invocation is not a contract call");const n=Qn(r);if(xn(e,"subInvocations").length>0)throw new jn("NESTED_INVOCATION","sub-invocation carries its own sub-invocations",n);const o=(t.calls??[]).findIndex((e=>e.contract===n.contract&&e.fn===n.fn));if(-1!==o){const e=(t.calls??[])[o],a=e.reject(xn(r,"args"));if(a)throw new jn("UNEXPECTED_CALL",a,n);if(u[o]=(u[o]??0)+1,(u[o]??0)>e.maxCount)throw new jn("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,n);continue}if("transfer"!==n.fn||3!==xn(r,"args").length)throw new jn("UNEXPECTED_CALL","only `transfer` is allowed",n);if(!t.transfers.some((e=>e.token===n.contract)))throw new jn("UNEXPECTED_TOKEN","transfer on an unexpected token",n);const[a,i,s]=xn(r,"args");if(Hn(a)!==t.caller)throw new jn("UNEXPECTED_SENDER","transfer is not from the caller",n);const c=Hn(i),d=t.transfers.findIndex((e=>e.token===n.contract&&e.to===c));if(-1===d)throw new jn("UNEXPECTED_RECIPIENT","transfer to an unexpected recipient",n);const p=Kn(s),f=t.transfers[d],h=(l[d]??0n)+(p??0n);if(void 0===p||p<=0n||h>f.maxAmount)throw new jn("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,n);l[d]=h}}const ro=e=>{throw new jn("MALFORMED_TRANSACTION",e)},no=(e,t)=>{const r=new Map;for(const t of Zn(e)??ro("payments argument is not a vector")){const[e,n]=Zn(t)??[],o=Hn(Yn(e,"asset")),a=Kn(n);if(void 0===o||void 0===a||a<0n)return ro("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})))},oo=new Set([1,3,5]),ao=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(Hn(e[0])!==t)return"`from` is not the caller";if(Hn(e[1])!==r||Hn(e[2])!==r)return"`spender` and `to` must be the lending controller";const n=Zn(e[3]);if(!n)return"requests is not a vector";for(const e of n){const t=Yn(e,"request_type");if(!t||"scvU32"!==Tn(t)||!oo.has(xn(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function io(e,t,r){const{contract:n,fn:o}=Qn(t),a=xn(t,"args"),i={caller:e,root:{contract:n,fn:o},transfers:[]};if(n===r.governance)return i;if(n===r.aggregatorRouter){if("execute_strategy"!==o)return i;const t=Kn(a[1]);if(Hn(a[0])!==e||void 0===t||"scvBytes"!==Tn(a[2]))return ro("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=$n(Rn(a[2]));return i.transfers=[{token:r.tokenIn,to:n,maxAmount:t}],i}if(n!==r.lendingController)throw new jn("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${n}; pass an explicit policy`);if(Hn(a[0])!==e)throw new jn("CALLER_MISMATCH",`${o} is not invoked for ${e}`);switch(o){case"supply":i.transfers=no(a[3],r.lendingPool);break;case"repay":case"liquidate":i.transfers=no(a[2],r.lendingPool);break;case"multiply":{const e=a[8];e&&"scvVoid"!==Tn(e)&&(i.transfers=no(s.xdr.ScVal.scvVec([e]),n));break}case"migrate_from_blend":{const t=Hn(a[4])??ro("blend_pool is not an address");i.calls=[ao(t,e,n)];break}}return i}const so=e=>{let t;try{t=s.xdr.TransactionEnvelope.fromXDR(e,"base64")}catch{return ro("not a transaction envelope")}if("envelopeTypeTx"!==Tn(t))return ro("expected a regular (v1) transaction");const r=xn(xn(t,"v1"),"tx"),n=xn(r,"operations")[0];if(!n||1!==xn(r,"operations").length)return ro("expected exactly one operation");const o=xn(n,"body");if("invokeHostFunction"!==Tn(o))return ro("operation is not a contract invocation");const a=xn(o,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==Tn(xn(a,"hostFunction"))?ro("host function is not a contract call"):{source:(i=xn(n,"sourceAccount")??xn(r,"sourceAccount"),s.StrKey.encodeEd25519PublicKey(Bn("keyTypeMuxedEd25519"===Tn(i)?xn(xn(i,"med25519"),"ed25519"):xn(i,"ed25519")))),op:a,call:xn(xn(a,"hostFunction"),"invokeContract")};var i};function lo(e,t){const r=so(e);if(void 0!==t.builtXdr&&xn(so(t.builtXdr).op,"hostFunction").toXDR("base64")!==xn(r.op,"hostFunction").toXDR("base64"))throw new jn("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",Qn(r.call));const n=t.policy??io(t.caller,r.call,{...a(t.network),...t.deployment});to(xn(r.op,"auth"),n,r.source)}function uo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function co(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=s.TransactionBuilder.fromXDR(t,r?.network?i[r.network]:"");try{const t=await e.simulateTransaction(o,{cpuInstructions:n});if(s.rpc.Api.isSimulationError(t))throw new Error(t.error);return s.rpc.assembleTransaction(o,t).build().toXDR()}catch(e){if(r?.invokedContractId)throw uo(r.invokedContractId,e);throw e}}async function po(e,t,r){return co(e,t.xdr,r)}function fo(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 ho(e,t){return new Uint8Array(0)}const mo=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 l.hp.from(t,"hex")};function go(e){const t=new s.Account(e.caller,e.sourceSequence),r=new s.Contract(e.forwarderAddress).call("mint_and_forward",s.xdr.ScVal.scvBytes(mo(e.message)),s.xdr.ScVal.scvBytes(mo(e.attestation)));return{xdr:new s.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const yo=10n**27n,wo=10n**18n,bo=10000n,So=27,vo=18;function Io(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 xo(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function To(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 Ro(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function Bo(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 Eo=e=>10n**BigInt(e);function _o(e,t,r){return t===r?e:r>t?e*Eo(r-t):e/Eo(t-r)}function Ao(e,t,r){if(t===r)return e;if(r>t)return e*Eo(r-t);const n=Eo(t-r),o=e/n;return e%n===0n?o:o+1n}function ko(e,t,r){return t===r?e:r>t?e*Eo(r-t):Bo(e,Eo(t-r))}const qo={floor:xo,ceil:To,halfUp:Ro},Uo={floor:_o,ceil:Ao,halfUp:ko};function Po(e,t,r,n){return Uo[n](qo[n](e,t,yo),So,r)}function Oo(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"floor")}function Co(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"ceil")}function $o(e,t,r){return Po(Io(e,"scaledRay"),Io(t,"indexRay"),r,"halfUp")}function Lo(e,t){if(t>So)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return _o(e,t,So)}function No(e,t,r,n){const o=qo[n](e,t,yo),a=Uo[n](o,So,vo);return qo[n](a,r,wo)}function Mo(e,t,r,n){const o=Uo[n](Lo(e,t),So,vo);return qo[n](o,r,wo)}const Do=e=>Number(e)/1e18,Wo=e=>Number(e)/1e27,Fo=(e,t)=>Number(e)/10**t;function Vo(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 zo=e=>Vo(e,vo),Xo=(e,t)=>Ro(e,t,yo),Go=(e,t)=>Ro(e,yo,t);function jo(e,t){return 0n===t?0n:Go(e,t)}function Ho(e,t){const r=e>yo?yo:e,n=Io(t.baseRateRay,"irm.baseRateRay"),o=Io(t.slope1Ray,"irm.slope1Ray"),a=Io(t.slope2Ray,"irm.slope2Ray"),i=Io(t.slope3Ray,"irm.slope3Ray"),s=Io(t.midUtilizationRay,"irm.midUtilizationRay"),l=Io(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),u=Io(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<s)c=n+Go(Xo(r,o),s);else if(r<l){const e=l-s;c=n+o+Go(Xo(r-s,a),e)}else{const e=yo-l;c=n+o+a+(0n===e?0n:Go(Xo(r-l,i),e))}return c>u?u:c}function Ko(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:Ro(Xo(e,t),bo-BigInt(r),bo)}const Zo=e=>Wo(e),Yo=e=>Math.expm1(Wo(e)),Jo=5n*wo,Qo=(e,t,r)=>`${e}:${t}:${r}`;function ea(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[Qo(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 ${Qo(t,r,n)}`);return a}const ta=/^0*[1-9]\d*$/,ra=e=>"string"==typeof e&&ta.test(e)?BigInt(e).toString():null,na=(e,t)=>`${e}:${t}`;function oa(e){const t=new Map,r=new Map,n=new Set,o=new Set;for(const a of e?.indexes??[]){const e=na(a.hubId,a.asset),i=ra(a.supplyIndex),s=ra(a.borrowIndex),l=ra(a.usdPrice),u=t.get(e),c=u&&ra(u.supplyIndex)===i&&ra(u.borrowIndex)===s&&ra(u.usdPrice)===l;null==i||null==s||null==l||u&&!c?n.add(e):u||t.set(e,a);const d=!1===a.valid||!0===a.stale||!0===a.deviation,p=r.get(a.asset);null==l||d||void 0!==p&&p.toString()!==l?o.add(a.asset):void 0===p&&r.set(a.asset,BigInt(l))}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 aa=(e,t)=>xo(e,BigInt(t),bo);function ia(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:Do(e.priceWad),amountBase:t.toString(),amountShort:Fo(t,e.decimals),usdWad:r.toString(),usd:Do(r),gateUsdWad:n.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:o?aa(n,a).toString():"0",liquidationWeightedUsdWad:o?aa(n,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function sa(e){if("supply"===e.side)return ia(e,Po(e.scaledRay,e.indexRay,e.decimals,"floor"),No(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),No(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Po(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=No(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ia(e,t,r,r)}function la(e,t,r,n){const o=Lo(t,r);return"supply"===e?xo(o,yo,n):To(o,yo,n)}function ua(e,t,r,n){const o=Lo(t,r);return"supply"===e?To(o,yo,n):xo(o,yo,n)}function ca(e,t){return sa({...e,scaledRay:la(e.side,t,e.decimals,e.indexRay)})}const da=(...e)=>{for(const t of e){const e=ra(t);if(null!=e)return BigInt(e)}return yo};function pa(e,t,r,n){const o=Io("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===o)return null;const a=n.indexes.get(na(t.hubId,t.asset)),i=n.prices.get(t.asset),s="supply"===e?da(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):da(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),l=i??zo(r.usdPrice);return sa({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:o,indexRay:s,priceWad:l,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==a&&void 0!==i})}const fa=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function ha(e,t,r,n,o){const a=fa(t,(e=>e.usdWad)),i=fa(t,(e=>e.ltvWeightedUsdWad)),s=fa(t,(e=>e.liquidationWeightedUsdWad)),l=fa(r,(e=>e.usdWad)),u=0n===l?null:xo(s,wo,l),c=0n===s?0:Number(l)/Number(s)*100,d=i<n||i<=l?0n:i-l;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:a.toString(),totalCollateralUsd:Do(a),ltvWeightedCollateralUsdWad:i.toString(),ltvWeightedCollateralUsd:Do(i),liquidationWeightedCollateralUsdWad:s.toString(),liquidationWeightedCollateralUsd:Do(s),totalDebtUsdWad:l.toString(),totalDebtUsd:Do(l),healthFactorWad:null===u?null:u.toString(),healthFactor:null===u?null:Do(u),healthPercent:c,borrowLimitUsdWad:i.toString(),borrowLimitUsd:Do(i),availableBorrowUsdWad:d.toString(),availableBorrowUsd:Do(d),minBorrowCollateralUsdWad:n.toString(),minBorrowCollateralUsd:Do(n),isLiquidatable:null!==u&&u<wo,liveDataValid:o}}function ma(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=oa(n),i=[],s=[];for(const e of t){const t=ea(r,e.spokeId,e.hubId,e.asset),n=pa("supply",e,t,a);n&&i.push(n);const o=pa("borrow",e,t,a);o&&s.push(o)}const l=null!=n?.minBorrowCollateralUsdWad?Io(n.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):Jo,u=void 0!==n&&[...i,...s].every((e=>e.liveDataUsed));return ha({accountId:o.accountId,owner:o.owner,spokeId:o.spokeId,mode:o.positionMode},i,s,l,u)}const ga=200n,ya=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),wa=e=>e<0n?0n:e,ba=(e,t,r,n)=>({amountBase:e.amount,amountShort:Fo(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:n}),Sa=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function va(e){const t=e.assetDecimals,r=Io(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:Vo(e.hubPool.suppliedShort,t),borrowedBase:Vo(e.hubPool.borrowedShort,t),cashBase:Vo(e.availableLiquidityShort,t),spokeSuppliedBase:Vo(e.suppliedShort,t),spokeBorrowedBase:Vo(e.borrowedShort,t),maxUtilizationRay:r>=yo?null:r}}const Ia=(e,t)=>e<=0n?null:Number(t)/Number(e);function xa(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 Ta=16n,Ra=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Ba(e,t,r){if(t.paused)return Sa("paused");if(t.frozen)return Sa("frozen");if(!t.isBorrowable)return Sa("cap");const n=t.assetDecimals,o=va(t),a=Ra(e.borrows,t),i=oa(r).indexes.get(na(t.hubId,t.asset)),s=a?BigInt(a.indexRay):Io(i?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),l=a?BigInt(a.usdPriceWad):function(e,t){return oa(t).prices.get(e.asset)??zo(e.usdPrice)}(t,r),u=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||l<=0n?0n:xo(t,10n**BigInt(n),l),o=e=>c+No(u+la("borrow",e,n,s),s,l,"ceil");f.push({amount:0n===r?0n:xa(r+Ta,(e=>o(e)<=d)),reason:"ltv"})}f.push({amount:wa(Io(t.borrowCap,"borrowCap")-o.spokeBorrowedBase),reason:"cap"});const h=Ro(o.suppliedBase,ga,bo);f.push({amount:wa(o.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const n=Lo(e.suppliedBase,t);return 0n===n?null:xa(wa(xo(e.suppliedBase,r,yo)-e.borrowedBase)+Ta,(o=>jo(Lo(e.borrowedBase+o,t),n)<=r))}(o,n);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=ya(f);return ba(g,n,!1,Ia(o.suppliedBase,o.borrowedBase+g.amount))}function Ea(e,t,r){if(t.paused)return Sa("paused");const n=Ra(e.supplies,t);if(!n)return Sa(null);const o=n.decimals,a=va(t),i=BigInt(n.scaledRay),s=BigInt(n.indexRay),l=BigInt(n.usdPriceWad),u=BigInt(n.amountBase),c=Po(i,s,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,u=To(e,bo,f),d=BigInt(n.gateUsdWad)-u,p=d<=0n?0n:xo(d,10n**BigInt(o),l),g=c>0n?c-1n:0n,y=p+Ta>g?g:p+Ta,w=e=>{const t=ua("supply",e,o,s);return xo(No(t>=i?0n:i-t,s,l,"floor"),f,bo)};h.push({amount:xa(y,(t=>w(t)>=e)),reason:r})}}h.push({amount:u,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=To(e.borrowedBase,yo,r),o=e.suppliedBase<n?0n:e.suppliedBase-n+Ta,a=Lo(e.borrowedBase,t);return xa(o>e.suppliedBase?e.suppliedBase:o,(n=>{const o=Lo(e.suppliedBase-n,t);return o>0n&&jo(a,o)<=r}))}(a,o);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=ya(h),w=m&&y.amount>=u;return ba(y,o,w,Ia(a.suppliedBase-y.amount,a.borrowedBase))}function _a(e){if(e.paused)return Sa("paused");if(e.frozen)return Sa("frozen");const t=e.assetDecimals,r=va(e),n={amount:wa(Io(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return ba(n,t,!1,Ia(r.suppliedBase+n.amount,r.borrowedBase))}function Aa(e,t,r){if(t.paused)return Sa("paused");const n=Ra(e.borrows,t);if(!n)return Sa(null);const o=n.decimals,a=va(t),i=BigInt(n.amountBase),s=void 0===r?null:Io(r,"walletBalance"),l=null!==s&&s<i?{amount:s,reason:"liquidity"}:{amount:i,reason:null};return ba(l,o,l.amount>=i,Ia(a.suppliedBase,wa(a.borrowedBase-l.amount)))}const ka=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,qa=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 Ua(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=>ka(t,e))),a=-1===o?void 0:t[o],i=qa(e.amountBase);let s;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(i>=0n)r=t+la(e.side,i,e.decimals,e.indexRay);else{const n=-i,o=n>=("supply"===e.side?Po(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:ua(e.side,n,e.decimals,e.indexRay);r=o>=t?0n:t-o}s=0n===r?null:sa({...e,scaledRay:r})}else s=i<=0n?null:ca(Pa(e),i);-1===o?s&&t.push(s):s?t[o]=s:t.splice(o,1)}return ha({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,n,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Pa(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:Io("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:zo(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function Oa(e,t=0n,r=0n){const n=e.assetDecimals,o=e=>e<0n?0n:e,a=o(Vo(e.hubPool.suppliedShort,n)+qa(t)),i=jo(Lo(o(Vo(e.hubPool.borrowedShort,n)+qa(r)),n),Lo(a,n)),s=Ho(i,e.irm),l=Ko(i,s,e.irm.reserveFactorBps);return{utilization:Wo(i),utilizationRay:i.toString(),borrowAprRay:s.toString(),supplyAprRay:l.toString(),borrowApr:Zo(s),supplyApr:Zo(l),borrowApy:Yo(s),supplyApy:Yo(l)}}const Ca={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."},6:{name:"InvalidAsset",message:"Invalid asset address."},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."},14:{name:"AmountMustBePositive",message:"The amount must be greater than zero."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},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."},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."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},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."}};function $a(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),n=Ca[r];return n?{code:r,...n}:null}})(),module.exports=n})();