@xoxno/sdk-js 1.0.229 → 1.0.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see index.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","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})();
2
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{var e={526(e,t){"use strict";t.byteLength=function(e){var t=i(e),r=t[0],o=t[1];return 3*(r+o)/4-o},t.toByteArray=function(e){var t,r,a=i(e),s=a[0],l=a[1],u=new n(function(e,t,r){return 3*(t+r)/4-r}(0,s,l)),c=0,d=l>0?s-4:s;for(r=0;r<d;r+=4)t=o[e.charCodeAt(r)]<<18|o[e.charCodeAt(r+1)]<<12|o[e.charCodeAt(r+2)]<<6|o[e.charCodeAt(r+3)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===l&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===l&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,o=e.length,n=o%3,a=[],s=16383,i=0,u=o-n;i<u;i+=s)a.push(l(e,i,i+s>u?u:i+s));return 1===n?(t=e[o-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===n&&(t=(e[o-2]<<8)+e[o-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")};for(var r=[],o=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=a[s],o[a.charCodeAt(s)]=s;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,o){for(var n,a,s=[],i=t;i<o;i+=3)n=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),s.push(r[(a=n)>>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const o=r(526),n=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,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 o=i(r);const n=o.write(e,t);return n!==r&&(o=o.slice(0,n)),o}(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 o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return l.from(o,t,r);const n=function(e){if(l.isBuffer(e)){const t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?i(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(n)return n;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),i(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=i(t);for(let o=0;o<t;o+=1)r[o]=255&e[o];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 o;return o=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(o,l.prototype),o}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function m(e,t){if(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,o=arguments.length>2&&!0===arguments[2];if(!o&&0===r)return 0;let n=!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 H(e).length;default:if(n)return o?-1:G(e).length;t=(""+t).toLowerCase(),n=!0}}function g(e,t,r){let o=!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 R(this,t,r);case"ascii":return B(this,t,r);case"latin1":case"binary":return E(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,r);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function y(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function w(e,t,r,o,n){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=l.from(t,o)),l.isBuffer(t))return 0===t.length?-1:b(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,o,n){let a,s=1,i=e.length,l=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s=2,i/=2,l/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let o=-1;for(a=r;a<i;a++)if(u(e,a)===u(t,-1===o?0:a-o)){if(-1===o&&(o=a),a-o+1===l)return o*s}else-1!==o&&(a-=a-o),o=-1}else for(r+l>i&&(r=i-l),a=r;a>=0;a--){let r=!0;for(let o=0;o<l;o++)if(u(e,a+o)!==u(t,o)){r=!1;break}if(r)return a}return-1}function S(e,t,r,o){r=Number(r)||0;const n=e.length-r;o?(o=Number(o))>n&&(o=n):o=n;const a=t.length;let s;for(o>a/2&&(o=a/2),s=0;s<o;++s){const o=parseInt(t.substr(2*s,2),16);if(Z(o))return s;e[r+s]=o}return s}function v(e,t,r,o){return j(G(t,e.length-r),e,r,o)}function _(e,t,r,o){return j(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,o)}function I(e,t,r,o){return j(H(t),e,r,o)}function T(e,t,r,o){return j(function(e,t){let r,o,n;const a=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),o=r>>8,n=r%256,a.push(n),a.push(o);return a}(t,e.length-r),e,r,o)}function x(e,t,r){return 0===t&&r===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,r))}function R(e,t,r){r=Math.min(e.length,r);const o=[];let n=t;for(;n<r;){const t=e[n];let a=null,s=t>239?4:t>223?3:t>191?2:1;if(n+s<=r){let r,o,i,l;switch(s){case 1:t<128&&(a=t);break;case 2:r=e[n+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[n+1],o=e[n+2],128==(192&r)&&128==(192&o)&&(l=(15&t)<<12|(63&r)<<6|63&o,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[n+1],o=e[n+2],i=e[n+3],128==(192&r)&&128==(192&o)&&128==(192&i)&&(l=(15&t)<<18|(63&r)<<12|(63&o)<<6|63&i,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),n+=s}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=A));return r}(o)}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?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(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,o=t.length;for(let n=0,a=Math.min(r,o);n<a;++n)if(e[n]!==t[n]){r=e[n],o=t[n];break}return r<o?-1:o<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 o=l.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(K(t,Uint8Array))n+t.length>o.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(o,n)):Uint8Array.prototype.set.call(o,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(o,n)}n+=t.length}return o},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?R(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,o,n){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===o&&(o=0),void 0===n&&(n=this.length),t<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(o>=n&&t>=r)return 0;if(o>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let a=(n>>>=0)-(o>>>=0),s=(r>>>=0)-(t>>>=0);const i=Math.min(a,s),u=this.slice(o,n),c=e.slice(t,r);for(let e=0;e<i;++e)if(u[e]!==c[e]){a=u[e],s=c[e];break}return a<s?-1:s<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,o){if(void 0===t)o="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)o=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===o&&(o="utf8")):(o=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let a=!1;for(;;)switch(o){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 _(this,e,t,r);case"base64":return I(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: "+o);o=(""+o).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function B(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(127&e[n]);return o}function E(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(e[n]);return o}function k(e,t,r){const o=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>o)&&(r=o);let n="";for(let o=t;o<r;++o)n+=Y[e[o]];return n}function q(e,t,r){const o=e.slice(t,r);let n="";for(let e=0;e<o.length-1;e+=2)n+=String.fromCharCode(o[e]+256*o[e+1]);return n}function P(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 U(e,t,r,o,n,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<a)throw new RangeError('"value" argument is out of bounds');if(r+o>e.length)throw new RangeError("Index out of range")}function C(e,t,r,o,n){W(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function O(e,t,r,o,n){W(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r+7]=a,a>>=8,e[r+6]=a,a>>=8,e[r+5]=a,a>>=8,e[r+4]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function N(e,t,r,o,n,a){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,o,a){return t=+t,r>>>=0,a||N(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function $(e,t,r,o,a){return t=+t,r>>>=0,a||N(e,0,r,8),n.write(e,t,r,o,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 o=this.subarray(e,t);return Object.setPrototypeOf(o,l.prototype),o},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return o},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e+--t],n=1;for(;t>0&&(n*=256);)o+=this[e+--t]*n;return o},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(o)+(BigInt(n)<<BigInt(32))})),l.prototype.readBigUInt64BE=Q((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(o)<<BigInt(32))+BigInt(n)})),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=t,n=1,a=this[e+--o];for(;o>0&&(n*=256);)a+=this[e+--o]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||P(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||P(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||P(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||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),l.prototype.readBigInt64BE=Q((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||U(this,e,t,r,Math.pow(2,8*r)-1,0);let n=1,a=0;for(this[t]=255&e;++a<r&&(n*=256);)this[t+a]=e/n&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||U(this,e,t,r,Math.pow(2,8*r)-1,0);let n=r-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||U(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||U(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||U(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||U(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||U(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=Q((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=Q((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);U(this,e,t,r,o-1,-o)}let n=0,a=1,s=0;for(this[t]=255&e;++n<r&&(a*=256);)e<0&&0===s&&0!==this[t+n-1]&&(s=1),this[t+n]=(e/a|0)-s&255;return t+r},l.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);U(this,e,t,r,o-1,-o)}let n=r-1,a=1,s=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/a|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||U(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||U(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||U(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||U(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||U(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=Q((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=Q((function(e,t=0){return O(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 $(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return $(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,o){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o<r&&(o=r),o===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(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t<o-r&&(o=e.length-t+r);const n=o-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,o):Uint8Array.prototype.set.call(e,this.subarray(r,o),t),n},l.prototype.fill=function(e,t,r,o){if("string"==typeof e){if("string"==typeof t?(o=t,t=0,r=this.length):"string"==typeof r&&(o=r,r=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!l.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===e.length){const t=e.charCodeAt(0);("utf8"===o&&t<128||"latin1"===o)&&(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 n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const a=l.isBuffer(e)?e:l.from(e,o),s=a.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=a[n%s]}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 F(e){let t="",r=e.length;const o="-"===e[0]?1:0;for(;r>=o+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,o,n,a){if(e>r||e<t){const o="bigint"==typeof t?"n":"";let n;throw n=a>3?0===t||t===BigInt(0)?`>= 0${o} and < 2${o} ** ${8*(a+1)}${o}`:`>= -(2${o} ** ${8*(a+1)-1}${o}) and < 2 ** ${8*(a+1)-1}${o}`:`>= ${t}${o} and <= ${r}${o}`,new M.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(o,n,a)}function z(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw z(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 o=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=F(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=F(n)),n+="n"),o+=` It must be ${t}. Received ${n}`,o}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function G(e,t){let r;t=t||1/0;const o=e.length;let n=null;const a=[];for(let s=0;s<o;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(s+1===o){(t-=3)>-1&&a.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&a.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(e){return o.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 j(e,t,r,o){let n;for(n=0;n<o&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}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 o=16*r;for(let n=0;n<16;++n)t[o+n]=e[r]+e[n]}return t}();function Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}},251(e,t){t.read=function(e,t,r,o,n){var a,s,i=8*n-o-1,l=(1<<i)-1,u=l>>1,c=-7,d=r?n-1:0,p=r?-1:1,f=e[t+d];for(d+=p,a=f&(1<<-c)-1,f>>=-c,c+=i;c>0;a=256*a+e[t+d],d+=p,c-=8);for(s=a&(1<<-c)-1,a>>=-c,c+=o;c>0;s=256*s+e[t+d],d+=p,c-=8);if(0===a)a=1-u;else{if(a===l)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,o),a-=u}return(f?-1:1)*s*Math.pow(2,a-o)},t.write=function(e,t,r,o,n,a){var s,i,l,u=8*a-n-1,c=(1<<u)-1,d=c>>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=o?0:a-1,h=o?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,s=c):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?p/l:p*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=c?(i=0,s=c):s+d>=1?(i=(t*l-1)*Math.pow(2,n),s+=d):(i=t*Math.pow(2,d-1)*Math.pow(2,n),s=0));n>=8;e[r+f]=255&i,f+=h,i/=256,n-=8);for(s=s<<n|i,u+=n;u>0;e[r+f]=255&s,f+=h,s/=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 o={type:"string"},n={type:"number"},a={type:"boolean"},s={...o,nullable:!0},i={...n,nullable:!0},l={...o,enum:["mainnet","testnet"]},u={...o,enum:["ready","stale","incomplete"]};function c(e){return{type:"object",required:Object.keys(e),properties:e}}const d={sac:o,symbol:o,name:o,decimals:i,logoUrl:s},p=c({valid:a,stale:a,deviation:a,timestamp:i}),f=c({...d,hubId:n,hubName:o,amountRaw:{...s,description:"Integer token base units, never scaled shares."},amount:s,apy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,valueUsd:i,priceStatus:p,indexRay:s,indexedAt:n,indexedLedger:n}),h=c({amountRaw:s,amount:s,usd:i}),m=c({spokeId:n,spokeName:o,ltvBps:n,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:o,nftContract:o,nftImage:{...o,format:"uri",description:"Dynamic position SVG served by the network's XOXNO API."},network:l,spokeId:i,spokeName:s,supplied:{type:"array",items:f},borrow:{type:"array",items:f},hasDebt:{...a,nullable:!0,description:"Null when account rows are unavailable."},healthFactor:{...i,description:"Null without debt or when risk inputs are unavailable."},borrowLimitUsd:i,availableBorrowUsd:{...i,description:"Account headroom, before per-market constraints."},netApy:{...i,description:"Net annual yield divided by positive net equity; fraction."},dataStatus:u})},y={type:"array",items:c({...d,hubId:n,hubName:o,network:l,supplyApy:{...i,description:"Fraction: 0.05 means 5%."},borrowApy:{...i,description:"Fraction: 0.05 means 5%."},priceUsd:i,priceStatus:p,spokes:{type:"array",items:m},dataStatus:u,indexedAt:{...n,description:"Pool state timestamp. Capacities are indexed snapshot estimates; prepare/simulate before signing."},indexedLedger:n})};function w(e){if(!e)return;const t=/\s*<([^<>\s]+)>\s*((?:;\s*[\w!#$%&'*+.^`|~-]+\s*=\s*(?:"(?:[^"\\\r\n]|\\.)*"|[\w!#$%&'*+.^`|~:/-]+)\s*)*)(,|$)/gy;let r,o=0;for(;o<e.length;){const n=t.exec(e);if(!n||n[3]&&t.lastIndex===e.length)throw new Error("Invalid pagination Link header");let a=!1,s=!1;for(const e of n[2].matchAll(/;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\.)*)"|([\w!#$%&'*+.^`|~:/-]+))\s*/g))if("rel"===e[1].toLowerCase()){if(s)throw new Error("Duplicate pagination link relation");s=!0,a=(e[2]??e[3]).replace(/\\(.)/g,"$1").toLowerCase().split(/\s+/).includes("next")}if(a){if(void 0!==r)throw new Error("Multiple next pagination links");r=n[1]}o=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 o(e,o){const n=new URL(`stellar-lending/v1/${e}`,t);let a=n;const s=new Set,i=[];for(;;){if(s.has(a.href))throw new Error("Pagination Link cycle");s.add(a.href);const e=await r(a.href,{signal:o,redirect:"error"});if(e.redirected||e.url&&new URL(e.url).href!==a.href)throw new Error("Stellar lending redirects are not allowed");if(!e.ok)throw new Error(`Stellar lending request failed: HTTP ${e.status}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Stellar lending response must be an array");i.push(...t);const l=w(e.headers.get("Link"));if(!l)break;const u=new URL(l,a);if(u.origin!==n.origin||u.pathname!==n.pathname||u.username||u.password||u.hash)throw new Error("Pagination Link must stay on the same API endpoint");a=u}return i}return{assets:({usage:e,signal:t}={})=>{if(void 0!==e&&"collateral"!==e&&"borrow"!==e)throw new Error("usage must be collateral or borrow");return o("assets"+(e?`?usage=${e}`:""),t)},positions:(e,{signal:t}={})=>{if(!e.trim()||"."===e||".."===e)throw new Error("owner is required");return o(`users/${encodeURIComponent(e)}/positions`,t)}}}},928(e,t,r){"use strict";r.d(t,{sW:()=>s,GW:()=>i});const o="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",n="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",a="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e";var s;!function(e){e.MAINNET="1",e.DEVNET="D"}(s||(s={}));class i{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=s.MAINNET,apiUrl:r,...i}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=i,this.config=t==s.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",FM_SC:o,DR_SC:n,KG_SC:a,Staking_SC:"erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",Manager_SC:"erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",P2P_SC:"erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6"}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:"erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",FM_SC:o,DR_SC:n,KG_SC:a,Staking_SC:"erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",Manager_SC:"erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",P2P_SC:"erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:o,cache:n,debug:a,timeout:s,...i}=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,..._}=o??{},{revalidate:I,...T}=l??{},x="GET"!==f||g?void 0:I??v,R="GET"!==f||g||x?void 0:u??n,A=h.body,B=d??s??(null==A?3e4:0),E=B>0?AbortSignal.timeout(B):void 0,k=h.signal??i.signal,q=E&&k?AbortSignal.any([k,E]):E??k,P={...i,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:R,next:{..._,...T,revalidate:x}};(c??a)&&console.debug("SDK fetch: ",S,P);const U=await fetch(S,P).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${S}: ${e.message}`),{cause:e});throw e})),C=await U.text();if(!U.ok){let e;try{e=JSON.parse(C)}catch{e={message:C}}const t=[S,U.status,U.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(C)}catch{return C}}}}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={exports:{}};return e[o](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},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 o={};(()=>{"use strict";r.r(o),r.d(o,{BPS:()=>In,DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD:()=>ra,LIQUIDATION_BUFFER_BPS:()=>Sa,RAY:()=>vn,RAY_DECIMALS:()=>Tn,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Gt,STELLAR_LENDING_TOPICS:()=>yo,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>s,STELLAR_ROUTE_MAX_BYTES:()=>Oo,SYNTHETIC_EVENT_ORDER_STRIDE:()=>bo,StellarAuthPolicyError:()=>Yo,StellarRouteVerificationError:()=>No,WAD:()=>_n,WAD_DECIMALS:()=>xn,XOXNOClient:()=>e.GW,aggregateAccountRisk:()=>wa,annualBorrowRateRay:()=>Qn,assertStellarAuthEntries:()=>an,assertStellarPreparedTxAuth:()=>fn,baseToRay:()=>Fn,baseToShort:()=>Gn,baseValueWad:()=>zn,buildLiveSnapshot:()=>la,buildSameTokenRepaySwapSteps:()=>wn,buildStellarAcceptOwnershipTx:()=>Bt,buildStellarAddRewardsTx:()=>Vt,buildStellarApproveBlendPoolTx:()=>Ut,buildStellarBorrowBatchTx:()=>Q,buildStellarBorrowTx:()=>J,buildStellarCctpForwardTx:()=>Sn,buildStellarClaimRevenueTx:()=>zt,buildStellarCreateLiquidityPoolTx:()=>Ft,buildStellarExecuteCancellerResetTx:()=>Gr,buildStellarExecuteStrategyTx:()=>Go,buildStellarFlashLoanTx:()=>ue,buildStellarGovernanceAddSpokeImmediateTx:()=>Zr,buildStellarGovernanceCreateHubImmediateTx:()=>Kr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>Mr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Fr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Wr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>zr,buildStellarGovernanceExecuteTx:()=>$r,buildStellarGovernanceExecuteUpdateDelayTx:()=>Dr,buildStellarGovernancePauseTx:()=>Qr,buildStellarGovernanceRevokeRoleImmediateTx:()=>Yr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>jr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Hr,buildStellarGrantRoleTx:()=>xt,buildStellarLendingIdentifier:()=>So,buildStellarLiquidateTx:()=>ne,buildStellarLiquidationEstimateTx:()=>se,buildStellarMigrateFromBlendTx:()=>ce,buildStellarMigrateTx:()=>_t,buildStellarMultiplyTx:()=>de,buildStellarPauseTx:()=>It,buildStellarProposeAddAssetToSpokeTx:()=>hr,buildStellarProposeAddSpokeTx:()=>pr,buildStellarProposeApproveBlendPoolTx:()=>_r,buildStellarProposeApproveTokenTx:()=>Sr,buildStellarProposeCancellerResetTx:()=>Xr,buildStellarProposeConfigureAssetOracleTx:()=>qr,buildStellarProposeCreateHubTx:()=>dr,buildStellarProposeCreateLiquidityPoolTx:()=>Tr,buildStellarProposeDeployPoolTx:()=>Rr,buildStellarProposeEditAssetInSpokeTx:()=>mr,buildStellarProposeEditOracleToleranceTx:()=>Pr,buildStellarProposeGovernanceUpgradeTx:()=>Ur,buildStellarProposeGrantGovernanceRoleTx:()=>Or,buildStellarProposeMigrateControllerTx:()=>Er,buildStellarProposeRemoveAssetFromSpokeTx:()=>gr,buildStellarProposeRemoveSpokeTx:()=>fr,buildStellarProposeRevokeBlendPoolTx:()=>Ir,buildStellarProposeRevokeGovernanceRoleTx:()=>Nr,buildStellarProposeRevokeTokenTx:()=>vr,buildStellarProposeSetAccumulatorTx:()=>ur,buildStellarProposeSetMinBorrowCollatTx:()=>br,buildStellarProposeSetPositionLimitsTx:()=>cr,buildStellarProposeSetPositionManagerTx:()=>wr,buildStellarProposeSetPriceAggregatorTx:()=>lr,buildStellarProposeSetSpokeLiquidationCurveTx:()=>yr,buildStellarProposeSetSwapAggregatorTx:()=>ir,buildStellarProposeTransferCtrlOwnershipTx:()=>kr,buildStellarProposeTransferGovOwnTx:()=>Lr,buildStellarProposeUnpauseTx:()=>Jr,buildStellarProposeUpdateDelayTx:()=>Cr,buildStellarProposeUpgradeControllerTx:()=>Br,buildStellarProposeUpgradePoolParamsTx:()=>xr,buildStellarProposeUpgradePoolTx:()=>Ar,buildStellarRenewAccountTx:()=>Dt,buildStellarRepayBatchTx:()=>re,buildStellarRepayDebtWithCollateralTx:()=>he,buildStellarRepayTx:()=>oe,buildStellarRevokeBlendPoolTx:()=>Ct,buildStellarRevokeRoleTx:()=>Rt,buildStellarSetAccumulatorTx:()=>qt,buildStellarSetOracleSanityBoundsTx:()=>$t,buildStellarSetOracleToleranceTx:()=>Nt,buildStellarSetOracleTx:()=>Ot,buildStellarSetPositionLimitsTx:()=>Pt,buildStellarSetPriceAggregatorTx:()=>kt,buildStellarSetSpokeAssetFlagsTx:()=>Lt,buildStellarSetSwapAggregatorTx:()=>Et,buildStellarSupplyBatchTx:()=>Z,buildStellarSupplyTx:()=>Y,buildStellarSwapCollateralTx:()=>fe,buildStellarSwapDebtTx:()=>pe,buildStellarTransferOwnershipTx:()=>At,buildStellarUnpauseTx:()=>Tt,buildStellarUpdateAccountThresholdTx:()=>Xt,buildStellarUpdateIndexesTx:()=>Mt,buildStellarUpgradeControllerTx:()=>vt,buildStellarUpgradeLiquidityPoolParamsTx:()=>Wt,buildStellarWithdrawBatchTx:()=>ee,buildStellarWithdrawTx:()=>te,buildTx:()=>j,burnShares:()=>fa,computeAccountRisk:()=>ba,createStellarLendingReadClient:()=>lt.createStellarLendingReadClient,decodeStellarLendingEvent:()=>wo,decodeStellarLiquidateReturn:()=>ae,decodeStellarLiquidationEstimate:()=>le,decodeStellarRouteBytes:()=>Do,decodeStellarSwapEnvelope:()=>Zo,depositRateRay:()=>Jn,divByIntHalfUp:()=>kn,encodeAssetOracle:()=>St,encodeInterestRateModel:()=>ut,encodeMarketParamsRaw:()=>ct,encodePositionLimits:()=>dt,encodePriceKey:()=>pt,encodeStrategyPayloadToRouteXdr:()=>Xo,extractEventOrder:()=>vo,getStellarAccountPositions:()=>Ee,getStellarActiveUsersSeries:()=>et,getStellarAggregatorQuote:()=>xo,getStellarAsset:()=>xe,getStellarAssetGraph:()=>Le,getStellarAssetMarkets:()=>Ue,getStellarAssetPage:()=>Pe,getStellarAssets:()=>Se,getStellarCampaignLeaderboard:()=>je,getStellarCampaignMe:()=>st,getStellarDefiLlamaDimensions:()=>rt,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>be,getStellarFeeRevenueSeries:()=>Ye,getStellarGovernanceProposals:()=>ze,getStellarHolderDistribution:()=>He,getStellarHub:()=>Re,getStellarHubGraph:()=>$e,getStellarHubHolders:()=>Oe,getStellarHubs:()=>ve,getStellarLendingContext:()=>ye,getStellarLendingLiveState:()=>we,getStellarLiquidationsLeaderboard:()=>Ge,getStellarLiquidationsSeries:()=>Qe,getStellarParticipantCounts:()=>Xe,getStellarPnlByScope:()=>at,getStellarPositionsLeaderboard:()=>Ve,getStellarPositionsPnl:()=>nt,getStellarQuoteTokens:()=>Ro,getStellarRateSpreadSeries:()=>tt,getStellarReserve:()=>Te,getStellarReserveGraph:()=>De,getStellarReserveHolders:()=>Ce,getStellarReserves:()=>Ie,getStellarRevenueSeries:()=>Ze,getStellarSpoke:()=>Ae,getStellarSpokeGraph:()=>Me,getStellarSpokeHolders:()=>Ne,getStellarSpokes:()=>_e,getStellarStatsHistory:()=>Ke,getStellarUserActivity:()=>Fe,getStellarUserActivityPage:()=>We,getStellarUserHistory:()=>ot,getStellarUserPositions:()=>Be,getStellarVolumeSeries:()=>Je,getStellarWalletBalance:()=>qe,getStellarWalletTokens:()=>ke,lendingAssetsSchema:()=>lt.lendingAssetsSchema,lendingPositionsSchema:()=>lt.lendingPositionsSchema,liveIndexKey:()=>ia,mapQuoteResponseToStrategyPayload:()=>Ho,mapQuoteResponseToStrategySwap:()=>jo,mapSorobanError:()=>Xa,mapStellarPositionActivityType:()=>Io,maxBorrow:()=>ka,maxRepay:()=>Ua,maxSupply:()=>Pa,maxWithdraw:()=>qa,mintShares:()=>pa,mulDivCeil:()=>Bn,mulDivFloor:()=>An,mulDivHalfUp:()=>En,numberToScaled:()=>Hn,numberToWad:()=>jn,parseStellarTokenAmount:()=>H,positionValueWad:()=>Wn,prepareStellarBuiltTx:()=>gn,prepareStellarTxXdr:()=>mn,projectAccountRisk:()=>Na,projectReserveApy:()=>$a,rayAprToApy:()=>ta,rayAprToNumber:()=>ea,rayToNumber:()=>Xn,rescaleCeil:()=>Un,rescaleFloor:()=>Pn,rescaleHalfUp:()=>Cn,reserveKey:()=>oa,resolveReserve:()=>na,stellarAuthPolicyForInvocation:()=>dn,stellarLendingDispatchKey:()=>ro,stellarLendingRead:()=>it,stellarNetworks:()=>n,stellarTokenContractId:()=>Fo,syntheticEventOrder:()=>_o,tagStellarInvokedContractError:()=>hn,toBase64Xdr:()=>eo,toBigInt:()=>Rn,toStellarPositionMode:()=>yn,unscale:()=>Ln,unscaleBorrowCeil:()=>Mn,unscaleHalfUp:()=>Dn,unscaleSupplyFloor:()=>$n,utilizationRay:()=>Yn,valueBasePosition:()=>ha,valueScaledPosition:()=>da,verifyStellarRouteBytes:()=>zo,wadToNumber:()=>Vn});var e=r(928);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:"CBMARXSYE56NPDLX42TTICM5GS5XQCYRD5VMCJME624TS6C2S53VETYU",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},n=t;function a(e){return t["testnet"===e?"stellarTestnet":"stellarMainnet"]}const s={mainnet:t.stellarMainnet.passphrase,testnet:t.stellarTestnet.passphrase},i=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,_=w-y,I=e=>new i.Address(e).toScVal(),T=e=>new i.ScInt(e).toI128(),x=e=>i.xdr.ScVal.scvU32(e),R=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 i.ScInt("string"==typeof e?e:e.toString()).toU64()},A=e=>i.xdr.ScVal.scvBool(e),B=e=>i.xdr.ScVal.scvString(e),E=e=>i.xdr.ScVal.scvSymbol(e),k=()=>i.xdr.ScVal.scvVoid(),q=e=>i.xdr.ScVal.scvVec(e),P=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=l.hp.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.xdr.ScVal.scvBytes(o)},U=(e,t)=>null==e?k():t(e),C=e=>i.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,i.xdr.ScVal.scvVec([I(t),T(r)]);var t,r}))),O=(e,t)=>M({asset:I(t),hub_id:x(e)}),N=(e,t,r)=>i.xdr.ScVal.scvVec([O(e,t),T(r)]),L=e=>i.xdr.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),$=e=>{if("Transfer"===e)return q([E("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([E("Credit"),R(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 i.xdr.ScMapEntry({key:E(t),val:e[t]})));return i.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>=_)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,o,n){this.ops.push([e,t,r,o,n])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const n=e.hops[o-1];if(n&&r.tokenIn!==n.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(c[r.venue],0===o?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 o=t[e].hops[0]?.tokenIn,n=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&n.push(r);const a=n.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 s=a===p;let i=p;n.forEach(((e,o)=>{r[e]=!0;const a=t[e];let l;if(o+1===n.length&&s)l=m;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(a.splitPpm*p/i);i-=Math.min(a.splitPpm,i),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 o=[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)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return l.hp.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const F=e=>{const t=new D(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),n=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(f,m,o,r,n)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[n,a]=o,[s,i]=e.preSwapFromA?[n,a]:[a,n];t.emit(c.Aquarius,y+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(h,m,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const n=Number(e.referralId??0);if(!Number.isInteger(n)||n<0||n>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return M({amounts:i.xdr.ScVal.scvVec(t.amountList.map((e=>T(e)))),assets:i.xdr.ScVal.scvVec(t.assetList.map((e=>I(e)))),ops:i.xdr.ScVal.scvBytes(t.toBytes(r,o,n))})},W=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 i.xdr.ScVal.scvBytes(t)},z=()=>i.xdr.ScVal.scvBytes(l.hp.alloc(0)),V=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 o=l.hp.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},X=e=>{if("string"==typeof e)return W(V(e));if(e instanceof Uint8Array)return 0===e.length?z():W(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?W(V(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?W(V(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?W(V(e.bytes)):0===e.bytes.length?z():W(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,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.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 o.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=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above ${p}`);if(!t.mintPool&&o!==p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to ${p}, got ${o}`)}return t})(e),i.xdr.ScVal.scvBytes(l.hp.from(F(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 i.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return i.xdr.ScVal.scvBytes(l.hp.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function H(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=i.Soroban.parseTokenAmount(e,t),o=BigInt(r);if(o<=0n||o>(1n<<127n)-1n)throw new Error("Token amount must be within the positive i128 range");return r}function j(e,t,r){if(!e.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const o=new i.Contract(e.controllerAddress),n=new i.Account(e.caller,e.sourceSequence);return{xdr:new i.TransactionBuilder(n,{fee:e.fee??i.BASE_FEE,networkPassphrase:s[e.network]}).addOperation(o.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 x(e)}function Z(e,t){const r=t.accountNonce??0;return j(e,"supply",[I(e.caller),R(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 Q(e,t){return j(e,"borrow",[I(e.caller),R(t.accountNonce),L([...t.borrows]),U(t.to,I)])}function J(e,t){return Q(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function ee(e,t){return j(e,"withdraw",[I(e.caller),R(t.accountNonce),L([...t.withdrawals]),U(t.to,I)])}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 j(e,"repay",[I(e.caller),R(t.accountNonce),L([...t.payments])])}function oe(e,t){return re(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function ne(e,t){return j(e,"liquidate",[I(e.caller),R(t.accountNonce),L([...t.debtPayments]),$(t.seizeMode??"Transfer")])}function ae(e){const t=(0,i.scValToNative)(i.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 se(e,t){return j(e,"get_liquidation_estimate",[R(t.accountNonce),L([...t.debtPayments]),$(t.seizeMode??"Transfer")])}const ie=e=>(Array.isArray(e)?e:[]).map((e=>{const t=e;return{asset:String(t.asset),amount:String(t.amount)}}));function le(e){const t=(0,i.scValToNative)(i.xdr.ScVal.fromXDR(e,"base64"));if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Stellar builder: liquidation estimate must be a struct");return{seizedCollaterals:ie(t.seized_collaterals),protocolFees:ie(t.protocol_fees),refunds:ie(t.refunds),maxPaymentWad:String(t.max_payment_wad),bonusRateBps:String(t.bonus_rate_bps)}}function ue(e,t){return j(e,"flash_loan",[I(e.caller),O(t.hubId,t.asset),T(t.amount),I(t.receiver),G(t.data)])}function ce(e,t){return j(e,"migrate_from_blend",[I(e.caller),R(t.accountId),K(t.spokeId),x(t.hubId),I(t.blendPool),q(t.collateralTokens.map(I)),q(t.supplyTokens.map(I)),C(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function de(e,t){const r=t.accountNonce??0;return j(e,"multiply",[I(e.caller),R(r),K(t.spokeId),O(t.collateral.hubId,t.collateral.asset),T(t.debtToFlashLoan),O(t.debt.hubId,t.debt.asset),x(t.mode),X(t.steps),U(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),U(t.convertSwap,X)])}function pe(e,t){return j(e,"swap_debt",[I(e.caller),R(t.accountNonce),O(t.existingDebt.hubId,t.existingDebt.asset),T(t.newDebtAmount),O(t.newDebt.hubId,t.newDebt.asset),X(t.steps)])}function fe(e,t){return j(e,"swap_collateral",[I(e.caller),R(t.accountNonce),O(t.current.hubId,t.current.asset),T(t.fromAmount),O(t.newCollateral.hubId,t.newCollateral.asset),X(t.steps)])}function he(e,t){return j(e,"repay_debt_with_collateral",[I(e.caller),R(t.accountNonce),O(t.collateral.hubId,t.collateral.asset),T(t.collateralAmount),O(t.debt.hubId,t.debt.asset),X(t.steps),A(t.closePosition)])}const me="/stellar-lending",ge=encodeURIComponent,ye=(e,t)=>e.fetchWithTimeout(`${me}/context`,t),we=(e,t)=>e.fetchWithTimeout(`${me}/live-state`,t),be=(e,t)=>e.fetchWithTimeout(`${me}/markets/detailed`,t),Se=(e,t)=>e.fetchWithTimeout(`${me}/assets`,t),ve=(e,t)=>e.fetchWithTimeout(`${me}/hubs`,t),_e=(e,t)=>e.fetchWithTimeout(`${me}/spokes`,t),Ie=(e,t={},r)=>e.fetchWithTimeout(`${me}/reserves`,{...r,params:{...t}}),Te=(e,t,r,o,n)=>e.fetchWithTimeout(`${me}/reserves/${t}/${r}/${ge(o)}`,n),xe=(e,t,r)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}`,r),Re=(e,t,r)=>e.fetchWithTimeout(`${me}/hubs/${t}`,r),Ae=(e,t,r)=>e.fetchWithTimeout(`${me}/spokes/${t}`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/positions`,r),Ee=(e,t,r)=>e.fetchWithTimeout(`${me}/accounts/${ge(t)}/positions`,r),ke=(e,t,r)=>e.fetchWithTimeout(`/user/${ge(t)}/token-inventory`,r),qe=async(t,r,o,n)=>{const a=await ke(t,r,n),s=t.chain===e.sW.MAINNET?"mainnet":"testnet",i=(a?.tokens??[]).find((e=>e.identifier===o));if(i)return{owner:r,network:i.stellarNetwork??s,asset:o,amount:String(i.balance),decimals:i.decimals};const{decimals:l}=await xe(t,o,n);if("number"!=typeof l)throw new Error(`Stellar lending: no decimals for ${o}; it is not a lending asset`);return{owner:r,network:s,asset:o,amount:"0",decimals:l}},Pe=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/page`,{...o,params:{...r}}),Ue=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/markets`,{...o,params:{side:r}}),Ce=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${me}/reserves/${t}/${r}/${ge(o)}/holders`,{...a,params:{side:n}}),Oe=(e,t,r,o)=>e.fetchWithTimeout(`${me}/hubs/${t}/holders`,{...o,params:{side:r}}),Ne=(e,t,r,o)=>e.fetchWithTimeout(`${me}/spokes/${t}/holders`,{...o,params:{side:r}}),Le=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/graph`,{...o,params:{...r}}),$e=(e,t,r,o)=>e.fetchWithTimeout(`${me}/hubs/${t}/graph`,{...o,params:{...r}}),Me=(e,t,r,o)=>e.fetchWithTimeout(`${me}/spokes/${t}/graph`,{...o,params:{...r}}),De=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${me}/reserves/${t}/${r}/${ge(o)}/graph`,{...a,params:{...n}}),Fe=(e,t,r={},o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/activity`,{...o,params:{...r}}),We=(e,t,r={},o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/activity/page`,{...o,params:{...r}}),ze=(e,t={},r)=>e.fetchWithTimeout(`${me}/governance/proposals`,{...r,params:{...t}}),Ve=(e,t={},r)=>e.fetchWithTimeout(`${me}/positions`,{...r,params:{...t}}),Xe=(e,t={},r)=>e.fetchWithTimeout(`${me}/participants`,{...r,params:{...t}}),Ge=(e,t={},r)=>e.fetchWithTimeout(`${me}/liquidations/leaderboard`,{...r,params:{...t}}),He=(e,t={},r)=>e.fetchWithTimeout(`${me}/distribution`,{...r,params:{...t}}),je=(e,t={},r)=>e.fetchWithTimeout(`${me}/campaign/leaderboard`,{...r,params:{...t}}),Ke=(e,t,r)=>e.fetchWithTimeout(`${me}/stats/history`,{...r,params:{...t}}),Ze=(e,t,r)=>e.fetchWithTimeout(`${me}/revenue`,{...r,params:{...t}}),Ye=(e,t,r)=>e.fetchWithTimeout(`${me}/revenue/fees`,{...r,params:{...t}}),Qe=(e,t,r)=>e.fetchWithTimeout(`${me}/liquidations`,{...r,params:{...t}}),Je=(e,t,r)=>e.fetchWithTimeout(`${me}/volume`,{...r,params:{...t}}),et=(e,t,r)=>e.fetchWithTimeout(`${me}/active-users`,{...r,params:{...t}}),tt=(e,t,r)=>e.fetchWithTimeout(`${me}/rate-spread`,{...r,params:{...t}}),rt=(e,t,r)=>e.fetchWithTimeout(`${me}/defillama`,{...r,params:{...t}}),ot=(e,t,r,o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/history`,{...o,params:{...r}}),nt=(e,t,r)=>e.fetchWithTimeout(`${me}/pnl`,{...r,params:{accountId:t}}),at=(e,t,r)=>e.fetchWithTimeout(`${me}/pnl/scope`,{...r,params:{scope:t}}),st=(e,t,r)=>e.fetchWithTimeout(`${me}/campaign/me`,{...r,params:{owner:t}}),it=e=>({context:t=>ye(e,t),liveState:t=>we(e,t),marketsDetailed:t=>be(e,t),assets:t=>Se(e,t),hubs:t=>ve(e,t),spokes:t=>_e(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?Ie(e,t,r):Ie(e,{},t),reserve:(t,r,o,n)=>Te(e,t,r,o,n),asset:(t,r)=>xe(e,t,r),hub:(t,r)=>Re(e,t,r),spoke:(t,r)=>Ae(e,t,r),userPositions:(t,r)=>Be(e,t,r),accountPositions:(t,r)=>Ee(e,t,r),walletTokens:(t,r)=>ke(e,t,r),walletBalance:(t,r,o)=>qe(e,t,r,o),assetPage:(t,r,o)=>Pe(e,t,r,o),assetMarkets:(t,r,o)=>Ue(e,t,r,o),reserveHolders:(t,r,o,n,a)=>Ce(e,t,r,o,n,a),hubHolders:(t,r,o)=>Oe(e,t,r,o),spokeHolders:(t,r,o)=>Ne(e,t,r,o),assetGraph:(t,r,o)=>Le(e,t,r,o),hubGraph:(t,r,o)=>$e(e,t,r,o),spokeGraph:(t,r,o)=>Me(e,t,r,o),reserveGraph:(t,r,o,n,a)=>De(e,t,r,o,n,a),userActivity:(t,r={},o)=>Fe(e,t,r,o),userActivityPage:(t,r={},o)=>We(e,t,r,o),governanceProposals:(t={},r)=>ze(e,t,r),positionsLeaderboard:(t={},r)=>Ve(e,t,r),participants:(t={},r)=>Xe(e,t,r),liquidationsLeaderboard:(t={},r)=>Ge(e,t,r),distribution:(t={},r)=>He(e,t,r),campaignLeaderboard:(t={},r)=>je(e,t,r),statsHistory:(t,r)=>Ke(e,t,r),revenue:(t,r)=>Ze(e,t,r),feeRevenue:(t,r)=>Ye(e,t,r),liquidations:(t,r)=>Qe(e,t,r),volume:(t,r)=>Je(e,t,r),activeUsers:(t,r)=>et(e,t,r),rateSpread:(t,r)=>tt(e,t,r),defillama:(t,r)=>rt(e,t,r),userHistory:(t,r,o)=>ot(e,t,r,o),positionsPnl:(t,r)=>nt(e,t,r),pnlByScope:(t,r)=>at(e,t,r),campaignMe:(t,r)=>st(e,t,r)});var lt=r(468);const ut=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:x(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),ct=e=>M({asset_decimals:x(e.assetDecimals),asset_id:I(e.assetId),base_borrow_rate:T(e.baseBorrowRateRay),flashloan_fee:x(e.flashloanFeeBps),is_flashloanable:A(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:x(e.reserveFactorBps),slope1:T(e.slope1Ray),slope2:T(e.slope2Ray),slope3:T(e.slope3Ray)}),dt=e=>M({max_borrow_positions:x(e.maxBorrowPositions),max_supply_positions:x(e.maxSupplyPositions)}),pt=e=>{if("Token"in e&&e.Token)return q([E("Token"),I(e.Token)]);if("Ref"in e&&e.Ref)return q([E("Ref"),E(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},ft=e=>{if("Stellar"in e)return q([E("Stellar"),I(e.Stellar)]);if("Symbol"in e)return q([E("Symbol"),E(e.Symbol)]);if("String"in e)return q([E("String"),B(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},ht=e=>{if("Spot"===e)return q([E("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return q([E("Twap"),x(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},mt=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return q([E(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},gt=e=>{if("Market"===e||"Fundamental"===e)return q([E(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},yt=e=>{if("Reflector"in e){const t=e.Reflector;return q([E("Reflector"),M({asset:ft(t.asset),contract:I(t.contract),read_mode:ht(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return q([E("MultiFeed"),M({contract:I(t.contract),feed_id:B(t.feedId),kind:mt(t.kind),nature:gt(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},wt=e=>{const t=e;return M({decimals:x(t.decimals),max_stale_seconds:R(t.maxStaleSeconds),provider:yt(t.provider)})},bt=e=>{if("RequireDisjoint"===e)return q([E("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return q([E("AllowShared"),q(t.map((e=>M({contract:I(e.contract),kind:mt(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},St=e=>{const t=e,r=t.sources??[];let o,n;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,n=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),n=Number(e.lowerRatioBps)}return M({asset_decimals:x(Number(t.assetDecimals)),independence:bt(t.independence),max_price_stale_seconds:R(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([E("Feed"),wt(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return q([E("Scaled"),M({factor:wt(t.factor),max_factor_wad:T(t.maxFactorWad),min_factor_wad:T(t.minFactorWad),quote:pt(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return q([E("LpShare"),M({key_a:pt(t.keyA),key_b:pt(t.keyB),kind:q([E(t.kind||"ConstantProduct")]),pool:I(t.pool),reserve_a_decimals:x(t.reserveADecimals),reserve_b_decimals:x(t.reserveBDecimals),share_decimals:x(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:M({lower_ratio_bps:x(n),upper_ratio_bps:x(o)})})};function vt(e,t){return j(e,"upgrade",[P(t.wasmHash)])}function _t(e,t){return j(e,"migrate",[x(t.newVersion)])}function It(e){return j(e,"pause",[])}function Tt(e){return j(e,"unpause",[])}function xt(e,t){return j(e,"grant_role",[I(t.account),E(t.role)])}function Rt(e,t){return j(e,"revoke_role",[I(t.account),E(t.role)])}function At(e,t){return j(e,"transfer_ownership",[I(t.newOwner),x(t.liveUntilLedger)])}function Bt(e){return j(e,"accept_ownership",[])}function Et(e,t){return j(e,"set_swap_aggregator",[I(t.aggregator)])}function kt(e,t){return j(e,"set_price_aggregator",[I(t.aggregator)])}function qt(e,t){return j(e,"set_accumulator",[I(t.accumulator)])}function Pt(e,t){return j(e,"set_position_limits",[dt(t)])}function Ut(e,t){return j(e,"approve_blend_pool",[I(t.pool)])}function Ct(e,t){return j(e,"revoke_blend_pool",[I(t.pool)])}function Ot(e,t){return j(e,"set_oracle",[pt(t.key),St(t.oracle)])}function Nt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,n=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return j(e,"set_tolerance",[pt(t.key),M({lower_ratio_bps:x(n),upper_ratio_bps:x(o)})])}function Lt(e,t){return j(e,"set_spoke_asset_flags",[x(t.spokeId),O(t.hubId,t.asset),A(t.paused),A(t.frozen),A(t.noSeize)])}function $t(e,t){return j(e,"set_oracle_sanity_bounds",[I(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Mt(e,t){return j(e,"update_indexes",[I(e.caller),q(t.assets.map((e=>O(e.hubId,e.asset))))])}function Dt(e,t){return j(e,"renew_account",[I(e.caller),R(t.accountNonce)])}function Ft(e,t){return j(e,"create_liquidity_pool",[x(t.hubId),I(t.asset),ct(t.params)])}function Wt(e,t){return j(e,"upgrade_liquidity_pool_params",[O(t.hubId,t.asset),ut(t.params)])}function zt(e,t){return j(e,"claim_revenue",[I(e.caller),q(t.assets.map((e=>O(e.hubId,e.asset))))])}function Vt(e,t){return j(e,"add_rewards",[I(e.caller),L(t.rewards)])}function Xt(e,t){return j(e,"update_account_threshold",[I(e.caller),A(t.hasRisks),q(t.accountNonces.map((e=>R(e))))])}const Gt="00".repeat(32),Ht=e=>{if("string"==typeof e)return P(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 i.xdr.ScVal.scvBytes(t)},jt=(e,...t)=>q([E(e),...t]),Kt=e=>M({asset:I(e.asset),hub_id:x(e.hubId),params:ct(e.params)}),Zt=e=>M({hub_asset:O(e.hubId,e.asset),params:ut(e.params)}),Yt=e=>M({new_owner:I(e.newOwner),live_until_ledger:x(e.liveUntilLedger)}),Qt=e=>M({key:pt(e.key),oracle:St(e.oracle)}),Jt=e=>M({asset:I(e.asset),bonus:x(e.bonus),borrow_cap:T(e.borrowCap),can_borrow:A(e.canBorrow),can_collateral:A(e.canCollateral),frozen:A(e.frozen),hub_id:x(e.hubId),paused:A(e.paused),liquidation_fees:x(e.liquidationFees),ltv:x(e.ltv),no_seize:A(e.noSeize),spoke_id:x(e.spokeId),supply_cap:T(e.supplyCap),threshold:x(e.threshold)}),er=e=>M({hub_asset:O(e.hubId,e.asset),spoke_id:x(e.spokeId)}),tr=e=>M({hf_for_max_bonus_wad:T(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:x(e.liquidationBonusFactorBps),spoke_id:x(e.spokeId),target_hf_wad:T(e.targetHfWad)}),rr=e=>M({key:pt(e.key),tolerance:x(e.tolerance)}),or=e=>M({account:I(e.account),role:E(e.role)});function nr(e,t,r){if(!e.governanceAddress)throw new Error("Stellar governanceAddress is required");const o=new i.Contract(e.governanceAddress),n=new i.Account(e.caller,e.sourceSequence);return{xdr:new i.TransactionBuilder(n,{fee:e.fee??i.BASE_FEE,networkPassphrase:s[e.network]}).addOperation(o.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const ar=(e,t,r)=>nr(e,"propose",[I(e.caller),t,Ht(r)]),sr=(e,t,r)=>nr(e,"execute_self",[k(),t,Ht(r)]);function ir(e,t,r){return ar(e,jt("SetSwapAggregator",I(t.aggregator)),r)}function lr(e,t,r){return ar(e,jt("SetPriceAggregator",I(t.aggregator)),r)}function ur(e,t,r){return ar(e,jt("SetAccumulator",I(t.accumulator)),r)}function cr(e,t,r){return ar(e,jt("SetPositionLimits",dt(t)),r)}function dr(e,t){return ar(e,jt("CreateHub"),t)}function pr(e,t){return ar(e,jt("AddSpoke"),t)}function fr(e,t,r){return ar(e,jt("RemoveSpoke",x(t.spokeId)),r)}function hr(e,t,r){return ar(e,jt("AddAssetToSpoke",Jt(t)),r)}function mr(e,t,r){return ar(e,jt("EditAssetInSpoke",Jt(t)),r)}function gr(e,t,r){return ar(e,jt("RemoveAssetFromSpoke",er(t)),r)}function yr(e,t,r){return ar(e,jt("SetSpokeLiquidationCurve",tr(t)),r)}function wr(e,t,r){return ar(e,jt("SetPositionManager",I(t.manager),A(t.isActive)),r)}function br(e,t,r){return ar(e,jt("SetMinBorrowCollateralUsd",T(t.floorWad)),r)}function Sr(e,t,r){return ar(e,jt("ApproveToken",I(t.token)),r)}function vr(e,t,r){return ar(e,jt("RevokeToken",I(t.token)),r)}function _r(e,t,r){return ar(e,jt("ApproveBlendPool",I(t.pool)),r)}function Ir(e,t,r){return ar(e,jt("RevokeBlendPool",I(t.pool)),r)}function Tr(e,t,r){return ar(e,jt("CreateLiquidityPool",Kt(t)),r)}function xr(e,t,r){return ar(e,jt("UpgradeLiquidityPoolParams",Zt(t)),r)}function Rr(e,t,r){return ar(e,jt("DeployPool",P(t.wasmHash)),r)}function Ar(e,t,r){return ar(e,jt("UpgradePool",P(t.wasmHash)),r)}function Br(e,t,r){return ar(e,jt("UpgradeController",P(t.wasmHash)),r)}function Er(e,t,r){return ar(e,jt("MigrateController",x(t.newVersion)),r)}function kr(e,t,r){return ar(e,jt("TransferCtrlOwnership",Yt(t)),r)}function qr(e,t,r){return ar(e,jt("ConfigureAssetOracle",Qt(t)),r)}function Pr(e,t,r){return ar(e,jt("EditOracleTolerance",rr(t)),r)}function Ur(e,t,r){return ar(e,jt("UpgradeGov",P(t.wasmHash)),r)}function Cr(e,t,r){return ar(e,jt("UpdateGovDelay",x(t.newDelay)),r)}function Or(e,t,r){return ar(e,jt("GrantGovRole",or(t)),r)}function Nr(e,t,r){return ar(e,jt("RevokeGovRole",or(t)),r)}function Lr(e,t,r){return ar(e,jt("TransferGovOwnership",Yt(t)),r)}function $r(e,t){const r=q(t.argsXdr.map((e=>i.xdr.ScVal.fromXDR(e,"base64")))),o=Ht(t.predecessor??Gt);return nr(e,"execute",[k(),I(t.target),E(t.functionName),r,o,Ht(t.salt)])}function Mr(e,t,r){return sr(e,jt("UpgradeGov",P(t.wasmHash)),r)}function Dr(e,t,r){return sr(e,jt("UpdateGovDelay",x(t.newDelay)),r)}function Fr(e,t,r){return sr(e,jt("GrantGovRole",or(t)),r)}function Wr(e,t,r){return sr(e,jt("RevokeGovRole",or(t)),r)}function zr(e,t,r){return sr(e,jt("TransferGovOwnership",Yt(t)),r)}const Vr=e=>q(e.map(I));function Xr(e,t,r){return nr(e,"propose_canceller_reset",[Vr(t.newCancellers),Ht(r)])}function Gr(e,t,r){return nr(e,"execute_canceller_reset",[U(t.executor,I),Vr(t.newCancellers),Ht(r)])}function Hr(e,t){return nr(e,"set_spoke_asset_flags",[I(e.caller),x(t.spokeId),O(t.hubId,t.asset),A(t.paused),A(t.frozen),A(t.noSeize)])}function jr(e,t){return nr(e,"set_oracle_sanity_bounds",[I(e.caller),I(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function Kr(e){return nr(e,"create_hub",[I(e.caller)])}function Zr(e){return nr(e,"add_spoke",[I(e.caller)])}function Yr(e,t){return nr(e,"revoke_role_immediate",[I(t.account),E(t.role)])}function Qr(e){return nr(e,"pause",[I(e.caller)])}function Jr(e,t){return ar(e,jt("Unpause"),t)}const eo=e=>e.toXDR("base64"),to=e=>i.xdr.ScVal.fromXDR(e,"base64"),ro=e=>e.map((e=>String((0,i.scValToNative)(to(e))))).join(":"),oo=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),no=e=>Number(e),ao=e=>String(e),so=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),io=["None","Multiply","Long","Short"],lo=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit","flash_pos"],uo=e=>Array.isArray(e)?e:[],co=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],lo[no(o)]??oo(o)),positionType:t,hubId:no(e[1]),asset:ao(e[2]),scaledAmountRay:oo(e[3]),indexRay:oo(e[4]),amount:oo(e[5]),liquidationThresholdBps:r?void 0:no(e[6]),liquidationBonusBps:r?void 0:no(e[7]),loanToValueBps:r?void 0:no(e[8]),liquidationFeesBps:r?void 0:no(e[9])};var o},po=e=>{return{owner:ao(e[0]),spokeId:no(e[1]),mode:(t=e[2],io[no(t)]??"None")};var t},fo=e=>Array.isArray(e)?e[1]:void 0,ho=e=>{const t=(r=e,Array.isArray(r)?ao(r[0]):ao(r));var r;if("Token"===t)return{Token:ao(fo(e))};if("Ref"===t)return{Ref:ao(fo(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:ao(t.Token)};if(void 0!==t.Ref)return{Ref:ao(t.Ref)}}return{Token:ao(e)}},mo=e=>{const t=e.tolerance??{};return{assetDecimals:no(e.asset_decimals),maxPriceStaleSeconds:no(e.max_price_stale_seconds),sources:uo(e.sources).map((e=>e)),tolerance:{upperRatio:no(t.upper_ratio_bps),lowerRatio:no(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:oo(e.min_sanity_price_wad),maxSanityPriceWad:oo(e.max_sanity_price_wad)}},go={"market:create":e=>({topic:"market:create",data:{hubId:no(e.hub_id),baseAsset:ao(e.base_asset),maxBorrowRate:oo(e.max_borrow_rate),baseBorrowRate:oo(e.base_borrow_rate),slope1:oo(e.slope1),slope2:oo(e.slope2),slope3:oo(e.slope3),midUtilization:oo(e.mid_utilization),optimalUtilization:oo(e.optimal_utilization),maxUtilization:oo(e.max_utilization),reserveFactor:no(e.reserve_factor),marketAddress:ao(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{hubId:void 0===e.hub_id?void 0:no(e.hub_id),asset:ao(e.asset),maxBorrowRateRay:oo(e.max_borrow_rate),baseBorrowRateRay:oo(e.base_borrow_rate),slope1Ray:oo(e.slope1),slope2Ray:oo(e.slope2),slope3Ray:oo(e.slope3),midUtilizationRay:oo(e.mid_utilization),optimalUtilizationRay:oo(e.optimal_utilization),maxUtilizationRay:oo(e.max_utilization),reserveFactorBps:no(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:uo(e).map((e=>{return t=uo(e),{hubId:no(t[0]),asset:ao(t[1]),timestamp:no(t[2]),supplyIndexRay:oo(t[3]),borrowIndexRay:oo(t[4]),cash:oo(t[5]),suppliedRay:oo(t[6]),borrowedRay:oo(t[7]),revenueRay:oo(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:uo(e).map((e=>{const t=e;return{hubId:no(t.hub_id),asset:ao(t.asset),params:(r=t.params,{maxBorrowRateRay:oo(r.max_borrow_rate),baseBorrowRateRay:oo(r.base_borrow_rate),slope1Ray:oo(r.slope1),slope2Ray:oo(r.slope2),slope3Ray:oo(r.slope3),midUtilizationRay:oo(r.mid_utilization),optimalUtilizationRay:oo(r.optimal_utilization),maxUtilizationRay:oo(r.max_utilization),reserveFactorBps:no(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:no(r.flashloan_fee),assetId:ao(r.asset_id),assetDecimals:no(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=uo(e);return{topic:"position:batch_update",data:{accountId:oo(t[0]),accountAttributes:po(uo(t[1])),updates:[...uo(t[2]).map((e=>co(uo(e),"Deposit"))),...uo(t[3]).map((e=>co(uo(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:no(e.hub_id),asset:ao(e.asset),receiver:ao(e.receiver),caller:ao(e.caller),amount:oo(e.amount),fee:oo(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:ho(e.key),oracle:mo(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:ao(e.asset),oracle:mo(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:ao(e.liquidator),accountId:oo(e.account_id),repaidUsdWad:oo(e.repaid_usd_wad),bonusBps:oo(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:oo(e.account_id),totalBorrowUsdWad:oo(e.total_borrow_usd_wad),totalCollateralUsdWad:oo(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:ao(e.token),amount:oo(e.amount),usdValueWad:void 0===e.usd_value_wad?void 0:oo(e.usd_value_wad),accountId:oo(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:no(e.hub_id),asset:ao(e.asset),amount:oo(e.amount),fee:oo(e.fee),amountSent:oo(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:ao(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:so(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:ao(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:ao(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:ao(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:ao(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:so(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:no(e.max_supply_positions),maxBorrowPositions:no(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:oo(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:ao(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:no(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:oo(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:oo(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:no(t.liquidation_bonus_factor_bps)}}},"position:flash_position":e=>({topic:"position:flash_position",data:{accountId:oo(e.account_id),hubId:no(e.hub_id),asset:ao(e.asset),receiver:ao(e.receiver),caller:ao(e.caller),amount:oo(e.amount),amountReceived:oo(e.amount_received),fee:oo(e.fee)}}),"revenue:claim":e=>({topic:"revenue:claim",data:{hubId:no(e.hub_id),asset:ao(e.asset),caller:ao(e.caller),accumulator:ao(e.accumulator),amount:oo(e.amount)}}),"account:delegate":e=>({topic:"account:delegate",data:{accountId:oo(e.account_id),owner:ao(e.owner),delegate:ao(e.delegate),granted:Boolean(e.granted)}}),"config:hub":e=>({topic:"config:hub",data:{hubId:no(e.hub_id)}}),"config:spoke_asset":e=>{const t=e.config;return{topic:"config:spoke_asset",data:{spokeId:no(e.spoke_id),hubId:no(e.hub_id),asset:ao(e.asset),config:{isCollateralizable:Boolean(t.is_collateralizable),isBorrowable:Boolean(t.is_borrowable),paused:Boolean(t.paused),frozen:Boolean(t.frozen),noSeize:Boolean(t.no_seize),loanToValueBps:no(t.loan_to_value),liquidationThresholdBps:no(t.liquidation_threshold),liquidationBonusBps:no(t.liquidation_bonus),liquidationFeesBps:no(t.liquidation_fees),supplyCap:oo(t.supply_cap),borrowCap:oo(t.borrow_cap)}}}},"config:remove_spoke_asset":e=>({topic:"config:remove_spoke_asset",data:{spokeId:no(e.spoke_id),hubId:no(e.hub_id),asset:ao(e.asset)}}),"strategy:blend_migration":e=>({topic:"strategy:blend_migration",data:{accountId:oo(e.account_id),blendPool:ao(e.blend_pool),collateralCount:no(e.collateral_count),supplyCount:no(e.supply_count),debtCount:no(e.debt_count)}}),"strategy:harvest":e=>({topic:"strategy:harvest",data:{from:ao(e.from),amount:oo(e.amount),pricePerShare:oo(e.price_per_share)}}),"governance:deploy_controller":e=>({topic:"governance:deploy_controller",data:{controller:ao(e.controller),wasmHash:so(e.wasm_hash)}}),"governance:deploy_price_aggregator":e=>({topic:"governance:deploy_price_aggregator",data:{priceAggregator:ao(e.price_aggregator),wasmHash:so(e.wasm_hash)}})},yo=Object.freeze(Object.keys(go));function wo(e,t){const r=ro(e),o=go[r];return o?o((0,i.scValToNative)(to(t))):null}const bo=1e4;function So(e,t){return`${e}-${BigInt(t).toString(10)}`}function vo(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function _o(e,t=0){return e*bo+t}function Io(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 To=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()};async function xo(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=To(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}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function Ro(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=To(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 Ao(e,t){const r=e[t];return"function"==typeof r?r.call(e):r}function Bo(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Eo(e){return ko(Ao(e,"bytes"))}function ko(e){const t=e;return l.hp.from("value"in t?t.value:t)}const qo=10,Po=5,Uo=3,Co=qo+Po*b+Uo*S,Oo=16384;class No extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const Lo=(e,t)=>{throw new No(e,t)},$o=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*Oo)return Lo("OVERSIZED",`encoded route has ${t.length} characters`);try{return Eo(X(e))}catch(e){return Lo("MALFORMED",e instanceof Error?e.message:String(e))}},Mo=e=>{let t;try{t=i.xdr.ScVal.fromXDR(e)}catch(e){return Lo("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==Bo(t))return Lo("MALFORMED","payload must be a StrategyPayload map");const r=Ao(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===Bo(Ao(e,"key"))?Ao(Ao(e,"key"),"sym").toString():"")).join(","))return Lo("MALFORMED","payload fields must be exactly amounts, assets, ops");const[o,n,a]=r.map((e=>Ao(e,"val")));return"scvVec"!==Bo(o)||"scvVec"!==Bo(n)||"scvBytes"!==Bo(a)?Lo("MALFORMED","payload field has the wrong type"):{amounts:Ao(o,"vec")??[],assets:Ao(n,"vec")??[],ops:Eo(a)}};function Do(e){const t=$o(e);0===t.length&&Lo("MALFORMED","route is empty"),t.length>Oo&&Lo("OVERSIZED",`route has ${t.length} bytes, above ${Oo}`);const r=Mo(t),o=r.assets.length,n=r.amounts.length;0===o&&Lo("MALFORMED","asset registry is empty"),(o>v||n>_)&&Lo("OVERSIZED",`registries hold ${o} assets and ${n} amounts`);const a=r.assets.map(((e,t)=>"scvAddress"!==Bo(e)?Lo("MALFORMED",`assets[${t}] is not an address`):i.Address.fromScAddress(Ao(e,"address")).toString())),s=r.amounts.map(((e,t)=>"scvI128"!==Bo(e)?Lo("MALFORMED",`amounts[${t}] is not an i128`):(0,i.scValToBigInt)(e))),l=r.ops;l.length<qo&&Lo("MALFORMED","program header is truncated"),l.length>Co&&Lo("OVERSIZED",`program has ${l.length} bytes, above ${Co}`);const I=e=>{const t=l[e];return void 0===t?Lo("MALFORMED",`program byte ${e} is missing`):t},T=I(0);T!==d&&Lo("UNSUPPORTED_VERSION",`program version ${T}, expected ${d}`);const x=I(8),R=I(9);0===x&&Lo("INVALID_STRUCTURE","program has no instructions"),(x>b||R>S)&&Lo("OVERSIZED",`program declares ${x} instructions and ${R} weights`);const A=qo+Po*x;l.length!==A+Uo*R&&Lo("MALFORMED","program length does not match its instruction and weight counts");const B=I(1),E=I(2),k=I(3);(B>=o||E>=o||k>=n)&&Lo("MALFORMED","header index is outside its registry"),B===E&&Lo("INVALID_STRUCTURE","token_in equals token_out");const q=l.readUInt32BE(4),P=[];for(let e=0;e<R;e+=1){const t=l.readUIntBE(A+Uo*e,Uo);(0===t||t>p)&&Lo("INVALID_STRUCTURE",`split weight ${t} outside 1..=${p}`),P.push(t)}const U=e=>a[e]??Lo("MALFORMED",`asset index ${e} is outside the registry`),C=e=>s[e]??Lo("MALFORMED",`amount index ${e} is outside the registry`),O=[];let N;for(let e=0;e<x;e+=1){const t=qo+Po*e,r=I(t),o=I(t+1),a=I(t+2),s=I(t+3),i=I(t+4),l=u.find((e=>c[e]===r));let d;if(l||r===f||r===h||Lo("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),o===m)d={kind:"all"};else if(o===g)void 0!==N&&N===s||Lo("INVALID_STRUCTURE",`instruction ${e} does not chain onto its predecessor`),d={kind:"prev"};else if(o>=w){const t=P[o-w];void 0===t&&Lo("MALFORMED",`instruction ${e} weight index is out of range`),d={kind:"ppm",ppm:t}}else d={kind:"fixed",amount:C(o-y)};const p=U(a);r!==f&&r!==h?(s===i&&Lo("INVALID_STRUCTURE",`instruction ${e} swaps a token for itself`),O.push({kind:"swap",venue:l,mode:d,pool:p,tokenIn:U(s),tokenOut:U(i)}),N=i):("all"!==d.kind&&Lo("MALFORMED",`liquidity instruction ${e} must use mode All`),i>=n&&Lo("MALFORMED",`instruction ${e} amount index is out of range`),O.push({kind:r===f?"burn":"mint",pool:p,shareToken:U(s),amountIndex:i}),N=r===h?s:void 0)}const L=C(k);return L<=0n&&Lo("MIN_OUT_TOO_LOW",`encoded total_min_out is ${L}`),{version:T,tokenIn:U(B),tokenOut:U(E),totalMinOut:L,referralId:q,assets:a,amounts:s,ops:O,weights:P}}function Fo(e,t){if(i.StrKey.isValidContract(e))return e;if(!t)return Lo("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?i.Asset.native():new i.Asset(e.slice(0,r),e.slice(r+1))).contractId(s[t])}catch{return Lo("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Wo=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):Lo("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function zo(e,t){const r=Wo(t.minOut,"expected.minOut");r<=0n&&Lo("EXPECTATION_MISSING","expected.minOut must be positive");const o=Do(e);if(o.tokenIn!==t.tokenIn&&Lo("TOKEN_IN_MISMATCH",`route spends ${o.tokenIn}, expected ${t.tokenIn}`),o.tokenOut!==t.tokenOut&&Lo("TOKEN_OUT_MISMATCH",`route delivers ${o.tokenOut}, expected ${t.tokenOut}`),o.totalMinOut<r&&Lo("MIN_OUT_TOO_LOW",`route enforces a minimum of ${o.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Wo(t.amountIn,"expected.amountIn");for(const t of o.ops)"swap"===t.kind&&"fixed"===t.mode.kind&&t.tokenIn===o.tokenIn&&t.mode.amount>e&&Lo("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return o}const Vo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Xo=e=>F(e).toXDR("base64");function Go(e,t){if(!e.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const r=new i.Contract(e.routerAddress),o=new i.Account(e.caller,e.sourceSequence),n=X(Vo(t,e.referralId));return{xdr:new i.TransactionBuilder(o,{fee:e.fee??i.BASE_FEE,networkPassphrase:s[e.network]}).addOperation(r.call("execute_strategy",I(e.caller),T(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function Ho(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(Ko),splitPpm:e.splitPpm}))):[{hops:e.hops.map(Ko),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function jo(e,t={}){const r=t.expected??{},o="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:Ho(e,t),n=[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 No("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===n)throw new No("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return zo(o,{tokenIn:Fo(r.tokenIn??e.from,t.network),tokenOut:Fo(r.tokenOut??e.to,t.network),minOut:n,amountIn:r.amountIn??e.amountIn}),o}const Ko=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Zo(e){try{const{envelopeXdr:t,networkPassphrase:r,routerAddress:o,viewer:n,operationIndex:a}=e;if(!r||!i.StrKey.isValidContract(o)||new i.Address(n).toString()!==n||"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 s=i.TransactionBuilder.fromXDR(t,r),l="innerTransaction"in s?s.innerTransaction:s;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"!==Bo(r))continue;const s=Ao(r,"invokeContract");if(i.Address.fromScAddress(Ao(s,"contractAddress")).toString()!==o||"execute_strategy"!==Ao(s,"functionName").toString())continue;const l=Ao(s,"args"),[c,d,p]=l;if(3!==l.length||!c||!d||!p||"scvAddress"!==Bo(c)||"scvI128"!==Bo(d)||"scvBytes"!==Bo(p))return null;if(i.Address.fromScAddress(Ao(c,"address")).toString()!==n)continue;const f=(0,i.scValToBigInt)(d);if(f<=0n)return null;const h=Do(Eo(p));if(h.tokenIn===h.tokenOut||!i.StrKey.isValidContract(h.tokenIn)||!i.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 Yo 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 Qo=e=>e&&"scvAddress"===Bo(e)?i.Address.fromScAddress(Ao(e,"address")).toString():void 0,Jo=e=>e&&"scvI128"===Bo(e)?(0,i.scValToBigInt)(e):void 0,en=e=>e&&"scvVec"===Bo(e)?Ao(e,"vec")??[]:void 0,tn=(e,t)=>{if(!e||"scvMap"!==Bo(e))return;const r=(Ao(e,"map")??[]).find((e=>"scvSymbol"===Bo(Ao(e,"key"))&&Ao(Ao(e,"key"),"sym").toString()===t));return r?Ao(r,"val"):void 0},rn=e=>Qo(e)??Jo(e)?.toString()??e.toXDR("base64"),on=e=>({contract:i.Address.fromScAddress(Ao(e,"contractAddress")).toString(),fn:Ao(e,"functionName").toString(),args:Ao(e,"args").map(rn)}),nn=e=>{const t=Ao(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===Bo(t)?Ao(t,"contractFn"):void 0};function an(e,t,r){const o=e.filter((e=>{const o=Ao(e,"credentials"),n=Bo(o);if("sorobanCredentialsAddress"!==n&&"sorobanCredentialsSourceAccount"!==n)throw new Yo("MALFORMED_TRANSACTION","unsupported authorization credentials");return("sorobanCredentialsAddress"===n?i.Address.fromScAddress(Ao(Ao(o,"address"),"address")).toString():r??t.caller)===t.caller}));if(o.length>1)throw new Yo("DUPLICATE_ENTRY",`${o.length} authorization entries for ${t.caller}, expected one`);const n=o[0];if(!n)return;const a=nn(Ao(n,"rootInvocation"));if(!a)throw new Yo("UNEXPECTED_ROOT","root is not a contract call");const s=on(a);if(s.contract!==t.root.contract||s.fn!==t.root.fn)throw new Yo("UNEXPECTED_ROOT",`expected ${t.root.contract}.${t.root.fn}`,s);const l=t.transfers.map((()=>0n)),u=(t.calls??[]).map((()=>0));for(const e of Ao(Ao(n,"rootInvocation"),"subInvocations")){const r=nn(e);if(!r)throw new Yo("UNEXPECTED_CALL","sub-invocation is not a contract call");const o=on(r);if(Ao(e,"subInvocations").length>0)throw new Yo("NESTED_INVOCATION","sub-invocation carries its own sub-invocations",o);const n=(t.calls??[]).findIndex((e=>e.contract===o.contract&&e.fn===o.fn));if(-1!==n){const e=(t.calls??[])[n],a=e.reject(Ao(r,"args"));if(a)throw new Yo("UNEXPECTED_CALL",a,o);if(u[n]=(u[n]??0)+1,(u[n]??0)>e.maxCount)throw new Yo("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,o);continue}if("transfer"!==o.fn||3!==Ao(r,"args").length)throw new Yo("UNEXPECTED_CALL","only `transfer` is allowed",o);if(!t.transfers.some((e=>e.token===o.contract)))throw new Yo("UNEXPECTED_TOKEN","transfer on an unexpected token",o);const[a,s,i]=Ao(r,"args");if(Qo(a)!==t.caller)throw new Yo("UNEXPECTED_SENDER","transfer is not from the caller",o);const c=Qo(s),d=t.transfers.findIndex((e=>e.token===o.contract&&e.to===c));if(-1===d)throw new Yo("UNEXPECTED_RECIPIENT","transfer to an unexpected recipient",o);const p=Jo(i),f=t.transfers[d],h=(l[d]??0n)+(p??0n);if(void 0===p||p<=0n||h>f.maxAmount)throw new Yo("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,o);l[d]=h}}const sn=e=>{throw new Yo("MALFORMED_TRANSACTION",e)},ln=(e,t)=>{const r=new Map;for(const t of en(e)??sn("payments argument is not a vector")){const[e,o]=en(t)??[],n=Qo(tn(e,"asset")),a=Jo(o);if(void 0===n||void 0===a||a<0n)return sn("payment is not a (HubAssetKey, i128) tuple");r.set(n,(r.get(n)??0n)+a)}return[...r].map((([e,r])=>({token:e,to:t,maxAmount:r})))},un=new Set([1,3,5]),cn=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(Qo(e[0])!==t)return"`from` is not the caller";if(Qo(e[1])!==r||Qo(e[2])!==r)return"`spender` and `to` must be the lending controller";const o=en(e[3]);if(!o)return"requests is not a vector";for(const e of o){const t=tn(e,"request_type");if(!t||"scvU32"!==Bo(t)||!un.has(Ao(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function dn(e,t,r){const{contract:o,fn:n}=on(t),a=Ao(t,"args"),s={caller:e,root:{contract:o,fn:n},transfers:[]};if(o===r.governance)return s;if(o===r.aggregatorRouter){if("execute_strategy"!==n)return s;const t=Jo(a[1]);if(Qo(a[0])!==e||void 0===t||"scvBytes"!==Bo(a[2]))return sn("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=Do(Eo(a[2]));return s.transfers=[{token:r.tokenIn,to:o,maxAmount:t}],s}if(o!==r.lendingController)throw new Yo("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${o}; pass an explicit policy`);if(Qo(a[0])!==e)throw new Yo("CALLER_MISMATCH",`${n} is not invoked for ${e}`);switch(n){case"supply":s.transfers=ln(a[3],r.lendingPool);break;case"repay":case"liquidate":s.transfers=ln(a[2],r.lendingPool);break;case"multiply":{const e=a[8];e&&"scvVoid"!==Bo(e)&&(s.transfers=ln(i.xdr.ScVal.scvVec([e]),o));break}case"migrate_from_blend":{const t=Qo(a[4])??sn("blend_pool is not an address");s.calls=[cn(t,e,o)];break}}return s}const pn=e=>{let t;try{t=i.xdr.TransactionEnvelope.fromXDR(e,"base64")}catch{return sn("not a transaction envelope")}if("envelopeTypeTx"!==Bo(t))return sn("expected a regular (v1) transaction");const r=Ao(Ao(t,"v1"),"tx"),o=Ao(r,"operations")[0];if(!o||1!==Ao(r,"operations").length)return sn("expected exactly one operation");const n=Ao(o,"body");if("invokeHostFunction"!==Bo(n))return sn("operation is not a contract invocation");const a=Ao(n,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==Bo(Ao(a,"hostFunction"))?sn("host function is not a contract call"):{source:(s=Ao(o,"sourceAccount")??Ao(r,"sourceAccount"),i.StrKey.encodeEd25519PublicKey(ko("keyTypeMuxedEd25519"===Bo(s)?Ao(Ao(s,"med25519"),"ed25519"):Ao(s,"ed25519")))),op:a,call:Ao(Ao(a,"hostFunction"),"invokeContract")};var s};function fn(e,t){const r=pn(e);if(void 0!==t.builtXdr&&Ao(pn(t.builtXdr).op,"hostFunction").toXDR("base64")!==Ao(r.op,"hostFunction").toXDR("base64"))throw new Yo("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",on(r.call));const o=t.policy??dn(t.caller,r.call,{...a(t.network),...t.deployment});an(Ao(r.op,"auth"),o,r.source)}function hn(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function mn(e,t,r){const o=r?.instructionLeeway??2e7;if(!Number.isInteger(o)||o<0||o>4294967295)throw new Error("instructionLeeway must be an integer from 0 to 4294967295");const n=i.TransactionBuilder.fromXDR(t,r?.network?s[r.network]:"");try{const t=await e.simulateTransaction(n,{cpuInstructions:o});if(i.rpc.Api.isSimulationError(t))throw new Error(t.error);return i.rpc.assembleTransaction(n,t).build().toXDR()}catch(e){if(r?.invokedContractId)throw hn(r.invokedContractId,e);throw e}}async function gn(e,t,r){return mn(e,t.xdr,r)}function yn(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 wn(e,t){return new Uint8Array(0)}const bn=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 Sn(e){const t=new i.Account(e.caller,e.sourceSequence),r=new i.Contract(e.forwarderAddress).call("mint_and_forward",i.xdr.ScVal.scvBytes(bn(e.message)),i.xdr.ScVal.scvBytes(bn(e.attestation)));return{xdr:new i.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:s[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const vn=10n**27n,_n=10n**18n,In=10000n,Tn=27,xn=18;function Rn(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 o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`Stellar math: ${t} must be a decimal integer string, got "${e}"`);r=BigInt(o)}if(r<0n)throw new Error(`Stellar math: ${t} must be non-negative, got ${r}`);return r}function An(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function Bn(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");const o=e*t,n=o/r;return o%r===0n?n:n+1n}function En(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function kn(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 qn=e=>10n**BigInt(e);function Pn(e,t,r){return t===r?e:r>t?e*qn(r-t):e/qn(t-r)}function Un(e,t,r){if(t===r)return e;if(r>t)return e*qn(r-t);const o=qn(t-r),n=e/o;return e%o===0n?n:n+1n}function Cn(e,t,r){return t===r?e:r>t?e*qn(r-t):kn(e,qn(t-r))}const On={floor:An,ceil:Bn,halfUp:En},Nn={floor:Pn,ceil:Un,halfUp:Cn};function Ln(e,t,r,o){return Nn[o](On[o](e,t,vn),Tn,r)}function $n(e,t,r){return Ln(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"floor")}function Mn(e,t,r){return Ln(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"ceil")}function Dn(e,t,r){return Ln(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"halfUp")}function Fn(e,t){if(t>Tn)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return Pn(e,t,Tn)}function Wn(e,t,r,o){const n=On[o](e,t,vn),a=Nn[o](n,Tn,xn);return On[o](a,r,_n)}function zn(e,t,r,o){const n=Nn[o](Fn(e,t),Tn,xn);return On[o](n,r,_n)}const Vn=e=>Number(e)/1e18,Xn=e=>Number(e)/1e27,Gn=(e,t)=>Number(e)/10**t;function Hn(e,t){if(!Number.isFinite(e)||e<=0||e>=1e21)return 0n;const r=e.toFixed(t),[o="0",n=""]=r.split(".");return BigInt(o+n.padEnd(t,"0"))}const jn=e=>Hn(e,xn),Kn=(e,t)=>En(e,t,vn),Zn=(e,t)=>En(e,vn,t);function Yn(e,t){return 0n===t?0n:Zn(e,t)}function Qn(e,t){const r=e>vn?vn:e,o=Rn(t.baseRateRay,"irm.baseRateRay"),n=Rn(t.slope1Ray,"irm.slope1Ray"),a=Rn(t.slope2Ray,"irm.slope2Ray"),s=Rn(t.slope3Ray,"irm.slope3Ray"),i=Rn(t.midUtilizationRay,"irm.midUtilizationRay"),l=Rn(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),u=Rn(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<i)c=o+Zn(Kn(r,n),i);else if(r<l){const e=l-i;c=o+n+Zn(Kn(r-i,a),e)}else{const e=vn-l;c=o+n+a+(0n===e?0n:Zn(Kn(r-l,s),e))}return c>u?u:c}function Jn(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:En(Kn(e,t),In-BigInt(r),In)}const ea=e=>Xn(e),ta=e=>Math.expm1(Xn(e)),ra=5n*_n,oa=(e,t,r)=>`${e}:${t}:${r}`;function na(e,t,r,o){const n=Array.isArray(e)?e:void 0,a=n?n.find((e=>e.spokeId===t&&e.hubId===r&&e.asset===o)):e[oa(t,r,o)]??Object.values(e).find((e=>e.spokeId===t&&e.hubId===r&&e.asset===o));if(!a)throw new Error(`Stellar math: no reserve for ${oa(t,r,o)}`);return a}const aa=/^0*[1-9]\d*$/,sa=e=>"string"==typeof e&&aa.test(e)?BigInt(e).toString():null,ia=(e,t)=>`${e}:${t}`;function la(e){const t=new Map,r=new Map,o=new Set,n=new Set;for(const a of e?.indexes??[]){const e=ia(a.hubId,a.asset),s=sa(a.supplyIndex),i=sa(a.borrowIndex),l=sa(a.usdPrice),u=t.get(e),c=u&&sa(u.supplyIndex)===s&&sa(u.borrowIndex)===i&&sa(u.usdPrice)===l;null==s||null==i||null==l||u&&!c?o.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?n.add(a.asset):void 0===p&&r.set(a.asset,BigInt(l))}for(const e of o)t.delete(e);for(const e of n)r.delete(e);return{indexes:t,prices:r,rejectedIndexKeys:o,rejectedAssets:n}}const ua=(e,t)=>An(e,BigInt(t),In);function ca(e,t,r,o){const n="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:Vn(e.priceWad),amountBase:t.toString(),amountShort:Gn(t,e.decimals),usdWad:r.toString(),usd:Vn(r),gateUsdWad:o.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:n?ua(o,a).toString():"0",liquidationWeightedUsdWad:n?ua(o,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function da(e){if("supply"===e.side)return ca(e,Ln(e.scaledRay,e.indexRay,e.decimals,"floor"),Wn(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),Wn(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Ln(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=Wn(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ca(e,t,r,r)}function pa(e,t,r,o){const n=Fn(t,r);return"supply"===e?An(n,vn,o):Bn(n,vn,o)}function fa(e,t,r,o){const n=Fn(t,r);return"supply"===e?Bn(n,vn,o):An(n,vn,o)}function ha(e,t){return da({...e,scaledRay:pa(e.side,t,e.decimals,e.indexRay)})}const ma=(...e)=>{for(const t of e){const e=sa(t);if(null!=e)return BigInt(e)}return vn};function ga(e,t,r,o){const n=Rn("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===n)return null;const a=o.indexes.get(ia(t.hubId,t.asset)),s=o.prices.get(t.asset),i="supply"===e?ma(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):ma(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),l=s??jn(r.usdPrice);return da({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:n,indexRay:i,priceWad:l,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==a&&void 0!==s})}const ya=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function wa(e,t,r,o,n){const a=ya(t,(e=>e.usdWad)),s=ya(t,(e=>e.ltvWeightedUsdWad)),i=ya(t,(e=>e.liquidationWeightedUsdWad)),l=ya(r,(e=>e.usdWad)),u=0n===l?null:An(i,_n,l),c=0n===i?0:Number(l)/Number(i)*100,d=s<o||s<=l?0n:s-l;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:a.toString(),totalCollateralUsd:Vn(a),ltvWeightedCollateralUsdWad:s.toString(),ltvWeightedCollateralUsd:Vn(s),liquidationWeightedCollateralUsdWad:i.toString(),liquidationWeightedCollateralUsd:Vn(i),totalDebtUsdWad:l.toString(),totalDebtUsd:Vn(l),healthFactorWad:null===u?null:u.toString(),healthFactor:null===u?null:Vn(u),healthPercent:c,borrowLimitUsdWad:s.toString(),borrowLimitUsd:Vn(s),availableBorrowUsdWad:d.toString(),availableBorrowUsd:Vn(d),minBorrowCollateralUsdWad:o.toString(),minBorrowCollateralUsd:Vn(o),isLiquidatable:null!==u&&u<_n,liveDataValid:n}}function ba(e){const{positions:t,reserves:r,liveState:o}=e,n=t[0];if(!n)throw new Error("Stellar math: computeAccountRisk needs at least one position row");for(const e of t)if(e.accountId!==n.accountId)throw new Error(`Stellar math: computeAccountRisk received mixed account ids (${n.accountId}, ${e.accountId})`);const a=la(o),s=[],i=[];for(const e of t){const t=na(r,e.spokeId,e.hubId,e.asset),o=ga("supply",e,t,a);o&&s.push(o);const n=ga("borrow",e,t,a);n&&i.push(n)}const l=null!=o?.minBorrowCollateralUsdWad?Rn(o.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):ra,u=void 0!==o&&[...s,...i].every((e=>e.liveDataUsed));return wa({accountId:n.accountId,owner:n.owner,spokeId:n.spokeId,mode:n.positionMode},s,i,l,u)}const Sa=200n,va=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),_a=e=>e<0n?0n:e,Ia=(e,t,r,o)=>({amountBase:e.amount,amountShort:Gn(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:o}),Ta=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function xa(e){const t=e.assetDecimals,r=Rn(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:Hn(e.hubPool.suppliedShort,t),borrowedBase:Hn(e.hubPool.borrowedShort,t),cashBase:Hn(e.availableLiquidityShort,t),spokeSuppliedBase:Hn(e.suppliedShort,t),spokeBorrowedBase:Hn(e.borrowedShort,t),maxUtilizationRay:r>=vn?null:r}}const Ra=(e,t)=>e<=0n?null:Number(t)/Number(e);function Aa(e,t){if(e<=0n||!t(0n))return 0n;let r=0n,o=e+1n;for(;o-r>1n;){const e=(r+o)/2n;t(e)?r=e:o=e}return r}const Ba=16n,Ea=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function ka(e,t,r){if(t.paused)return Ta("paused");if(t.frozen)return Ta("frozen");if(!t.isBorrowable)return Ta("cap");const o=t.assetDecimals,n=xa(t),a=Ea(e.borrows,t),s=la(r).indexes.get(ia(t.hubId,t.asset)),i=a?BigInt(a.indexRay):Rn(s?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),l=a?BigInt(a.usdPriceWad):function(e,t){return la(t).prices.get(e.asset)??jn(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:An(t,10n**BigInt(o),l),n=e=>c+Wn(u+pa("borrow",e,o,i),i,l,"ceil");f.push({amount:0n===r?0n:Aa(r+Ba,(e=>n(e)<=d)),reason:"ltv"})}f.push({amount:_a(Rn(t.borrowCap,"borrowCap")-n.spokeBorrowedBase),reason:"cap"});const h=En(n.suppliedBase,Sa,In);f.push({amount:_a(n.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const o=Fn(e.suppliedBase,t);return 0n===o?null:Aa(_a(An(e.suppliedBase,r,vn)-e.borrowedBase)+Ba,(n=>Yn(Fn(e.borrowedBase+n,t),o)<=r))}(n,o);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=va(f);return Ia(g,o,!1,Ra(n.suppliedBase,n.borrowedBase+g.amount))}function qa(e,t,r){if(t.paused)return Ta("paused");const o=Ea(e.supplies,t);if(!o)return Ta(null);const n=o.decimals,a=xa(t),s=BigInt(o.scaledRay),i=BigInt(o.indexRay),l=BigInt(o.usdPriceWad),u=BigInt(o.amountBase),c=Ln(s,i,n,"halfUp"),d=BigInt(e.totalDebtUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=BigInt(Math.min(o.entryLtvBps,o.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(o.ltvWeightedUsdWad);if(a<t){m=!1;const e=t-a,u=Bn(e,In,f),d=BigInt(o.gateUsdWad)-u,p=d<=0n?0n:An(d,10n**BigInt(n),l),g=c>0n?c-1n:0n,y=p+Ba>g?g:p+Ba,w=e=>{const t=fa("supply",e,n,i);return An(Wn(t>=s?0n:s-t,i,l,"floor"),f,In)};h.push({amount:Aa(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 o=Bn(e.borrowedBase,vn,r),n=e.suppliedBase<o?0n:e.suppliedBase-o+Ba,a=Fn(e.borrowedBase,t);return Aa(n>e.suppliedBase?e.suppliedBase:n,(o=>{const n=Fn(e.suppliedBase-o,t);return n>0n&&Yn(a,n)<=r}))}(a,n);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=va(h),w=m&&y.amount>=u;return Ia(y,n,w,Ra(a.suppliedBase-y.amount,a.borrowedBase))}function Pa(e){if(e.paused)return Ta("paused");if(e.frozen)return Ta("frozen");const t=e.assetDecimals,r=xa(e),o={amount:_a(Rn(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return Ia(o,t,!1,Ra(r.suppliedBase+o.amount,r.borrowedBase))}function Ua(e,t,r){if(t.paused)return Ta("paused");const o=Ea(e.borrows,t);if(!o)return Ta(null);const n=o.decimals,a=xa(t),s=BigInt(o.amountBase),i=void 0===r?null:Rn(r,"walletBalance"),l=null!==i&&i<s?{amount:i,reason:"liquidity"}:{amount:s,reason:null};return Ia(l,n,l.amount>=s,Ra(a.suppliedBase,_a(a.borrowedBase-l.amount)))}const Ca=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,Oa=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 Na(e,t){const r=[...e.supplies],o=[...e.borrows];for(const e of t){const t="supply"===e.side?r:o,n=t.findIndex((t=>Ca(t,e))),a=-1===n?void 0:t[n],s=Oa(e.amountBase);let i;if(a){const e={side:a.side,hubId:a.hubId,asset:a.asset,decimals:a.decimals,indexRay:BigInt(a.indexRay),priceWad:BigInt(a.usdPriceWad),entryLtvBps:a.entryLtvBps,entryLiquidationThresholdBps:a.entryLiquidationThresholdBps,entryLiquidationBonusBps:a.entryLiquidationBonusBps,entryLiquidationFeesBps:a.entryLiquidationFeesBps,liveDataUsed:a.liveDataUsed},t=BigInt(a.scaledRay);let r;if(s>=0n)r=t+pa(e.side,s,e.decimals,e.indexRay);else{const o=-s,n=o>=("supply"===e.side?Ln(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:fa(e.side,o,e.decimals,e.indexRay);r=n>=t?0n:t-n}i=0n===r?null:da({...e,scaledRay:r})}else i=s<=0n?null:ha(La(e),s);-1===n?i&&t.push(i):i?t[n]=i:t.splice(n,1)}return wa({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,o,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function La(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:Rn("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:jn(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function $a(e,t=0n,r=0n){const o=e.assetDecimals,n=e=>e<0n?0n:e,a=n(Hn(e.hubPool.suppliedShort,o)+Oa(t)),s=Yn(Fn(n(Hn(e.hubPool.borrowedShort,o)+Oa(r)),o),Fn(a,o)),i=Qn(s,e.irm),l=Jn(s,i,e.irm.reserveFactorBps);return{utilization:Xn(s),utilizationRay:s.toString(),borrowAprRay:i.toString(),supplyAprRay:l.toString(),borrowApr:ea(i),supplyApr:ea(l),borrowApy:ta(i),supplyApy:ta(l)}}const Ma={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},5:{name:"PoolAlreadyDeployed",message:"Singleton pool, controller, or price aggregator already recorded."},6:{name:"InvalidAsset",message:"Invalid asset address."},7:{name:"AssetsAreTheSame",message:"Same market or token where distinct HubAssetKeys or underlying assets, respectively, are required."},8:{name:"WrongToken",message:"Params.asset_id differs from the market's asset."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},13:{name:"AccountNotInMarket",message:"Caller lacks the account's position NFT, or the account has no metadata."},14:{name:"AmountMustBePositive",message:"The amount must be greater than zero."},16:{name:"InvalidPayments",message:"Payments or route list empty when required, non-empty when forbidden, or over the view limit."},18:{name:"NotSmartContract",message:"Address is not a deployed contract."},24:{name:"AccountNotFound",message:"Account id has no state, or its NFT owner is unresolvable."},25:{name:"AccountModeMismatch",message:"Account mode differs from the call's required mode."},27:{name:"AggregatorNotSet",message:"Swap or price aggregator not configured."},29:{name:"PositionLimitsNotSet",message:"No position limits stored."},30:{name:"PoolNotInitialized",message:"Pool or controller unset, or market params/state missing."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},33:{name:"MathOverflow",message:"Checked arithmetic overflow or failed narrowing conversion."},34:{name:"InternalError",message:"Internal invariant failed. Report it."},36:{name:"InvalidPositionLimits",message:"Supply or borrow limit is zero or above POSITION_LIMIT_MAX (5)."},38:{name:"SpotOnlyNotProductionSafe",message:"Every oracle source reads an unsmoothed spot market."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},40:{name:"TimelockOperationExpired",message:"Scheduled operation's grace period elapsed."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},42:{name:"BlendPoolNotApproved",message:"Blend pool not approved."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},45:{name:"RegistryCapReached",message:"Account already has MAX_DELEGATES (16)."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},47:{name:"BorrowRoundsToZeroShares",message:"Positive borrow mints zero scaled debt shares."},48:{name:"CannotRemoveLastProposer",message:"Revoke would leave no proposer."},49:{name:"WithdrawRoundsToZeroShares",message:"Positive withdrawal burns zero scaled supply shares."},50:{name:"NetSettleRoundsToZeroShares",message:"Positive net settlement burns zero shares."},51:{name:"SupplyRoundsToZeroShares",message:"Positive supply mints zero scaled shares."},52:{name:"RepayRoundsToZeroShares",message:"Positive net repayment burns zero scaled debt shares."},53:{name:"PositionNftNotSet",message:"NFT address unset on a path needing it, such as account creation. Ownership lookup can return #24 instead."},54:{name:"PositionNftAlreadyDeployed",message:"Position-NFT address already recorded."},55:{name:"DivisionByZero",message:"Fixed-point multiply-divide with zero denominator."},100:{name:"InsufficientCollateral",message:"Post-operation LTV-weighted collateral below total debt, or health factor below 1 WAD."},101:{name:"HealthFactorTooHigh",message:"Target has no debt or health factor >= 1 WAD; not liquidatable."},102:{name:"HealthFactorTooLow",message:"Update_account_threshold with has_risks = true ends below 1.05 WAD. A gated liquidation-tuple refresh skips a tuple that fails its hypothetical health-factor check."},104:{name:"NotCollateral",message:"Spoke listing disallows the asset as collateral."},107:{name:"AssetNotBorrowable",message:"Spoke listing disallows borrowing the asset."},109:{name:"PositionLimitExceeded",message:"New slot exceeds the position limit, or a sub-3-decimal supply leg would coexist with another supply slot."},110:{name:"PositionNotFound",message:"Reserved code; no longer emitted."},111:{name:"InvalidPositionMode",message:"Mode is not Multiply, Long, or Short."},112:{name:"InsufficientLiquidity",message:"Market cash below the draw, or the draw breaks the liquidation buffer."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},114:{name:"CannotCleanBadDebt",message:"Account fails the bad-debt gate."},115:{name:"WithdrawLessThanFee",message:"Liquidation protocol fee exceeds the gross withdrawal."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},118:{name:"OptUtilTooHigh",message:"Optimal utilization >= 100%."},119:{name:"InvalidReserveFactor",message:"Reserve factor >= 100%."},120:{name:"DebtPositionNotFound",message:"No debt position for that hub asset."},121:{name:"CollateralPositionNotFound",message:"No supply position for that hub asset."},122:{name:"CannotCloseWithRemainingDebt",message:"Close_position with borrow positions open."},123:{name:"PoolInsolvent",message:"Supplier claims exceed cash plus debt, or zero supply with debt outstanding."},126:{name:"MinBorrowCollateralNotMet",message:"With debt outstanding, LTV-weighted collateral below the USD floor, or a sub-3-decimal supply leg under 2 raw units after floor conversion."},127:{name:"UtilizationAboveMax",message:"Post-operation utilization above max_utilization."},128:{name:"BaseRateNegative",message:"Negative base borrow rate."},129:{name:"SlopeNonMonotonic",message:"Rate slopes do not increase monotonically."},130:{name:"MaxRateBelowBase",message:"Max borrow rate not strictly above base."},131:{name:"MaxBorrowRateTooHigh",message:"Max borrow rate exceeds MAX_BORROW_RATE_RAY (200% APR)."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},133:{name:"SelfLiquidationNotAllowed",message:"SeizeMode::Credit(id) receiver is the liquidated account. Owners may still liquidate their own account."},134:{name:"InvalidLiquidationCurve",message:"Curve bounds fail validation."},135:{name:"FullCloseRequired",message:"Retired; no error site."},201:{name:"InvalidAggregator",message:"Proposed aggregator is not a deployed contract."},204:{name:"InvalidOracleTokenType",message:"Reflector asset given as string; only address or symbol accepted."},205:{name:"UnsafePriceNotAllowed",message:"Two legs disagree beyond tolerance, or only one produced a reading."},206:{name:"PriceFeedStale",message:"Observation exceeds its staleness budget. Timestamps over 60 s ahead are dropped; the error then depends on remaining sources."},208:{name:"BadLastTolerance",message:"Upper ratio outside 10150..12500 (excess over BPS outside 150..2500 bps), or lower ratio is not the required rounded reciprocal."},210:{name:"NoLastPrice",message:"No readable source, or an Aquarius LP read failed (for example, reserves or shares)."},211:{name:"NoAccumulator",message:"Controller has no revenue accumulator."},212:{name:"ReflectorHistoryEmpty",message:"Reflector returns no price history."},216:{name:"OracleNotConfigured",message:"No oracle for the price key, or the response omits a requested asset."},217:{name:"InvalidPrice",message:"Price <= 0, or LP fair-value math non-representable."},218:{name:"InvalidStalenessConfig",message:"Max_stale_seconds out of range or below the source's guaranteed freshness."},219:{name:"TwapInsufficientObservations",message:"Record count zero or below the smoothing minimum, or history too short, too long, or denser than feed resolution."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},222:{name:"InvalidOracleResolution",message:"Reflector resolution below minimum, above max_stale_seconds, or implying a TWAP span above it."},223:{name:"SanityBoundViolated",message:"Price outside the stored sanity band."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."},226:{name:"SanityBandTooWideForSingleSource",message:"Band exceeds the tighter limit for single-source, LP, or dual-source oracles with identical provider trust sets."},227:{name:"SanityBandMustTighten",message:"Set_sanity_band would widen the band. Widen via timelocked ConfigureAssetOracle."},228:{name:"TwapRecordsOutOfRange",message:"Record count above MAX_TWAP_RECORDS (12)."},229:{name:"OracleDepthExceeded",message:"Composition nests deeper than MAX_RESOLUTION_DEPTH (3)."},230:{name:"FactorOutOfBounds",message:"Scaled source's factor price outside its min/max."},231:{name:"SourceCountOutOfRange",message:"Zero or over two sources, or Aquarius LP combined with another source."},232:{name:"IndependenceNotDeclared",message:"Sources violate RequireDisjoint, or AllowShared is empty or not exactly the shared providers."},234:{name:"UnsupportedAquariusPool",message:"Aquarius pool of wrong type, or zero reserve or total shares."},235:{name:"InsufficientAquariusLiquidity",message:"Pool value below min_pool_value_wad."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},310:{name:"SpokeMismatch",message:"Account's spoke differs from the targeted spoke."},311:{name:"SpokeSupplyCapReached",message:"Supply would exceed the spoke supply cap."},312:{name:"SpokeBorrowCapReached",message:"Borrow would exceed the spoke borrow cap."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},319:{name:"SpokeFlagsEpochMismatch",message:"RelaxSpokeAssetFlags epoch is stale or wrong; checked at proposal and execution."},400:{name:"FlashLoanOngoing",message:"Flash loan in progress; re-entrant calls refused."},401:{name:"FlashloanNotEnabled",message:"Market is_flashloanable is false."},402:{name:"InvalidFlashloanRepay",message:"Allowance below principal plus fee, or a pool balance check after payout, callback, or repayment fails."},409:{name:"StrategyFeeExceeds",message:"Strategy fee exceeds the borrowed amount."},412:{name:"InvalidFlashloanReceiver",message:"Receiver not a deployed Wasm contract, or a controller payout targets the controller or pool."},500:{name:"ConvertStepsRequired",message:"Multiply initial payment is neither collateral nor debt asset, with no convert_swap."},501:{name:"RouterOverspend",message:"Controller input balance rose during the swap, or router spent over amount_in."},502:{name:"NoSwapOutput",message:"Swap produced no positive measured output."},503:{name:"CollateralRequired",message:"Flash_position collateral list has no positive minimum. Empty list raises #16."},504:{name:"CollateralMinimumNotMet",message:"Measured deposit below its minimum, or none positive."},505:{name:"FlashPositionClosed",message:"Flash_position ended without supply or positive debt in its debt market."}},Da=/Error\(Contract,\s*#(\d+)\)/,Fa=/contract:(C[A-Z2-7]{55})[^\n]*?Error\(Contract,\s*#(\d+)\)/g,Wa=/\[xoxno-invoked:(C[A-Z2-7]{55})\]/,za=/contract:C[A-Z2-7]{55}/,Va=(e,t)=>{for(const r of e.matchAll(Fa))if(t.has(r[1]))return Number(r[2]);if(za.test(e))return null;const r=e.match(Wa),o=e.match(Da);return r&&t.has(r[1])&&o?Number(o[1]):null};function Xa(e,t){let r;if(t?.contracts?.length)r=Va(e,new Set(t.contracts));else{const t=e.match(Da);r=t?Number(t[1]):null}if(null===r)return null;const o=Ma[r];return o?{code:r,...o}:null}})(),module.exports=o})();