@xoxno/sdk-js 1.0.230 → 1.0.231
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/stellar/events/decode.d.ts +4 -6
- package/dist/cjs/sdk/stellar/lending-read.d.ts +16 -2
- package/dist/esm/sdk/stellar/events/decode.js +113 -12
- package/dist/esm/sdk/stellar/lending-read.js +40 -4
- package/dist/index.cjs +1 -1
- package/dist/sdk/stellar/events/decode.d.ts +4 -6
- package/dist/sdk/stellar/index.cjs +1 -1
- package/dist/sdk/stellar/index.esm.js +1 -1
- package/dist/sdk/stellar/lending-read.d.ts +16 -2
- package/package.json +2 -2
|
@@ -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=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 A(this,t,r);case"ascii":return E(this,t,r);case"latin1":case"binary":return B(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(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 I(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 x(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 R(e,t,r){return 0===t&&r===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,r))}function A(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<=_)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=_));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?A(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 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: "+o);o=(""+o).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const _=4096;function E(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 B(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=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const 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=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const 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=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const 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=J((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const 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=J((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=J((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=J((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=J((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 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,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)}}}},387(e,t,r){"use strict";r.d(t,{GW:()=>a});var o,n=r(564);!function(e){e.MAINNET="1",e.DEVNET="D"}(o||(o={}));class a{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=o.MAINNET,apiUrl:r,...a}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=a,this.config=t==o.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:n.s0,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.V,Manager_SC:n.Rh,P2P_SC:n.EP}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:n.cM,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.J6,Manager_SC:n.Ff,P2P_SC:n.gx}}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,...I}=o??{},{revalidate:x,...T}=l??{},R="GET"!==f||g?void 0:x??v,A="GET"!==f||g||R?void 0:u??n,_=h.body,E=d??s??(null==_?3e4:0),B=E>0?AbortSignal.timeout(E):void 0,k=h.signal??i.signal,q=B&&k?AbortSignal.any([k,B]):B??k,P={...i,...h,method:f,...Object.keys(w).length?{headers:w}:{},...q?{signal:q}:{},cache:A,next:{...I,...T,revalidate:R}};(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}}}},564(e,t,r){"use strict";r.d(t,{EP:()=>u,Ff:()=>p,J6:()=>d,KL:()=>s,Rh:()=>l,V:()=>i,ZZ:()=>n,cM:()=>c,gx:()=>f,s0:()=>o,sM:()=>a});const o="erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",n="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",a="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",s="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e",i="erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",l="erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",u="erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6",c="erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",d="erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",p="erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",f="erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}},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:()=>ta,LIQUIDATION_BUFFER_BPS:()=>ba,RAY:()=>Sn,RAY_DECIMALS:()=>xn,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Xt,STELLAR_LENDING_TOPICS:()=>go,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>s,STELLAR_ROUTE_MAX_BYTES:()=>Co,SYNTHETIC_EVENT_ORDER_STRIDE:()=>wo,StellarAuthPolicyError:()=>Zo,StellarRouteVerificationError:()=>Oo,WAD:()=>vn,WAD_DECIMALS:()=>Tn,XOXNOClient:()=>e.GW,aggregateAccountRisk:()=>ya,annualBorrowRateRay:()=>Yn,assertStellarAuthEntries:()=>nn,assertStellarPreparedTxAuth:()=>pn,baseToRay:()=>Dn,baseToShort:()=>Xn,baseValueWad:()=>Wn,buildLiveSnapshot:()=>ia,buildSameTokenRepaySwapSteps:()=>yn,buildStellarAcceptOwnershipTx:()=>_t,buildStellarAddRewardsTx:()=>zt,buildStellarApproveBlendPoolTx:()=>Pt,buildStellarBorrowBatchTx:()=>J,buildStellarBorrowTx:()=>Q,buildStellarCctpForwardTx:()=>bn,buildStellarClaimRevenueTx:()=>Wt,buildStellarCreateLiquidityPoolTx:()=>Dt,buildStellarExecuteCancellerResetTx:()=>Xr,buildStellarExecuteStrategyTx:()=>Xo,buildStellarFlashLoanTx:()=>ue,buildStellarGovernanceAddSpokeImmediateTx:()=>Kr,buildStellarGovernanceCreateHubImmediateTx:()=>jr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>$r,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Dr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Fr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Wr,buildStellarGovernanceExecuteTx:()=>Lr,buildStellarGovernanceExecuteUpdateDelayTx:()=>Mr,buildStellarGovernancePauseTx:()=>Yr,buildStellarGovernanceRevokeRoleImmediateTx:()=>Zr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Hr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Gr,buildStellarGrantRoleTx:()=>Tt,buildStellarLendingIdentifier:()=>bo,buildStellarLiquidateTx:()=>ne,buildStellarLiquidationEstimateTx:()=>se,buildStellarMigrateFromBlendTx:()=>ce,buildStellarMigrateTx:()=>vt,buildStellarMultiplyTx:()=>de,buildStellarPauseTx:()=>It,buildStellarProposeAddAssetToSpokeTx:()=>fr,buildStellarProposeAddSpokeTx:()=>dr,buildStellarProposeApproveBlendPoolTx:()=>vr,buildStellarProposeApproveTokenTx:()=>br,buildStellarProposeCancellerResetTx:()=>Vr,buildStellarProposeConfigureAssetOracleTx:()=>kr,buildStellarProposeCreateHubTx:()=>cr,buildStellarProposeCreateLiquidityPoolTx:()=>xr,buildStellarProposeDeployPoolTx:()=>Rr,buildStellarProposeEditAssetInSpokeTx:()=>hr,buildStellarProposeEditOracleToleranceTx:()=>qr,buildStellarProposeGovernanceUpgradeTx:()=>Pr,buildStellarProposeGrantGovernanceRoleTx:()=>Cr,buildStellarProposeMigrateControllerTx:()=>Er,buildStellarProposeRemoveAssetFromSpokeTx:()=>mr,buildStellarProposeRemoveSpokeTx:()=>pr,buildStellarProposeRevokeBlendPoolTx:()=>Ir,buildStellarProposeRevokeGovernanceRoleTx:()=>Or,buildStellarProposeRevokeTokenTx:()=>Sr,buildStellarProposeSetAccumulatorTx:()=>lr,buildStellarProposeSetMinBorrowCollatTx:()=>wr,buildStellarProposeSetPositionLimitsTx:()=>ur,buildStellarProposeSetPositionManagerTx:()=>yr,buildStellarProposeSetPriceAggregatorTx:()=>ir,buildStellarProposeSetSpokeLiquidationCurveTx:()=>gr,buildStellarProposeSetSwapAggregatorTx:()=>sr,buildStellarProposeTransferCtrlOwnershipTx:()=>Br,buildStellarProposeTransferGovOwnTx:()=>Nr,buildStellarProposeUnpauseTx:()=>Jr,buildStellarProposeUpdateDelayTx:()=>Ur,buildStellarProposeUpgradeControllerTx:()=>_r,buildStellarProposeUpgradePoolParamsTx:()=>Tr,buildStellarProposeUpgradePoolTx:()=>Ar,buildStellarRenewAccountTx:()=>Mt,buildStellarRepayBatchTx:()=>re,buildStellarRepayDebtWithCollateralTx:()=>he,buildStellarRepayTx:()=>oe,buildStellarRevokeBlendPoolTx:()=>Ut,buildStellarRevokeRoleTx:()=>Rt,buildStellarSetAccumulatorTx:()=>kt,buildStellarSetOracleSanityBoundsTx:()=>Lt,buildStellarSetOracleToleranceTx:()=>Ot,buildStellarSetOracleTx:()=>Ct,buildStellarSetPositionLimitsTx:()=>qt,buildStellarSetPriceAggregatorTx:()=>Bt,buildStellarSetSpokeAssetFlagsTx:()=>Nt,buildStellarSetSwapAggregatorTx:()=>Et,buildStellarSupplyBatchTx:()=>Z,buildStellarSupplyTx:()=>Y,buildStellarSwapCollateralTx:()=>fe,buildStellarSwapDebtTx:()=>pe,buildStellarTransferOwnershipTx:()=>At,buildStellarUnpauseTx:()=>xt,buildStellarUpdateAccountThresholdTx:()=>Vt,buildStellarUpdateIndexesTx:()=>$t,buildStellarUpgradeControllerTx:()=>St,buildStellarUpgradeLiquidityPoolParamsTx:()=>Ft,buildStellarWithdrawBatchTx:()=>ee,buildStellarWithdrawTx:()=>te,buildTx:()=>j,burnShares:()=>pa,computeAccountRisk:()=>wa,createStellarLendingReadClient:()=>it.createStellarLendingReadClient,decodeStellarLendingEvent:()=>yo,decodeStellarLiquidateReturn:()=>ae,decodeStellarLiquidationEstimate:()=>le,decodeStellarRouteBytes:()=>Mo,decodeStellarSwapEnvelope:()=>Ko,depositRateRay:()=>Jn,divByIntHalfUp:()=>Bn,encodeAssetOracle:()=>bt,encodeInterestRateModel:()=>lt,encodeMarketParamsRaw:()=>ut,encodePositionLimits:()=>ct,encodePriceKey:()=>dt,encodeStrategyPayloadToRouteXdr:()=>Vo,extractEventOrder:()=>So,getStellarAccountPositions:()=>Be,getStellarActiveUsersSeries:()=>Qe,getStellarAggregatorQuote:()=>To,getStellarAsset:()=>Re,getStellarAssetGraph:()=>Ne,getStellarAssetMarkets:()=>Pe,getStellarAssetPage:()=>qe,getStellarAssets:()=>Se,getStellarCampaignLeaderboard:()=>He,getStellarCampaignMe:()=>at,getStellarDefiLlamaDimensions:()=>tt,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>be,getStellarFeeRevenueSeries:()=>Ze,getStellarGovernanceProposals:()=>We,getStellarHolderDistribution:()=>Ge,getStellarHub:()=>Ae,getStellarHubGraph:()=>Le,getStellarHubHolders:()=>Ce,getStellarHubs:()=>ve,getStellarLendingContext:()=>ye,getStellarLendingLiveState:()=>we,getStellarLiquidationsLeaderboard:()=>Xe,getStellarLiquidationsSeries:()=>Ye,getStellarParticipantCounts:()=>Ve,getStellarPnlByScope:()=>nt,getStellarPositionsLeaderboard:()=>ze,getStellarPositionsPnl:()=>ot,getStellarQuoteTokens:()=>Ro,getStellarRateSpreadSeries:()=>et,getStellarReserve:()=>Te,getStellarReserveGraph:()=>Me,getStellarReserveHolders:()=>Ue,getStellarReserves:()=>xe,getStellarRevenueSeries:()=>Ke,getStellarSpoke:()=>_e,getStellarSpokeGraph:()=>$e,getStellarSpokeHolders:()=>Oe,getStellarSpokes:()=>Ie,getStellarStatsHistory:()=>je,getStellarUserActivity:()=>De,getStellarUserActivityPage:()=>Fe,getStellarUserHistory:()=>rt,getStellarUserPositions:()=>Ee,getStellarVolumeSeries:()=>Je,getStellarWalletBalance:()=>ke,lendingAssetsSchema:()=>it.lendingAssetsSchema,lendingPositionsSchema:()=>it.lendingPositionsSchema,liveIndexKey:()=>sa,mapQuoteResponseToStrategyPayload:()=>Go,mapQuoteResponseToStrategySwap:()=>Ho,mapSorobanError:()=>Va,mapStellarPositionActivityType:()=>Io,maxBorrow:()=>Ba,maxRepay:()=>Pa,maxSupply:()=>qa,maxWithdraw:()=>ka,mintShares:()=>da,mulDivCeil:()=>_n,mulDivFloor:()=>An,mulDivHalfUp:()=>En,numberToScaled:()=>Gn,numberToWad:()=>Hn,parseStellarTokenAmount:()=>H,positionValueWad:()=>Fn,prepareStellarBuiltTx:()=>mn,prepareStellarTxXdr:()=>hn,projectAccountRisk:()=>Oa,projectReserveApy:()=>La,rayAprToApy:()=>ea,rayAprToNumber:()=>Qn,rayToNumber:()=>Vn,rescaleCeil:()=>Pn,rescaleFloor:()=>qn,rescaleHalfUp:()=>Un,reserveKey:()=>ra,resolveReserve:()=>oa,stellarAuthPolicyForInvocation:()=>cn,stellarLendingDispatchKey:()=>to,stellarLendingRead:()=>st,stellarNetworks:()=>n,stellarTokenContractId:()=>Do,syntheticEventOrder:()=>vo,tagStellarInvokedContractError:()=>fn,toBase64Xdr:()=>Qr,toBigInt:()=>Rn,toStellarPositionMode:()=>gn,unscale:()=>Nn,unscaleBorrowCeil:()=>$n,unscaleHalfUp:()=>Mn,unscaleSupplyFloor:()=>Ln,utilizationRay:()=>Zn,valueBasePosition:()=>fa,valueScaledPosition:()=>ca,verifyStellarRouteBytes:()=>Wo,wadToNumber:()=>zn});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:"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,I=w-y,x=e=>new i.Address(e).toScVal(),T=e=>new i.ScInt(e).toI128(),R=e=>i.xdr.ScVal.scvU32(e),A=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()},_=e=>i.xdr.ScVal.scvBool(e),E=e=>i.xdr.ScVal.scvString(e),B=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([x(t),T(r)]);var t,r}))),O=(e,t)=>M({asset:x(t),hub_id:R(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([B("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([B("Credit"),A(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:B(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>=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,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=>x(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 R(e)}function Z(e,t){const r=t.accountNonce??0;return j(e,"supply",[x(e.caller),A(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 j(e,"borrow",[x(e.caller),A(t.accountNonce),L([...t.borrows]),U(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 j(e,"withdraw",[x(e.caller),A(t.accountNonce),L([...t.withdrawals]),U(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 j(e,"repay",[x(e.caller),A(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",[x(e.caller),A(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",[A(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",[x(e.caller),O(t.hubId,t.asset),T(t.amount),x(t.receiver),G(t.data)])}function ce(e,t){return j(e,"migrate_from_blend",[x(e.caller),A(t.accountId),K(t.spokeId),R(t.hubId),x(t.blendPool),q(t.collateralTokens.map(x)),q(t.supplyTokens.map(x)),C(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function de(e,t){const r=t.accountNonce??0;return j(e,"multiply",[x(e.caller),A(r),K(t.spokeId),O(t.collateral.hubId,t.collateral.asset),T(t.debtToFlashLoan),O(t.debt.hubId,t.debt.asset),R(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",[x(e.caller),A(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",[x(e.caller),A(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",[x(e.caller),A(t.accountNonce),O(t.collateral.hubId,t.collateral.asset),T(t.collateralAmount),O(t.debt.hubId,t.debt.asset),X(t.steps),_(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),Ie=(e,t)=>e.fetchWithTimeout(`${me}/spokes`,t),xe=(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),Re=(e,t,r)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}`,r),Ae=(e,t,r)=>e.fetchWithTimeout(`${me}/hubs/${t}`,r),_e=(e,t,r)=>e.fetchWithTimeout(`${me}/spokes/${t}`,r),Ee=(e,t,r)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/positions`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${me}/accounts/${ge(t)}/positions`,r),ke=(e,t,r,o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/assets/${ge(r)}/balance`,o),qe=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/page`,{...o,params:{...r}}),Pe=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/markets`,{...o,params:{side:r}}),Ue=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${me}/reserves/${t}/${r}/${ge(o)}/holders`,{...a,params:{side:n}}),Ce=(e,t,r,o)=>e.fetchWithTimeout(`${me}/hubs/${t}/holders`,{...o,params:{side:r}}),Oe=(e,t,r,o)=>e.fetchWithTimeout(`${me}/spokes/${t}/holders`,{...o,params:{side:r}}),Ne=(e,t,r,o)=>e.fetchWithTimeout(`${me}/assets/${ge(t)}/graph`,{...o,params:{...r}}),Le=(e,t,r,o)=>e.fetchWithTimeout(`${me}/hubs/${t}/graph`,{...o,params:{...r}}),$e=(e,t,r,o)=>e.fetchWithTimeout(`${me}/spokes/${t}/graph`,{...o,params:{...r}}),Me=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${me}/reserves/${t}/${r}/${ge(o)}/graph`,{...a,params:{...n}}),De=(e,t,r={},o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/activity`,{...o,params:{...r}}),Fe=(e,t,r={},o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/activity/page`,{...o,params:{...r}}),We=(e,t={},r)=>e.fetchWithTimeout(`${me}/governance/proposals`,{...r,params:{...t}}),ze=(e,t={},r)=>e.fetchWithTimeout(`${me}/positions`,{...r,params:{...t}}),Ve=(e,t={},r)=>e.fetchWithTimeout(`${me}/participants`,{...r,params:{...t}}),Xe=(e,t={},r)=>e.fetchWithTimeout(`${me}/liquidations/leaderboard`,{...r,params:{...t}}),Ge=(e,t={},r)=>e.fetchWithTimeout(`${me}/distribution`,{...r,params:{...t}}),He=(e,t={},r)=>e.fetchWithTimeout(`${me}/campaign/leaderboard`,{...r,params:{...t}}),je=(e,t,r)=>e.fetchWithTimeout(`${me}/stats/history`,{...r,params:{...t}}),Ke=(e,t,r)=>e.fetchWithTimeout(`${me}/revenue`,{...r,params:{...t}}),Ze=(e,t,r)=>e.fetchWithTimeout(`${me}/revenue/fees`,{...r,params:{...t}}),Ye=(e,t,r)=>e.fetchWithTimeout(`${me}/liquidations`,{...r,params:{...t}}),Je=(e,t,r)=>e.fetchWithTimeout(`${me}/volume`,{...r,params:{...t}}),Qe=(e,t,r)=>e.fetchWithTimeout(`${me}/active-users`,{...r,params:{...t}}),et=(e,t,r)=>e.fetchWithTimeout(`${me}/rate-spread`,{...r,params:{...t}}),tt=(e,t,r)=>e.fetchWithTimeout(`${me}/defillama`,{...r,params:{...t}}),rt=(e,t,r,o)=>e.fetchWithTimeout(`${me}/users/${ge(t)}/history`,{...o,params:{...r}}),ot=(e,t,r)=>e.fetchWithTimeout(`${me}/pnl`,{...r,params:{accountId:t}}),nt=(e,t,r)=>e.fetchWithTimeout(`${me}/pnl/scope`,{...r,params:{scope:t}}),at=(e,t,r)=>e.fetchWithTimeout(`${me}/campaign/me`,{...r,params:{owner:t}}),st=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=>Ie(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?xe(e,t,r):xe(e,{},t),reserve:(t,r,o,n)=>Te(e,t,r,o,n),asset:(t,r)=>Re(e,t,r),hub:(t,r)=>Ae(e,t,r),spoke:(t,r)=>_e(e,t,r),userPositions:(t,r)=>Ee(e,t,r),accountPositions:(t,r)=>Be(e,t,r),walletBalance:(t,r,o)=>ke(e,t,r,o),assetPage:(t,r,o)=>qe(e,t,r,o),assetMarkets:(t,r,o)=>Pe(e,t,r,o),reserveHolders:(t,r,o,n,a)=>Ue(e,t,r,o,n,a),hubHolders:(t,r,o)=>Ce(e,t,r,o),spokeHolders:(t,r,o)=>Oe(e,t,r,o),assetGraph:(t,r,o)=>Ne(e,t,r,o),hubGraph:(t,r,o)=>Le(e,t,r,o),spokeGraph:(t,r,o)=>$e(e,t,r,o),reserveGraph:(t,r,o,n,a)=>Me(e,t,r,o,n,a),userActivity:(t,r={},o)=>De(e,t,r,o),userActivityPage:(t,r={},o)=>Fe(e,t,r,o),governanceProposals:(t={},r)=>We(e,t,r),positionsLeaderboard:(t={},r)=>ze(e,t,r),participants:(t={},r)=>Ve(e,t,r),liquidationsLeaderboard:(t={},r)=>Xe(e,t,r),distribution:(t={},r)=>Ge(e,t,r),campaignLeaderboard:(t={},r)=>He(e,t,r),statsHistory:(t,r)=>je(e,t,r),revenue:(t,r)=>Ke(e,t,r),feeRevenue:(t,r)=>Ze(e,t,r),liquidations:(t,r)=>Ye(e,t,r),volume:(t,r)=>Je(e,t,r),activeUsers:(t,r)=>Qe(e,t,r),rateSpread:(t,r)=>et(e,t,r),defillama:(t,r)=>tt(e,t,r),userHistory:(t,r,o)=>rt(e,t,r,o),positionsPnl:(t,r)=>ot(e,t,r),pnlByScope:(t,r)=>nt(e,t,r),campaignMe:(t,r)=>at(e,t,r)});var it=r(468);const lt=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)}),ut=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.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)}),ct=e=>M({max_borrow_positions:R(e.maxBorrowPositions),max_supply_positions:R(e.maxSupplyPositions)}),dt=e=>{if("Token"in e&&e.Token)return q([B("Token"),x(e.Token)]);if("Ref"in e&&e.Ref)return q([B("Ref"),B(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},pt=e=>{if("Stellar"in e)return q([B("Stellar"),x(e.Stellar)]);if("Symbol"in e)return q([B("Symbol"),B(e.Symbol)]);if("String"in e)return q([B("String"),E(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},ft=e=>{if("Spot"===e)return q([B("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return q([B("Twap"),R(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},ht=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return q([B(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},mt=e=>{if("Market"===e||"Fundamental"===e)return q([B(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},gt=e=>{if("Reflector"in e){const t=e.Reflector;return q([B("Reflector"),M({asset:pt(t.asset),contract:x(t.contract),read_mode:ft(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return q([B("MultiFeed"),M({contract:x(t.contract),feed_id:E(t.feedId),kind:ht(t.kind),nature:mt(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},yt=e=>{const t=e;return M({decimals:R(t.decimals),max_stale_seconds:A(t.maxStaleSeconds),provider:gt(t.provider)})},wt=e=>{if("RequireDisjoint"===e)return q([B("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return q([B("AllowShared"),q(t.map((e=>M({contract:x(e.contract),kind:ht(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},bt=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:R(Number(t.assetDecimals)),independence:wt(t.independence),max_price_stale_seconds:A(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([B("Feed"),yt(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return q([B("Scaled"),M({factor:yt(t.factor),max_factor_wad:T(t.maxFactorWad),min_factor_wad:T(t.minFactorWad),quote:dt(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return q([B("LpShare"),M({key_a:dt(t.keyA),key_b:dt(t.keyB),kind:q([B(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(n),upper_ratio_bps:R(o)})})};function St(e,t){return j(e,"upgrade",[P(t.wasmHash)])}function vt(e,t){return j(e,"migrate",[R(t.newVersion)])}function It(e){return j(e,"pause",[])}function xt(e){return j(e,"unpause",[])}function Tt(e,t){return j(e,"grant_role",[x(t.account),B(t.role)])}function Rt(e,t){return j(e,"revoke_role",[x(t.account),B(t.role)])}function At(e,t){return j(e,"transfer_ownership",[x(t.newOwner),R(t.liveUntilLedger)])}function _t(e){return j(e,"accept_ownership",[])}function Et(e,t){return j(e,"set_swap_aggregator",[x(t.aggregator)])}function Bt(e,t){return j(e,"set_price_aggregator",[x(t.aggregator)])}function kt(e,t){return j(e,"set_accumulator",[x(t.accumulator)])}function qt(e,t){return j(e,"set_position_limits",[ct(t)])}function Pt(e,t){return j(e,"approve_blend_pool",[x(t.pool)])}function Ut(e,t){return j(e,"revoke_blend_pool",[x(t.pool)])}function Ct(e,t){return j(e,"set_oracle",[dt(t.key),bt(t.oracle)])}function Ot(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",[dt(t.key),M({lower_ratio_bps:R(n),upper_ratio_bps:R(o)})])}function Nt(e,t){return j(e,"set_spoke_asset_flags",[R(t.spokeId),O(t.hubId,t.asset),_(t.paused),_(t.frozen),_(t.noSeize)])}function Lt(e,t){return j(e,"set_oracle_sanity_bounds",[x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function $t(e,t){return j(e,"update_indexes",[x(e.caller),q(t.assets.map((e=>O(e.hubId,e.asset))))])}function Mt(e,t){return j(e,"renew_account",[x(e.caller),A(t.accountNonce)])}function Dt(e,t){return j(e,"create_liquidity_pool",[R(t.hubId),x(t.asset),ut(t.params)])}function Ft(e,t){return j(e,"upgrade_liquidity_pool_params",[O(t.hubId,t.asset),lt(t.params)])}function Wt(e,t){return j(e,"claim_revenue",[x(e.caller),q(t.assets.map((e=>O(e.hubId,e.asset))))])}function zt(e,t){return j(e,"add_rewards",[x(e.caller),L(t.rewards)])}function Vt(e,t){return j(e,"update_account_threshold",[x(e.caller),_(t.hasRisks),q(t.accountNonces.map((e=>A(e))))])}const Xt="00".repeat(32),Gt=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)},Ht=(e,...t)=>q([B(e),...t]),jt=e=>M({asset:x(e.asset),hub_id:R(e.hubId),params:ut(e.params)}),Kt=e=>M({hub_asset:O(e.hubId,e.asset),params:lt(e.params)}),Zt=e=>M({new_owner:x(e.newOwner),live_until_ledger:R(e.liveUntilLedger)}),Yt=e=>M({key:dt(e.key),oracle:bt(e.oracle)}),Jt=e=>M({asset:x(e.asset),bonus:R(e.bonus),borrow_cap:T(e.borrowCap),can_borrow:_(e.canBorrow),can_collateral:_(e.canCollateral),frozen:_(e.frozen),hub_id:R(e.hubId),paused:_(e.paused),liquidation_fees:R(e.liquidationFees),ltv:R(e.ltv),no_seize:_(e.noSeize),spoke_id:R(e.spokeId),supply_cap:T(e.supplyCap),threshold:R(e.threshold)}),Qt=e=>M({hub_asset:O(e.hubId,e.asset),spoke_id:R(e.spokeId)}),er=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)}),tr=e=>M({key:dt(e.key),tolerance:R(e.tolerance)}),rr=e=>M({account:x(e.account),role:B(e.role)});function or(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 nr=(e,t,r)=>or(e,"propose",[x(e.caller),t,Gt(r)]),ar=(e,t,r)=>or(e,"execute_self",[k(),t,Gt(r)]);function sr(e,t,r){return nr(e,Ht("SetSwapAggregator",x(t.aggregator)),r)}function ir(e,t,r){return nr(e,Ht("SetPriceAggregator",x(t.aggregator)),r)}function lr(e,t,r){return nr(e,Ht("SetAccumulator",x(t.accumulator)),r)}function ur(e,t,r){return nr(e,Ht("SetPositionLimits",ct(t)),r)}function cr(e,t){return nr(e,Ht("CreateHub"),t)}function dr(e,t){return nr(e,Ht("AddSpoke"),t)}function pr(e,t,r){return nr(e,Ht("RemoveSpoke",R(t.spokeId)),r)}function fr(e,t,r){return nr(e,Ht("AddAssetToSpoke",Jt(t)),r)}function hr(e,t,r){return nr(e,Ht("EditAssetInSpoke",Jt(t)),r)}function mr(e,t,r){return nr(e,Ht("RemoveAssetFromSpoke",Qt(t)),r)}function gr(e,t,r){return nr(e,Ht("SetSpokeLiquidationCurve",er(t)),r)}function yr(e,t,r){return nr(e,Ht("SetPositionManager",x(t.manager),_(t.isActive)),r)}function wr(e,t,r){return nr(e,Ht("SetMinBorrowCollateralUsd",T(t.floorWad)),r)}function br(e,t,r){return nr(e,Ht("ApproveToken",x(t.token)),r)}function Sr(e,t,r){return nr(e,Ht("RevokeToken",x(t.token)),r)}function vr(e,t,r){return nr(e,Ht("ApproveBlendPool",x(t.pool)),r)}function Ir(e,t,r){return nr(e,Ht("RevokeBlendPool",x(t.pool)),r)}function xr(e,t,r){return nr(e,Ht("CreateLiquidityPool",jt(t)),r)}function Tr(e,t,r){return nr(e,Ht("UpgradeLiquidityPoolParams",Kt(t)),r)}function Rr(e,t,r){return nr(e,Ht("DeployPool",P(t.wasmHash)),r)}function Ar(e,t,r){return nr(e,Ht("UpgradePool",P(t.wasmHash)),r)}function _r(e,t,r){return nr(e,Ht("UpgradeController",P(t.wasmHash)),r)}function Er(e,t,r){return nr(e,Ht("MigrateController",R(t.newVersion)),r)}function Br(e,t,r){return nr(e,Ht("TransferCtrlOwnership",Zt(t)),r)}function kr(e,t,r){return nr(e,Ht("ConfigureAssetOracle",Yt(t)),r)}function qr(e,t,r){return nr(e,Ht("EditOracleTolerance",tr(t)),r)}function Pr(e,t,r){return nr(e,Ht("UpgradeGov",P(t.wasmHash)),r)}function Ur(e,t,r){return nr(e,Ht("UpdateGovDelay",R(t.newDelay)),r)}function Cr(e,t,r){return nr(e,Ht("GrantGovRole",rr(t)),r)}function Or(e,t,r){return nr(e,Ht("RevokeGovRole",rr(t)),r)}function Nr(e,t,r){return nr(e,Ht("TransferGovOwnership",Zt(t)),r)}function Lr(e,t){const r=q(t.argsXdr.map((e=>i.xdr.ScVal.fromXDR(e,"base64")))),o=Gt(t.predecessor??Xt);return or(e,"execute",[k(),x(t.target),B(t.functionName),r,o,Gt(t.salt)])}function $r(e,t,r){return ar(e,Ht("UpgradeGov",P(t.wasmHash)),r)}function Mr(e,t,r){return ar(e,Ht("UpdateGovDelay",R(t.newDelay)),r)}function Dr(e,t,r){return ar(e,Ht("GrantGovRole",rr(t)),r)}function Fr(e,t,r){return ar(e,Ht("RevokeGovRole",rr(t)),r)}function Wr(e,t,r){return ar(e,Ht("TransferGovOwnership",Zt(t)),r)}const zr=e=>q(e.map(x));function Vr(e,t,r){return or(e,"propose_canceller_reset",[zr(t.newCancellers),Gt(r)])}function Xr(e,t,r){return or(e,"execute_canceller_reset",[U(t.executor,x),zr(t.newCancellers),Gt(r)])}function Gr(e,t){return or(e,"set_spoke_asset_flags",[x(e.caller),R(t.spokeId),O(t.hubId,t.asset),_(t.paused),_(t.frozen),_(t.noSeize)])}function Hr(e,t){return or(e,"set_oracle_sanity_bounds",[x(e.caller),x(t.asset),T(t.minPriceWad),T(t.maxPriceWad)])}function jr(e){return or(e,"create_hub",[x(e.caller)])}function Kr(e){return or(e,"add_spoke",[x(e.caller)])}function Zr(e,t){return or(e,"revoke_role_immediate",[x(t.account),B(t.role)])}function Yr(e){return or(e,"pause",[x(e.caller)])}function Jr(e,t){return nr(e,Ht("Unpause"),t)}const Qr=e=>e.toXDR("base64"),eo=e=>i.xdr.ScVal.fromXDR(e,"base64"),to=e=>e.map((e=>String((0,i.scValToNative)(eo(e))))).join(":"),ro=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),oo=e=>Number(e),no=e=>String(e),ao=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),so=["None","Multiply","Long","Short"],io=["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"],lo=e=>Array.isArray(e)?e:[],uo=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],io[oo(o)]??ro(o)),positionType:t,hubId:oo(e[1]),asset:no(e[2]),scaledAmountRay:ro(e[3]),indexRay:ro(e[4]),amount:ro(e[5]),liquidationThresholdBps:r?void 0:oo(e[6]),liquidationBonusBps:r?void 0:oo(e[7]),loanToValueBps:r?void 0:oo(e[8]),liquidationFeesBps:r?void 0:oo(e[9])};var o},co=e=>{return{owner:no(e[0]),spokeId:oo(e[1]),mode:(t=e[2],so[oo(t)]??"None")};var t},po=e=>Array.isArray(e)?e[1]:void 0,fo=e=>{const t=(r=e,Array.isArray(r)?no(r[0]):no(r));var r;if("Token"===t)return{Token:no(po(e))};if("Ref"===t)return{Ref:no(po(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:no(t.Token)};if(void 0!==t.Ref)return{Ref:no(t.Ref)}}return{Token:no(e)}},ho=e=>{const t=e.tolerance??{};return{assetDecimals:oo(e.asset_decimals),maxPriceStaleSeconds:oo(e.max_price_stale_seconds),sources:lo(e.sources).map((e=>e)),tolerance:{upperRatio:oo(t.upper_ratio_bps),lowerRatio:oo(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:ro(e.min_sanity_price_wad),maxSanityPriceWad:ro(e.max_sanity_price_wad)}},mo={"market:create":e=>({topic:"market:create",data:{hubId:oo(e.hub_id),baseAsset:no(e.base_asset),maxBorrowRate:ro(e.max_borrow_rate),baseBorrowRate:ro(e.base_borrow_rate),slope1:ro(e.slope1),slope2:ro(e.slope2),slope3:ro(e.slope3),midUtilization:ro(e.mid_utilization),optimalUtilization:ro(e.optimal_utilization),maxUtilization:ro(e.max_utilization),reserveFactor:oo(e.reserve_factor),marketAddress:no(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{hubId:oo(e.hub_id),asset:no(e.asset),maxBorrowRateRay:ro(e.max_borrow_rate),baseBorrowRateRay:ro(e.base_borrow_rate),slope1Ray:ro(e.slope1),slope2Ray:ro(e.slope2),slope3Ray:ro(e.slope3),midUtilizationRay:ro(e.mid_utilization),optimalUtilizationRay:ro(e.optimal_utilization),maxUtilizationRay:ro(e.max_utilization),reserveFactorBps:oo(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:lo(e).map((e=>{return t=lo(e),{hubId:oo(t[0]),asset:no(t[1]),timestamp:oo(t[2]),supplyIndexRay:ro(t[3]),borrowIndexRay:ro(t[4]),cash:ro(t[5]),suppliedRay:ro(t[6]),borrowedRay:ro(t[7]),revenueRay:ro(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:lo(e).map((e=>{const t=e;return{hubId:oo(t.hub_id),asset:no(t.asset),params:(r=t.params,{maxBorrowRateRay:ro(r.max_borrow_rate),baseBorrowRateRay:ro(r.base_borrow_rate),slope1Ray:ro(r.slope1),slope2Ray:ro(r.slope2),slope3Ray:ro(r.slope3),midUtilizationRay:ro(r.mid_utilization),optimalUtilizationRay:ro(r.optimal_utilization),maxUtilizationRay:ro(r.max_utilization),reserveFactorBps:oo(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:oo(r.flashloan_fee),assetId:no(r.asset_id),assetDecimals:oo(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=lo(e);return{topic:"position:batch_update",data:{accountId:ro(t[0]),accountAttributes:co(lo(t[1])),updates:[...lo(t[2]).map((e=>uo(lo(e),"Deposit"))),...lo(t[3]).map((e=>uo(lo(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:oo(e.hub_id),asset:no(e.asset),receiver:no(e.receiver),caller:no(e.caller),amount:ro(e.amount),fee:ro(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:fo(e.key),oracle:ho(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:no(e.asset),oracle:ho(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:no(e.liquidator),accountId:ro(e.account_id),repaidUsdWad:ro(e.repaid_usd_wad),bonusBps:ro(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:ro(e.account_id),totalBorrowUsdWad:ro(e.total_borrow_usd_wad),totalCollateralUsdWad:ro(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:no(e.token),amount:ro(e.amount),accountId:ro(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:oo(e.hub_id),asset:no(e.asset),amount:ro(e.amount),fee:ro(e.fee),amountSent:ro(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:no(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:ao(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:no(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:no(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:no(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:no(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:ao(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:oo(e.max_supply_positions),maxBorrowPositions:oo(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:ro(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:no(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:oo(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:ro(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:ro(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:oo(t.liquidation_bonus_factor_bps)}}}},go=Object.freeze(Object.keys(mo));function yo(e,t){const r=to(e),o=mo[r];return o?o((0,i.scValToNative)(eo(t))):null}const wo=1e4;function bo(e,t){return`${e}-${BigInt(t).toString(10)}`}function So(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function vo(e,t=0){return e*wo+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 xo=(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 To(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=xo(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=xo(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 _o(e){if(!e||"object"!=typeof e)return;const t=e;return"function"==typeof t.switch?t.switch().name:t.type}function Eo(e){return Bo(Ao(e,"bytes"))}function Bo(e){const t=e;return l.hp.from("value"in t?t.value:t)}const ko=10,qo=5,Po=3,Uo=ko+qo*b+Po*S,Co=16384;class Oo extends Error{code;constructor(e,t){super(`Stellar route verification failed [${e}]: ${t}`),this.name="StellarRouteVerificationError",this.code=e}}const No=(e,t)=>{throw new Oo(e,t)},Lo=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*Co)return No("OVERSIZED",`encoded route has ${t.length} characters`);try{return Eo(X(e))}catch(e){return No("MALFORMED",e instanceof Error?e.message:String(e))}},$o=e=>{let t;try{t=i.xdr.ScVal.fromXDR(e)}catch(e){return No("MALFORMED",`payload is not one XDR ScVal: ${e instanceof Error?e.message:String(e)}`)}if("scvMap"!==_o(t))return No("MALFORMED","payload must be a StrategyPayload map");const r=Ao(t,"map")??[];if("amounts,assets,ops"!==r.map((e=>"scvSymbol"===_o(Ao(e,"key"))?Ao(Ao(e,"key"),"sym").toString():"")).join(","))return No("MALFORMED","payload fields must be exactly amounts, assets, ops");const[o,n,a]=r.map((e=>Ao(e,"val")));return"scvVec"!==_o(o)||"scvVec"!==_o(n)||"scvBytes"!==_o(a)?No("MALFORMED","payload field has the wrong type"):{amounts:Ao(o,"vec")??[],assets:Ao(n,"vec")??[],ops:Eo(a)}};function Mo(e){const t=Lo(e);0===t.length&&No("MALFORMED","route is empty"),t.length>Co&&No("OVERSIZED",`route has ${t.length} bytes, above ${Co}`);const r=$o(t),o=r.assets.length,n=r.amounts.length;0===o&&No("MALFORMED","asset registry is empty"),(o>v||n>I)&&No("OVERSIZED",`registries hold ${o} assets and ${n} amounts`);const a=r.assets.map(((e,t)=>"scvAddress"!==_o(e)?No("MALFORMED",`assets[${t}] is not an address`):i.Address.fromScAddress(Ao(e,"address")).toString())),s=r.amounts.map(((e,t)=>"scvI128"!==_o(e)?No("MALFORMED",`amounts[${t}] is not an i128`):(0,i.scValToBigInt)(e))),l=r.ops;l.length<ko&&No("MALFORMED","program header is truncated"),l.length>Uo&&No("OVERSIZED",`program has ${l.length} bytes, above ${Uo}`);const x=e=>{const t=l[e];return void 0===t?No("MALFORMED",`program byte ${e} is missing`):t},T=x(0);T!==d&&No("UNSUPPORTED_VERSION",`program version ${T}, expected ${d}`);const R=x(8),A=x(9);0===R&&No("INVALID_STRUCTURE","program has no instructions"),(R>b||A>S)&&No("OVERSIZED",`program declares ${R} instructions and ${A} weights`);const _=ko+qo*R;l.length!==_+Po*A&&No("MALFORMED","program length does not match its instruction and weight counts");const E=x(1),B=x(2),k=x(3);(E>=o||B>=o||k>=n)&&No("MALFORMED","header index is outside its registry"),E===B&&No("INVALID_STRUCTURE","token_in equals token_out");const q=l.readUInt32BE(4),P=[];for(let e=0;e<A;e+=1){const t=l.readUIntBE(_+Po*e,Po);(0===t||t>p)&&No("INVALID_STRUCTURE",`split weight ${t} outside 1..=${p}`),P.push(t)}const U=e=>a[e]??No("MALFORMED",`asset index ${e} is outside the registry`),C=e=>s[e]??No("MALFORMED",`amount index ${e} is outside the registry`),O=[];let N;for(let e=0;e<R;e+=1){const t=ko+qo*e,r=x(t),o=x(t+1),a=x(t+2),s=x(t+3),i=x(t+4),l=u.find((e=>c[e]===r));let d;if(l||r===f||r===h||No("UNKNOWN_OPCODE",`instruction ${e} has opcode ${r}`),o===m)d={kind:"all"};else if(o===g)void 0!==N&&N===s||No("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&&No("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&&No("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&&No("MALFORMED",`liquidity instruction ${e} must use mode All`),i>=n&&No("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&&No("MIN_OUT_TOO_LOW",`encoded total_min_out is ${L}`),{version:T,tokenIn:U(E),tokenOut:U(B),totalMinOut:L,referralId:q,assets:a,amounts:s,ops:O,weights:P}}function Do(e,t){if(i.StrKey.isValidContract(e))return e;if(!t)return No("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 No("MALFORMED",`token id ${e} is not a contract id or a classic asset`)}}const Fo=(e,t)=>"bigint"==typeof e?e:/^\d+$/.test(e)?BigInt(e):No("EXPECTATION_MISSING",`${t} must be a base-unit integer string`);function Wo(e,t){const r=Fo(t.minOut,"expected.minOut");r<=0n&&No("EXPECTATION_MISSING","expected.minOut must be positive");const o=Mo(e);if(o.tokenIn!==t.tokenIn&&No("TOKEN_IN_MISMATCH",`route spends ${o.tokenIn}, expected ${t.tokenIn}`),o.tokenOut!==t.tokenOut&&No("TOKEN_OUT_MISMATCH",`route delivers ${o.tokenOut}, expected ${t.tokenOut}`),o.totalMinOut<r&&No("MIN_OUT_TOO_LOW",`route enforces a minimum of ${o.totalMinOut}, below the expected ${r}`),void 0!==t.amountIn){const e=Fo(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&&No("AMOUNT_IN_EXCEEDED",`a leg spends ${t.mode.amount}, above the input ${e}`)}return o}const zo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Vo=e=>F(e).toXDR("base64");function Xo(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(zo(t,e.referralId));return{xdr:new i.TransactionBuilder(o,{fee:e.fee??i.BASE_FEE,networkPassphrase:s[e.network]}).addOperation(r.call("execute_strategy",x(e.caller),T(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function Go(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(jo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(jo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function Ho(e,t={}){const r=t.expected??{},o="string"==typeof e.routeXdr&&e.routeXdr.length>0?{routeXdr:e.routeXdr}:Go(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 Oo("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 Oo("EXPECTATION_MISSING","quote has no `amountOutMin`; pass `slippage` when fetching it or `expected.minOut`");return Wo(o,{tokenIn:Do(r.tokenIn??e.from,t.network),tokenOut:Do(r.tokenOut??e.to,t.network),minOut:n,amountIn:r.amountIn??e.amountIn}),o}const jo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Ko(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"!==_o(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"!==_o(c)||"scvI128"!==_o(d)||"scvBytes"!==_o(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=Mo(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 Zo 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 Yo=e=>e&&"scvAddress"===_o(e)?i.Address.fromScAddress(Ao(e,"address")).toString():void 0,Jo=e=>e&&"scvI128"===_o(e)?(0,i.scValToBigInt)(e):void 0,Qo=e=>e&&"scvVec"===_o(e)?Ao(e,"vec")??[]:void 0,en=(e,t)=>{if(!e||"scvMap"!==_o(e))return;const r=(Ao(e,"map")??[]).find((e=>"scvSymbol"===_o(Ao(e,"key"))&&Ao(Ao(e,"key"),"sym").toString()===t));return r?Ao(r,"val"):void 0},tn=e=>Yo(e)??Jo(e)?.toString()??e.toXDR("base64"),rn=e=>({contract:i.Address.fromScAddress(Ao(e,"contractAddress")).toString(),fn:Ao(e,"functionName").toString(),args:Ao(e,"args").map(tn)}),on=e=>{const t=Ao(e,"function");return"sorobanAuthorizedFunctionTypeContractFn"===_o(t)?Ao(t,"contractFn"):void 0};function nn(e,t,r){const o=e.filter((e=>{const o=Ao(e,"credentials"),n=_o(o);if("sorobanCredentialsAddress"!==n&&"sorobanCredentialsSourceAccount"!==n)throw new Zo("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 Zo("DUPLICATE_ENTRY",`${o.length} authorization entries for ${t.caller}, expected one`);const n=o[0];if(!n)return;const a=on(Ao(n,"rootInvocation"));if(!a)throw new Zo("UNEXPECTED_ROOT","root is not a contract call");const s=rn(a);if(s.contract!==t.root.contract||s.fn!==t.root.fn)throw new Zo("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=on(e);if(!r)throw new Zo("UNEXPECTED_CALL","sub-invocation is not a contract call");const o=rn(r);if(Ao(e,"subInvocations").length>0)throw new Zo("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 Zo("UNEXPECTED_CALL",a,o);if(u[n]=(u[n]??0)+1,(u[n]??0)>e.maxCount)throw new Zo("UNEXPECTED_CALL",`more than ${e.maxCount} calls`,o);continue}if("transfer"!==o.fn||3!==Ao(r,"args").length)throw new Zo("UNEXPECTED_CALL","only `transfer` is allowed",o);if(!t.transfers.some((e=>e.token===o.contract)))throw new Zo("UNEXPECTED_TOKEN","transfer on an unexpected token",o);const[a,s,i]=Ao(r,"args");if(Yo(a)!==t.caller)throw new Zo("UNEXPECTED_SENDER","transfer is not from the caller",o);const c=Yo(s),d=t.transfers.findIndex((e=>e.token===o.contract&&e.to===c));if(-1===d)throw new Zo("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 Zo("AMOUNT_EXCEEDED",`transfers total ${h}, above the expected ${f.maxAmount}`,o);l[d]=h}}const an=e=>{throw new Zo("MALFORMED_TRANSACTION",e)},sn=(e,t)=>{const r=new Map;for(const t of Qo(e)??an("payments argument is not a vector")){const[e,o]=Qo(t)??[],n=Yo(en(e,"asset")),a=Jo(o);if(void 0===n||void 0===a||a<0n)return an("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})))},ln=new Set([1,3,5]),un=(e,t,r)=>({contract:e,fn:"submit",maxCount:2,reject:e=>{if(4!==e.length)return"submit must have four arguments";if(Yo(e[0])!==t)return"`from` is not the caller";if(Yo(e[1])!==r||Yo(e[2])!==r)return"`spender` and `to` must be the lending controller";const o=Qo(e[3]);if(!o)return"requests is not a vector";for(const e of o){const t=en(e,"request_type");if(!t||"scvU32"!==_o(t)||!ln.has(Ao(t,"u32")))return"request is not a withdraw, withdraw-collateral, or repay"}}});function cn(e,t,r){const{contract:o,fn:n}=rn(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(Yo(a[0])!==e||void 0===t||"scvBytes"!==_o(a[2]))return an("execute_strategy arguments must be (caller, total_in, swap_xdr)");const r=Mo(Eo(a[2]));return s.transfers=[{token:r.tokenIn,to:o,maxAmount:t}],s}if(o!==r.lendingController)throw new Zo("UNSUPPORTED_CONTRACT",`no authorization policy for contract ${o}; pass an explicit policy`);if(Yo(a[0])!==e)throw new Zo("CALLER_MISMATCH",`${n} is not invoked for ${e}`);switch(n){case"supply":s.transfers=sn(a[3],r.lendingPool);break;case"repay":case"liquidate":s.transfers=sn(a[2],r.lendingPool);break;case"multiply":{const e=a[8];e&&"scvVoid"!==_o(e)&&(s.transfers=sn(i.xdr.ScVal.scvVec([e]),o));break}case"migrate_from_blend":{const t=Yo(a[4])??an("blend_pool is not an address");s.calls=[un(t,e,o)];break}}return s}const dn=e=>{let t;try{t=i.xdr.TransactionEnvelope.fromXDR(e,"base64")}catch{return an("not a transaction envelope")}if("envelopeTypeTx"!==_o(t))return an("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 an("expected exactly one operation");const n=Ao(o,"body");if("invokeHostFunction"!==_o(n))return an("operation is not a contract invocation");const a=Ao(n,"invokeHostFunctionOp");return"hostFunctionTypeInvokeContract"!==_o(Ao(a,"hostFunction"))?an("host function is not a contract call"):{source:(s=Ao(o,"sourceAccount")??Ao(r,"sourceAccount"),i.StrKey.encodeEd25519PublicKey(Bo("keyTypeMuxedEd25519"===_o(s)?Ao(Ao(s,"med25519"),"ed25519"):Ao(s,"ed25519")))),op:a,call:Ao(Ao(a,"hostFunction"),"invokeContract")};var s};function pn(e,t){const r=dn(e);if(void 0!==t.builtXdr&&Ao(dn(t.builtXdr).op,"hostFunction").toXDR("base64")!==Ao(r.op,"hostFunction").toXDR("base64"))throw new Zo("INVOCATION_CHANGED","the prepared transaction does not invoke what was built",rn(r.call));const o=t.policy??cn(t.caller,r.call,{...a(t.network),...t.deployment});nn(Ao(r.op,"auth"),o,r.source)}function fn(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function hn(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 fn(r.invokedContractId,e);throw e}}async function mn(e,t,r){return hn(e,t.xdr,r)}function gn(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 yn(e,t){return new Uint8Array(0)}const wn=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 bn(e){const t=new i.Account(e.caller,e.sourceSequence),r=new i.Contract(e.forwarderAddress).call("mint_and_forward",i.xdr.ScVal.scvBytes(wn(e.message)),i.xdr.ScVal.scvBytes(wn(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 Sn=10n**27n,vn=10n**18n,In=10000n,xn=27,Tn=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 _n(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 Bn(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 kn=e=>10n**BigInt(e);function qn(e,t,r){return t===r?e:r>t?e*kn(r-t):e/kn(t-r)}function Pn(e,t,r){if(t===r)return e;if(r>t)return e*kn(r-t);const o=kn(t-r),n=e/o;return e%o===0n?n:n+1n}function Un(e,t,r){return t===r?e:r>t?e*kn(r-t):Bn(e,kn(t-r))}const Cn={floor:An,ceil:_n,halfUp:En},On={floor:qn,ceil:Pn,halfUp:Un};function Nn(e,t,r,o){return On[o](Cn[o](e,t,Sn),xn,r)}function Ln(e,t,r){return Nn(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"floor")}function $n(e,t,r){return Nn(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"ceil")}function Mn(e,t,r){return Nn(Rn(e,"scaledRay"),Rn(t,"indexRay"),r,"halfUp")}function Dn(e,t){if(t>xn)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return qn(e,t,xn)}function Fn(e,t,r,o){const n=Cn[o](e,t,Sn),a=On[o](n,xn,Tn);return Cn[o](a,r,vn)}function Wn(e,t,r,o){const n=On[o](Dn(e,t),xn,Tn);return Cn[o](n,r,vn)}const zn=e=>Number(e)/1e18,Vn=e=>Number(e)/1e27,Xn=(e,t)=>Number(e)/10**t;function Gn(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 Hn=e=>Gn(e,Tn),jn=(e,t)=>En(e,t,Sn),Kn=(e,t)=>En(e,Sn,t);function Zn(e,t){return 0n===t?0n:Kn(e,t)}function Yn(e,t){const r=e>Sn?Sn: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+Kn(jn(r,n),i);else if(r<l){const e=l-i;c=o+n+Kn(jn(r-i,a),e)}else{const e=Sn-l;c=o+n+a+(0n===e?0n:Kn(jn(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(jn(e,t),In-BigInt(r),In)}const Qn=e=>Vn(e),ea=e=>Math.expm1(Vn(e)),ta=5n*vn,ra=(e,t,r)=>`${e}:${t}:${r}`;function oa(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[ra(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 ${ra(t,r,o)}`);return a}const na=/^0*[1-9]\d*$/,aa=e=>"string"==typeof e&&na.test(e)?BigInt(e).toString():null,sa=(e,t)=>`${e}:${t}`;function ia(e){const t=new Map,r=new Map,o=new Set,n=new Set;for(const a of e?.indexes??[]){const e=sa(a.hubId,a.asset),s=aa(a.supplyIndex),i=aa(a.borrowIndex),l=aa(a.usdPrice),u=t.get(e),c=u&&aa(u.supplyIndex)===s&&aa(u.borrowIndex)===i&&aa(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 la=(e,t)=>An(e,BigInt(t),In);function ua(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:zn(e.priceWad),amountBase:t.toString(),amountShort:Xn(t,e.decimals),usdWad:r.toString(),usd:zn(r),gateUsdWad:o.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:n?la(o,a).toString():"0",liquidationWeightedUsdWad:n?la(o,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function ca(e){if("supply"===e.side)return ua(e,Nn(e.scaledRay,e.indexRay,e.decimals,"floor"),Fn(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),Fn(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Nn(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=Fn(e.scaledRay,e.indexRay,e.priceWad,"ceil");return ua(e,t,r,r)}function da(e,t,r,o){const n=Dn(t,r);return"supply"===e?An(n,Sn,o):_n(n,Sn,o)}function pa(e,t,r,o){const n=Dn(t,r);return"supply"===e?_n(n,Sn,o):An(n,Sn,o)}function fa(e,t){return ca({...e,scaledRay:da(e.side,t,e.decimals,e.indexRay)})}const ha=(...e)=>{for(const t of e){const e=aa(t);if(null!=e)return BigInt(e)}return Sn};function ma(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(sa(t.hubId,t.asset)),s=o.prices.get(t.asset),i="supply"===e?ha(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):ha(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),l=s??Hn(r.usdPrice);return ca({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 ga=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function ya(e,t,r,o,n){const a=ga(t,(e=>e.usdWad)),s=ga(t,(e=>e.ltvWeightedUsdWad)),i=ga(t,(e=>e.liquidationWeightedUsdWad)),l=ga(r,(e=>e.usdWad)),u=0n===l?null:An(i,vn,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:zn(a),ltvWeightedCollateralUsdWad:s.toString(),ltvWeightedCollateralUsd:zn(s),liquidationWeightedCollateralUsdWad:i.toString(),liquidationWeightedCollateralUsd:zn(i),totalDebtUsdWad:l.toString(),totalDebtUsd:zn(l),healthFactorWad:null===u?null:u.toString(),healthFactor:null===u?null:zn(u),healthPercent:c,borrowLimitUsdWad:s.toString(),borrowLimitUsd:zn(s),availableBorrowUsdWad:d.toString(),availableBorrowUsd:zn(d),minBorrowCollateralUsdWad:o.toString(),minBorrowCollateralUsd:zn(o),isLiquidatable:null!==u&&u<vn,liveDataValid:n}}function wa(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=ia(o),s=[],i=[];for(const e of t){const t=oa(r,e.spokeId,e.hubId,e.asset),o=ma("supply",e,t,a);o&&s.push(o);const n=ma("borrow",e,t,a);n&&i.push(n)}const l=null!=o?.minBorrowCollateralUsdWad?Rn(o.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):ta,u=void 0!==o&&[...s,...i].every((e=>e.liveDataUsed));return ya({accountId:n.accountId,owner:n.owner,spokeId:n.spokeId,mode:n.positionMode},s,i,l,u)}const ba=200n,Sa=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),va=e=>e<0n?0n:e,Ia=(e,t,r,o)=>({amountBase:e.amount,amountShort:Xn(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:o}),xa=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function Ta(e){const t=e.assetDecimals,r=Rn(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:Gn(e.hubPool.suppliedShort,t),borrowedBase:Gn(e.hubPool.borrowedShort,t),cashBase:Gn(e.availableLiquidityShort,t),spokeSuppliedBase:Gn(e.suppliedShort,t),spokeBorrowedBase:Gn(e.borrowedShort,t),maxUtilizationRay:r>=Sn?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 _a=16n,Ea=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Ba(e,t,r){if(t.paused)return xa("paused");if(t.frozen)return xa("frozen");if(!t.isBorrowable)return xa("cap");const o=t.assetDecimals,n=Ta(t),a=Ea(e.borrows,t),s=ia(r).indexes.get(sa(t.hubId,t.asset)),i=a?BigInt(a.indexRay):Rn(s?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),l=a?BigInt(a.usdPriceWad):function(e,t){return ia(t).prices.get(e.asset)??Hn(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+Fn(u+da("borrow",e,o,i),i,l,"ceil");f.push({amount:0n===r?0n:Aa(r+_a,(e=>n(e)<=d)),reason:"ltv"})}f.push({amount:va(Rn(t.borrowCap,"borrowCap")-n.spokeBorrowedBase),reason:"cap"});const h=En(n.suppliedBase,ba,In);f.push({amount:va(n.cashBase-h),reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const o=Dn(e.suppliedBase,t);return 0n===o?null:Aa(va(An(e.suppliedBase,r,Sn)-e.borrowedBase)+_a,(n=>Zn(Dn(e.borrowedBase+n,t),o)<=r))}(n,o);null!==m&&f.push({amount:m,reason:"utilizationCap"});const g=Sa(f);return Ia(g,o,!1,Ra(n.suppliedBase,n.borrowedBase+g.amount))}function ka(e,t,r){if(t.paused)return xa("paused");const o=Ea(e.supplies,t);if(!o)return xa(null);const n=o.decimals,a=Ta(t),s=BigInt(o.scaledRay),i=BigInt(o.indexRay),l=BigInt(o.usdPriceWad),u=BigInt(o.amountBase),c=Nn(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=_n(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+_a>g?g:p+_a,w=e=>{const t=pa("supply",e,n,i);return An(Fn(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=_n(e.borrowedBase,Sn,r),n=e.suppliedBase<o?0n:e.suppliedBase-o+_a,a=Dn(e.borrowedBase,t);return Aa(n>e.suppliedBase?e.suppliedBase:n,(o=>{const n=Dn(e.suppliedBase-o,t);return n>0n&&Zn(a,n)<=r}))}(a,n);null!==g&&h.push({amount:g,reason:"utilizationCap"});const y=Sa(h),w=m&&y.amount>=u;return Ia(y,n,w,Ra(a.suppliedBase-y.amount,a.borrowedBase))}function qa(e){if(e.paused)return xa("paused");if(e.frozen)return xa("frozen");const t=e.assetDecimals,r=Ta(e),o={amount:va(Rn(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return Ia(o,t,!1,Ra(r.suppliedBase+o.amount,r.borrowedBase))}function Pa(e,t,r){if(t.paused)return xa("paused");const o=Ea(e.borrows,t);if(!o)return xa(null);const n=o.decimals,a=Ta(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,va(a.borrowedBase-l.amount)))}const Ua=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,Ca=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 Oa(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=>Ua(t,e))),a=-1===n?void 0:t[n],s=Ca(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+da(e.side,s,e.decimals,e.indexRay);else{const o=-s,n=o>=("supply"===e.side?Nn(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:pa(e.side,o,e.decimals,e.indexRay);r=n>=t?0n:t-n}i=0n===r?null:ca({...e,scaledRay:r})}else i=s<=0n?null:fa(Na(e),s);-1===n?i&&t.push(i):i?t[n]=i:t.splice(n,1)}return ya({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,o,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Na(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:Hn(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function La(e,t=0n,r=0n){const o=e.assetDecimals,n=e=>e<0n?0n:e,a=n(Gn(e.hubPool.suppliedShort,o)+Ca(t)),s=Zn(Dn(n(Gn(e.hubPool.borrowedShort,o)+Ca(r)),o),Dn(a,o)),i=Yn(s,e.irm),l=Jn(s,i,e.irm.reserveFactorBps);return{utilization:Vn(s),utilizationRay:s.toString(),borrowAprRay:i.toString(),supplyAprRay:l.toString(),borrowApr:Qn(i),supplyApr:Qn(l),borrowApy:ea(i),supplyApy:ea(l)}}const $a={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."}},Ma=/Error\(Contract,\s*#(\d+)\)/,Da=/contract:(C[A-Z2-7]{55})[^\n]*?Error\(Contract,\s*#(\d+)\)/g,Fa=/\[xoxno-invoked:(C[A-Z2-7]{55})\]/,Wa=/contract:C[A-Z2-7]{55}/,za=(e,t)=>{for(const r of e.matchAll(Da))if(t.has(r[1]))return Number(r[2]);if(Wa.test(e))return null;const r=e.match(Fa),o=e.match(Ma);return r&&t.has(r[1])&&o?Number(o[1]):null};function Va(e,t){let r;if(t?.contracts?.length)r=za(e,new Set(t.contracts));else{const t=e.match(Ma);r=t?Number(t[1]):null}if(null===r)return null;const o=$a[r];return o?{code:r,...o}:null}})(),module.exports=o})();
|
|
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})();
|