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