@xoxno/sdk-js 1.0.217 → 1.0.218
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/stellar/__tests__/math/account.test.d.ts +10 -0
- package/dist/cjs/sdk/stellar/__tests__/math/parity.test.d.ts +14 -0
- package/dist/cjs/sdk/stellar/__tests__/math/scaled-rates.test.d.ts +6 -0
- package/dist/cjs/sdk/stellar/index.d.ts +1 -0
- package/dist/cjs/sdk/stellar/math/account.d.ts +183 -0
- package/dist/cjs/sdk/stellar/math/index.d.ts +12 -0
- package/dist/cjs/sdk/stellar/math/limits.d.ts +80 -0
- package/dist/cjs/sdk/stellar/math/projection.d.ts +53 -0
- package/dist/cjs/sdk/stellar/math/rates.d.ts +34 -0
- package/dist/cjs/sdk/stellar/math/scaled.d.ts +99 -0
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/sdk/stellar/__tests__/math/account.test.d.ts +10 -0
- package/dist/sdk/stellar/__tests__/math/parity.test.d.ts +14 -0
- package/dist/sdk/stellar/__tests__/math/scaled-rates.test.d.ts +6 -0
- 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/math/account.d.ts +183 -0
- package/dist/sdk/stellar/math/index.d.ts +12 -0
- package/dist/sdk/stellar/math/limits.d.ts +80 -0
- package/dist/sdk/stellar/math/projection.d.ts +53 -0
- package/dist/sdk/stellar/math/rates.d.ts +34 -0
- package/dist/sdk/stellar/math/scaled.d.ts +99 -0
- package/package.json +1 -1
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixture-driven tests for `computeAccountRisk`, the limit helpers and the
|
|
3
|
+
* projections. Expected health factors are worked by hand from
|
|
4
|
+
* `rs-lending-xlm/docs/reference/formulas.md` §Valuation and health:
|
|
5
|
+
* value_usd = round(round(round(shares·index/RAY)/1e9)·price/WAD)
|
|
6
|
+
* ltv_collateral = Σ floor(floor-value · min(ltv, threshold) / BPS)
|
|
7
|
+
* weighted_collateral = Σ floor(floor-value · threshold / BPS)
|
|
8
|
+
* debt = Σ ceil-value; HF = floor(weighted_collateral · WAD / debt)
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parity between the SDK math and the xoxno-ui mirrors it replaces. The UI
|
|
3
|
+
* functions are re-implemented inline below as the oracle, ported verbatim
|
|
4
|
+
* (BigNumber integer ops → BigInt, floats kept as floats) from:
|
|
5
|
+
* - xoxno-ui/src/modules/lending/stellar-scaled-math.ts
|
|
6
|
+
* (`unscaleSupplyFloor`, `unscaleBorrowCeil`)
|
|
7
|
+
* - xoxno-ui/src/modules/lending/utils.ts
|
|
8
|
+
* (`getBorrowApy`, `getSupplyApy`, `getNewCollateral` + `getHealthPercentage`,
|
|
9
|
+
* `calculateMaxBorrow` cap headroom)
|
|
10
|
+
* - xoxno-ui/src/modules/lending/stellar-limits.ts
|
|
11
|
+
* (`resolveMaxUtilization`, `utilCapBorrowUsd`, `utilCapWithdrawUsd`)
|
|
12
|
+
* Inputs are random but deterministic (mulberry32, fixed seed).
|
|
13
|
+
*/
|
|
14
|
+
export {};
|
|
@@ -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],o=t[1];return 3*(r+o)/4-o},t.toByteArray=function(e){var t,r,a=s(e),i=a[0],l=a[1],u=new n(function(e,t,r){return 3*(t+r)/4-r}(0,i,l)),c=0,p=l>0?i-4:i;for(r=0;r<p;r+=4)t=o[e.charCodeAt(r)]<<18|o[e.charCodeAt(r+1)]<<12|o[e.charCodeAt(r+2)]<<6|o[e.charCodeAt(r+3)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===l&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===l&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,o=e.length,n=o%3,a=[],i=16383,s=0,u=o-n;s<u;s+=i)a.push(l(e,s,s+i>u?u:s+i));return 1===n?(t=e[o-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===n&&(t=(e[o-2]<<8)+e[o-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")};for(var r=[],o=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)r[i]=a[i],o[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,o){for(var n,a,i=[],s=t;s<o;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(r[(a=n)>>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const o=r(526),n=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const 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 p(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|g(e,t);let o=s(r);const n=o.write(e,t);return n!==r&&(o=o.slice(0,n)),o}(e,t);if(ArrayBuffer.isView(e))return function(e){if(K(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return f(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 d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(K(e,SharedArrayBuffer)||e&&K(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return l.from(o,t,r);const n=function(e){if(l.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?s(0):f(e):"Buffer"===e.type&&Array.isArray(e.data)?f(e.data):void 0}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return c(e),s(e<0?0:0|h(e))}function f(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let o=0;o<t;o+=1)r[o]=255&e[o];return r}function d(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let o;return o=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(o,l.prototype),o}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function g(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,o=arguments.length>2&&!0===arguments[2];if(!o&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return H(e).length;default:if(n)return o?-1:X(e).length;t=(""+t).toLowerCase(),n=!0}}function m(e,t,r){let o=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return k(this,t,r);case"ascii":return I(this,t,r);case"latin1":case"binary":return q(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,r);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function y(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function b(e,t,r,o,n){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),J(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=l.from(t,o)),l.isBuffer(t))return 0===t.length?-1:w(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,o,n){let a,i=1,s=e.length,l=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;i=2,s/=2,l/=2,r/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(n){let o=-1;for(a=r;a<s;a++)if(u(e,a)===u(t,-1===o?0:a-o)){if(-1===o&&(o=a),a-o+1===l)return o*i}else-1!==o&&(a-=a-o),o=-1}else for(r+l>s&&(r=s-l),a=r;a>=0;a--){let r=!0;for(let o=0;o<l;o++)if(u(e,a+o)!==u(t,o)){r=!1;break}if(r)return a}return-1}function S(e,t,r,o){r=Number(r)||0;const n=e.length-r;o?(o=Number(o))>n&&(o=n):o=n;const a=t.length;let i;for(o>a/2&&(o=a/2),i=0;i<o;++i){const o=parseInt(t.substr(2*i,2),16);if(J(o))return i;e[r+i]=o}return i}function _(e,t,r,o){return j(X(t,e.length-r),e,r,o)}function v(e,t,r,o){return j(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,o)}function T(e,t,r,o){return j(H(t),e,r,o)}function x(e,t,r,o){return j(function(e,t){let r,o,n;const a=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)r=e.charCodeAt(i),o=r>>8,n=r%256,a.push(n),a.push(o);return a}(t,e.length-r),e,r,o)}function A(e,t,r){return 0===t&&r===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,r))}function k(e,t,r){r=Math.min(e.length,r);const o=[];let n=t;for(;n<r;){const t=e[n];let a=null,i=t>239?4:t>223?3:t>191?2:1;if(n+i<=r){let r,o,s,l;switch(i){case 1:t<128&&(a=t);break;case 2:r=e[n+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[n+1],o=e[n+2],128==(192&r)&&128==(192&o)&&(l=(15&t)<<12|(63&r)<<6|63&o,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[n+1],o=e[n+2],s=e[n+3],128==(192&r)&&128==(192&o)&&128==(192&s)&&(l=(15&t)<<18|(63&r)<<12|(63&o)<<6|63&s,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),n+=i}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=E));return r}(o)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?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 p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,o=t.length;for(let n=0,a=Math.min(r,o);n<a;++n)if(e[n]!==t[n]){r=e[n],o=t[n];break}return r<o?-1:o<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const o=l.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(K(t,Uint8Array))n+t.length>o.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(o,n)):Uint8Array.prototype.set.call(o,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(o,n)}n+=t.length}return o},l.byteLength=g,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?k(this,0,e):m.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},a&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,r,o,n){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===o&&(o=0),void 0===n&&(n=this.length),t<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(o>=n&&t>=r)return 0;if(o>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let a=(n>>>=0)-(o>>>=0),i=(r>>>=0)-(t>>>=0);const s=Math.min(a,i),u=this.slice(o,n),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,o){if(void 0===t)o="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)o=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===o&&(o="utf8")):(o=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let a=!1;for(;;)switch(o){case"hex":return S(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":case"latin1":case"binary":return v(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function I(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(127&e[n]);return o}function q(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(e[n]);return o}function R(e,t,r){const o=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>o)&&(r=o);let n="";for(let o=t;o<r;++o)n+=Y[e[o]];return n}function B(e,t,r){const o=e.slice(t,r);let n="";for(let e=0;e<o.length-1;e+=2)n+=String.fromCharCode(o[e]+256*o[e+1]);return n}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,r,o,n,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<a)throw new RangeError('"value" argument is out of bounds');if(r+o>e.length)throw new RangeError("Index out of range")}function O(e,t,r,o,n){F(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a;let 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,o,n){F(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r+7]=a,a>>=8,e[r+6]=a,a>>=8,e[r+5]=a,a>>=8,e[r+4]=a;let 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,o,n,a){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N(e,t,r,o,a){return t=+t,r>>>=0,a||$(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function L(e,t,r,o,a){return t=+t,r>>>=0,a||$(e,0,r,8),n.write(e,t,r,o,52,8),r+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const o=this.subarray(e,t);return Object.setPrototypeOf(o,l.prototype),o},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return o},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e+--t],n=1;for(;t>0&&(n*=256);)o+=this[e+--t]*n;return o},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(o)+(BigInt(n)<<BigInt(32))})),l.prototype.readBigUInt64BE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(o)<<BigInt(32))+BigInt(n)})),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let o=t,n=1,a=this[e+--o];for(;o>0&&(n*=256);)a+=this[e+--o]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),l.prototype.readBigInt64BE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||U(this,e,t,r,Math.pow(2,8*r)-1,0);let n=1,a=0;for(this[t]=255&e;++a<r&&(n*=256);)this[t+a]=e/n&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||U(this,e,t,r,Math.pow(2,8*r)-1,0);let n=r-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Z((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=Z((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);U(this,e,t,r,o-1,-o)}let n=0,a=1,i=0;for(this[t]=255&e;++n<r&&(a*=256);)e<0&&0===i&&0!==this[t+n-1]&&(i=1),this[t+n]=(e/a|0)-i&255;return t+r},l.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);U(this,e,t,r,o-1,-o)}let n=r-1,a=1,i=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===i&&0!==this[t+n+1]&&(i=1),this[t+n]=(e/a|0)-i&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Z((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=Z((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeFloatLE=function(e,t,r){return N(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return N(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,o){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o<r&&(o=r),o===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t<o-r&&(o=e.length-t+r);const n=o-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,o):Uint8Array.prototype.set.call(e,this.subarray(r,o),t),n},l.prototype.fill=function(e,t,r,o){if("string"==typeof e){if("string"==typeof t?(o=t,t=0,r=this.length):"string"==typeof r&&(o=r,r=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!l.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===e.length){const t=e.charCodeAt(0);("utf8"===o&&t<128||"latin1"===o)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const a=l.isBuffer(e)?e:l.from(e,o),i=a.length;if(0===i)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=a[n%i]}return this};const M={};function W(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 D(e){let t="",r=e.length;const o="-"===e[0]?1:0;for(;r>=o+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function F(e,t,r,o,n,a){if(e>r||e<t){const o="bigint"==typeof t?"n":"";let n;throw n=a>3?0===t||t===BigInt(0)?`>= 0${o} and < 2${o} ** ${8*(a+1)}${o}`:`>= -(2${o} ** ${8*(a+1)-1}${o}) and < 2 ** ${8*(a+1)-1}${o}`:`>= ${t}${o} and <= ${r}${o}`,new M.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||G(t,e.length-(r+1))}(o,n,a)}function z(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}W("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),W("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),W("ERR_OUT_OF_RANGE",(function(e,t,r){let o=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=D(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=D(n)),n+="n"),o+=` It must be ${t}. Received ${n}`,o}),RangeError);const V=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const o=e.length;let n=null;const a=[];for(let i=0;i<o;++i){if(r=e.charCodeAt(i),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===o){(t-=3)>-1&&a.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&a.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(e){return o.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(V,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,r,o){let n;for(n=0;n<o&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const o=16*r;for(let n=0;n<16;++n)t[o+n]=e[r]+e[n]}return t}();function Z(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},251(e,t){t.read=function(e,t,r,o,n){var a,i,s=8*n-o-1,l=(1<<s)-1,u=l>>1,c=-7,p=r?n-1:0,f=r?-1:1,d=e[t+p];for(p+=f,a=d&(1<<-c)-1,d>>=-c,c+=s;c>0;a=256*a+e[t+p],p+=f,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=o;c>0;i=256*i+e[t+p],p+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,o),a-=u}return(d?-1:1)*i*Math.pow(2,a-o)},t.write=function(e,t,r,o,n,a){var i,s,l,u=8*a-n-1,c=(1<<u)-1,p=c>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=o?0:a-1,h=o?1:-1,g=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+p>=1?f/l:f*Math.pow(2,1-p))*l>=2&&(i++,l/=2),i+p>=c?(s=0,i=c):i+p>=1?(s=(t*l-1)*Math.pow(2,n),i+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),i=0));n>=8;e[r+d]=255&s,d+=h,s/=256,n-=8);for(i=i<<n|s,u+=n;u>0;e[r+d]=255&i,d+=h,i/=256,u-=8);e[r+d-h]|=128*g}},387(e,t,r){"use strict";r.d(t,{GW:()=>a});var o,n=r(564);!function(e){e.MAINNET="1",e.DEVNET="D"}(o||(o={}));class a{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=o.MAINNET,apiUrl:r,...a}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=a,this.config=t==o.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:n.s0,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.V,Manager_SC:n.Rh,P2P_SC:n.EP}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:n.cM,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.J6,Manager_SC:n.Ff,P2P_SC:n.gx}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:o,cache:n,debug:a,timeout:i,...s}=this.init,{next:l,cache:u,debug:c,timeout:p,headers:f,method:d="GET",...h}=r,g=f?.Authorization,m="Bearer undefined"===g?void 0:g,y="GET"!==d&&"HEAD"!==d&&"PUT"!==d,b={...f,Referer:"https://xoxno.sdk","User-Agent":"XOXNO/1.0/SDK",...y?{"Content-Type":"application/json"}:{},...m?{Authorization:m}:{}},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}=o??{},{revalidate:T,...x}=l??{},A="GET"!==d||m?void 0:T??_,k="GET"!==d||m||A?void 0:u??n,E=h.body,I=p??i??(null==E?3e4:0),q=I>0?AbortSignal.timeout(I):void 0,R=h.signal??s.signal,B=q&&R?AbortSignal.any([R,q]):q??R,P={...s,...h,method:d,...Object.keys(b).length?{headers:b}:{},...B?{signal:B}:{},cache:k,next:{...v,...x,revalidate:A}};(c??a)&&console.debug("SDK fetch: ",S,P);const U=await fetch(S,P).catch((e=>{if(e instanceof Error&&!e.message.match(/^http(s?):\/\//))throw Object.assign(new Error(`${S}: ${e.message}`),{cause:e});throw e})),O=await U.text();if(!U.ok){let e;try{e=JSON.parse(O)}catch{e={message:O}}const t=[S,U.status,U.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:()=>f,J6:()=>p,KL:()=>i,Rh:()=>l,V:()=>s,ZZ:()=>n,cM:()=>c,gx:()=>d,s0:()=>o,sM:()=>a});const o="erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",n="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",a="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",i="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e",s="erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",l="erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",u="erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6",c="erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",p="erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",f="erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",d="erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={exports:{}};return e[o](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";r.r(o),r.d(o,{STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Ot,STELLAR_LENDING_TOPICS:()=>io,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>i,SYNTHETIC_EVENT_ORDER_STRIDE:()=>lo,XOXNOClient:()=>e.GW,buildSameTokenRepaySwapSteps:()=>qo,buildStellarAcceptOwnershipTx:()=>ft,buildStellarAddRewardsTx:()=>Pt,buildStellarApproveBlendPoolTx:()=>bt,buildStellarApproveTokenTx:()=>St,buildStellarBatchSwapTx:()=>So,buildStellarBorrowBatchTx:()=>W,buildStellarBorrowTx:()=>D,buildStellarCctpForwardTx:()=>Bo,buildStellarClaimRevenueTx:()=>Bt,buildStellarCreateLiquidityPoolTx:()=>qt,buildStellarExecuteCancellerResetTx:()=>$r,buildStellarExecuteStrategyTx:()=>wo,buildStellarFlashLoanTx:()=>j,buildStellarGovernanceAddSpokeImmediateTx:()=>Wr,buildStellarGovernanceCreateHubImmediateTx:()=>Mr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>qr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Br,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Pr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Ur,buildStellarGovernanceExecuteTx:()=>Ir,buildStellarGovernanceExecuteUpdateDelayTx:()=>Rr,buildStellarGovernancePauseTx:()=>Fr,buildStellarGovernanceRevokeRoleImmediateTx:()=>Dr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Lr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Nr,buildStellarGrantRoleTx:()=>ut,buildStellarLendingIdentifier:()=>uo,buildStellarLiquidateTx:()=>X,buildStellarMigrateFromBlendTx:()=>K,buildStellarMigrateTx:()=>it,buildStellarMultiplyTx:()=>J,buildStellarPauseTx:()=>st,buildStellarProposeAddAssetToSpokeTx:()=>or,buildStellarProposeAddSpokeTx:()=>tr,buildStellarProposeApproveBlendPoolTx:()=>pr,buildStellarProposeApproveTokenTx:()=>ur,buildStellarProposeCancellerResetTx:()=>Cr,buildStellarProposeConfigureAssetOracleTx:()=>Sr,buildStellarProposeConfigureMarketOracleTx:()=>_r,buildStellarProposeCreateHubTx:()=>er,buildStellarProposeCreateLiquidityPoolTx:()=>dr,buildStellarProposeDeployPoolTx:()=>gr,buildStellarProposeEditAssetInSpokeTx:()=>nr,buildStellarProposeEditOracleToleranceTx:()=>vr,buildStellarProposeGovernanceUpgradeTx:()=>Tr,buildStellarProposeGrantGovernanceRoleTx:()=>Ar,buildStellarProposeMigrateControllerTx:()=>br,buildStellarProposeRemoveAssetFromSpokeTx:()=>ar,buildStellarProposeRemoveSpokeTx:()=>rr,buildStellarProposeRevokeBlendPoolTx:()=>fr,buildStellarProposeRevokeGovernanceRoleTx:()=>kr,buildStellarProposeRevokeTokenTx:()=>cr,buildStellarProposeSetAccumulatorTx:()=>Zt,buildStellarProposeSetAggregatorTx:()=>Yt,buildStellarProposeSetMinBorrowCollatTx:()=>lr,buildStellarProposeSetPositionLimitsTx:()=>Qt,buildStellarProposeSetPositionManagerTx:()=>sr,buildStellarProposeSetPriceAggregatorTx:()=>Jt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>ir,buildStellarProposeSetSwapAggregatorTx:()=>Kt,buildStellarProposeTransferCtrlOwnershipTx:()=>wr,buildStellarProposeTransferGovOwnTx:()=>Er,buildStellarProposeUnpauseTx:()=>zr,buildStellarProposeUpdateDelayTx:()=>xr,buildStellarProposeUpgradeControllerTx:()=>yr,buildStellarProposeUpgradePoolParamsTx:()=>hr,buildStellarProposeUpgradePoolTx:()=>mr,buildStellarRenewAccountTx:()=>It,buildStellarRepayBatchTx:()=>G,buildStellarRepayDebtWithCollateralTx:()=>Q,buildStellarRepayTx:()=>V,buildStellarRevokeBlendPoolTx:()=>wt,buildStellarRevokeRoleTx:()=>ct,buildStellarRevokeTokenTx:()=>_t,buildStellarSetAccumulatorTx:()=>mt,buildStellarSetAggregatorTx:()=>gt,buildStellarSetMarketOracleConfigTx:()=>Tt,buildStellarSetOracleSanityBoundsTx:()=>kt,buildStellarSetOracleToleranceTx:()=>xt,buildStellarSetOracleTx:()=>vt,buildStellarSetPositionLimitsTx:()=>yt,buildStellarSetPriceAggregatorTx:()=>ht,buildStellarSetSpokeAssetFlagsTx:()=>At,buildStellarSetSwapAggregatorTx:()=>dt,buildStellarSupplyBatchTx:()=>L,buildStellarSupplyTx:()=>M,buildStellarSwapCollateralTx:()=>Z,buildStellarSwapDebtTx:()=>Y,buildStellarTransferOwnershipTx:()=>pt,buildStellarUnpauseTx:()=>lt,buildStellarUpdateAccountThresholdTx:()=>Ut,buildStellarUpdateIndexesTx:()=>Et,buildStellarUpgradeControllerTx:()=>at,buildStellarUpgradeLiquidityPoolParamsTx:()=>Rt,buildStellarWithdrawBatchTx:()=>F,buildStellarWithdrawTx:()=>z,buildTx:()=>$,decodeStellarLendingEvent:()=>so,decodeStellarLiquidateReturn:()=>H,encodeAssetOracle:()=>ot,encodeInterestRateModel:()=>Xe,encodeMarketOracleConfigInput:()=>nt,encodeMarketParamsRaw:()=>He,encodePositionLimits:()=>je,encodePriceKey:()=>Ke,encodeStrategyPayloadToRouteXdr:()=>bo,extractEventOrder:()=>co,getStellarAccountPositions:()=>he,getStellarActiveUsersSeries:()=>Le,getStellarAggregatorQuote:()=>go,getStellarAsset:()=>ce,getStellarAssetGraph:()=>_e,getStellarAssetMarkets:()=>ye,getStellarAssetPage:()=>me,getStellarAssets:()=>ae,getStellarCampaignLeaderboard:()=>Pe,getStellarCampaignMe:()=>Ge,getStellarDefiLlamaDimensions:()=>We,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>ne,getStellarFeeRevenueSeries:()=>Ce,getStellarGovernanceProposals:()=>Ee,getStellarHolderDistribution:()=>Be,getStellarHub:()=>pe,getStellarHubGraph:()=>ve,getStellarHubHolders:()=>we,getStellarHubs:()=>ie,getStellarLendingContext:()=>re,getStellarLendingLiveState:()=>oe,getStellarLiquidationsLeaderboard:()=>Re,getStellarLiquidationsSeries:()=>$e,getStellarParticipantCounts:()=>qe,getStellarPnlByScope:()=>ze,getStellarPositionsLeaderboard:()=>Ie,getStellarPositionsPnl:()=>Fe,getStellarQuoteTokens:()=>mo,getStellarRateSpreadSeries:()=>Me,getStellarReserve:()=>ue,getStellarReserveGraph:()=>xe,getStellarReserveHolders:()=>be,getStellarReserves:()=>le,getStellarRevenueSeries:()=>Oe,getStellarSpoke:()=>fe,getStellarSpokeGraph:()=>Te,getStellarSpokeHolders:()=>Se,getStellarSpokes:()=>se,getStellarStatsHistory:()=>Ue,getStellarUserActivity:()=>Ae,getStellarUserActivityPage:()=>ke,getStellarUserHistory:()=>De,getStellarUserPositions:()=>de,getStellarVolumeSeries:()=>Ne,getStellarWalletBalance:()=>ge,mapQuoteResponseToAggregatorSwap:()=>To,mapQuoteResponseToStrategyPayload:()=>_o,mapQuoteResponseToStrategySwap:()=>vo,mapSorobanError:()=>Uo,mapStellarPositionActivityType:()=>fo,prepareStellarBuiltTx:()=>Eo,prepareStellarTxXdr:()=>ko,stellarLendingDispatchKey:()=>Xr,stellarLendingRead:()=>Ve,stellarNetworks:()=>n,syntheticEventOrder:()=>po,tagStellarInvokedContractError:()=>Ao,toBase64Xdr:()=>Gr,toStellarPositionMode:()=>Io});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",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",aggregatorRouter:"CDNTWMWW2WGYTKIZTJYNGNVQQZI4KTC5BQRZ3275KESRX5T4O3AYECL5",governance:"CDS33JDOYH3F3FL4QUQ6DV4WKHML2AKHF4LADTZ57FRUAEBTE7NMY5FQ",priceAggregator:"CAALOOTIDXCX7D7FMQIBSSAJLPKOM3GMXS4UUSTDIG42JCRRJHOPUHOP",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},n=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},p=1e6,f=e=>new s.Address(e).toScVal(),d=e=>new s.ScInt(e).toI128(),h=e=>s.xdr.ScVal.scvU32(e),g=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()},m=e=>s.xdr.ScVal.scvBool(e),y=e=>s.xdr.ScVal.scvString(e),b=e=>s.xdr.ScVal.scvSymbol(e),w=()=>s.xdr.ScVal.scvVoid(),S=e=>s.xdr.ScVal.scvVec(e),_=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=l.hp.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return s.xdr.ScVal.scvBytes(o)},v=(e,t)=>null==e?w():t(e),T=e=>s.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,s.xdr.ScVal.scvVec([f(t),d(r)]);var t,r}))),x=(e,t)=>I({asset:f(t),hub_id:h(e)}),A=(e,t,r)=>s.xdr.ScVal.scvVec([x(e,t),d(r)]),k=e=>s.xdr.ScVal.scvVec(e.map((e=>A(e.hubId,e.asset,e.amount)))),E=e=>{if("Transfer"===e)return S([b("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return S([b("Credit"),g(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},I=e=>{const t=Object.keys(e).sort().map((t=>new s.xdr.ScMapEntry({key:b(t),val:e[t]})));return s.xdr.ScVal.scvMap(t)};class q{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>=256)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>=126)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>=32)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..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,n){this.ops.push([e,t,r,o,n])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const n=e.hops[o-1];if(n&&r.tokenIn!==n.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(c[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,n=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&n.push(r);const a=n.reduce(((e,r)=>e+t[r].splitPpm),0);if(a>p)throw new Error(`Stellar builder: split weights for one token sum to ${a}, above 1000000`);const i=a===p;let s=p;n.forEach(((e,o)=>{r[e]=!0;const a=t[e];let l;if(o+1===n.length&&i)l=0;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=128+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>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return l.hp.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const R=e=>{const t=new q(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),n=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,n)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[n,a]=o,[i,s]=e.preSwapFromA?[n,a]:[a,n];t.emit(c.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(i),t.asset(s))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const n=Number(e.referralId??0);if(!Number.isInteger(n)||n<0||n>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return I({amounts:s.xdr.ScVal.scvVec(t.amountList.map((e=>d(e)))),assets:s.xdr.ScVal.scvVec(t.assetList.map((e=>f(e)))),ops:s.xdr.ScVal.scvBytes(t.toBytes(r,o,n))})},B=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)},P=()=>s.xdr.ScVal.scvBytes(l.hp.alloc(0)),U=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return l.hp.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=l.hp.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},O=e=>{if("string"==typeof e)return B(U(e));if(e instanceof Uint8Array)return 0===e.length?P():B(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?B(U(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?B(U(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?B(U(e.bytes)):0===e.bytes.length?P():B(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length&&!t.burnPool&&!t.mintPool)throw new Error("Stellar builder: `steps.paths` needs a strategy path or a liquidity burn/mint operation");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!u.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==p)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),s.xdr.ScVal.scvBytes(l.hp.from(R(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},C=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 $(e,t,r){if(!e.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const o=new s.Contract(e.controllerAddress),n=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function N(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return h(e)}function L(e,t){const r=t.accountNonce??0;return $(e,"supply",[f(e.caller),g(r),N(t.spokeId),k([...t.assets])])}function M(e,t){return L(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function W(e,t){return $(e,"borrow",[f(e.caller),g(t.accountNonce),k([...t.borrows]),v(t.to,f)])}function D(e,t){return W(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function F(e,t){return $(e,"withdraw",[f(e.caller),g(t.accountNonce),k([...t.withdrawals]),v(t.to,f)])}function z(e,t){return F(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function G(e,t){return $(e,"repay",[f(e.caller),g(t.accountNonce),k([...t.payments])])}function V(e,t){return G(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function X(e,t){return $(e,"liquidate",[f(e.caller),g(t.accountNonce),k([...t.debtPayments]),E(t.seizeMode??"Transfer")])}function H(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 j(e,t){return $(e,"flash_loan",[f(e.caller),x(t.hubId,t.asset),d(t.amount),f(t.receiver),C(t.data)])}function K(e,t){return $(e,"migrate_from_blend",[f(e.caller),g(t.accountId),N(t.spokeId),h(t.hubId),f(t.blendPool),S(t.collateralTokens.map(f)),S(t.supplyTokens.map(f)),T(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function J(e,t){const r=t.accountNonce??0;return $(e,"multiply",[f(e.caller),g(r),N(t.spokeId),x(t.collateral.hubId,t.collateral.asset),d(t.debtToFlashLoan),x(t.debt.hubId,t.debt.asset),h(t.mode),O(t.steps),v(t.initialPayment,(e=>A(e.hubId,e.asset,e.amount))),v(t.convertSwap,O)])}function Y(e,t){return $(e,"swap_debt",[f(e.caller),g(t.accountNonce),x(t.existingDebt.hubId,t.existingDebt.asset),d(t.newDebtAmount),x(t.newDebt.hubId,t.newDebt.asset),O(t.steps)])}function Z(e,t){return $(e,"swap_collateral",[f(e.caller),g(t.accountNonce),x(t.current.hubId,t.current.asset),d(t.fromAmount),x(t.newCollateral.hubId,t.newCollateral.asset),O(t.steps)])}function Q(e,t){return $(e,"repay_debt_with_collateral",[f(e.caller),g(t.accountNonce),x(t.collateral.hubId,t.collateral.asset),d(t.collateralAmount),x(t.debt.hubId,t.debt.asset),O(t.steps),m(t.closePosition)])}const ee="/stellar-lending",te=encodeURIComponent,re=(e,t)=>e.fetchWithTimeout(`${ee}/context`,t),oe=(e,t)=>e.fetchWithTimeout(`${ee}/live-state`,t),ne=(e,t)=>e.fetchWithTimeout(`${ee}/markets/detailed`,t),ae=(e,t)=>e.fetchWithTimeout(`${ee}/assets`,t),ie=(e,t)=>e.fetchWithTimeout(`${ee}/hubs`,t),se=(e,t)=>e.fetchWithTimeout(`${ee}/spokes`,t),le=(e,t={},r)=>e.fetchWithTimeout(`${ee}/reserves`,{...r,params:{...t}}),ue=(e,t,r,o,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}`,n),ce=(e,t,r)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}`,r),pe=(e,t,r)=>e.fetchWithTimeout(`${ee}/hubs/${t}`,r),fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/spokes/${t}`,r),de=(e,t,r)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/positions`,r),he=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${te(t)}/positions`,r),ge=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/assets/${te(r)}/balance`,o),me=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/page`,{...o,params:{...r}}),ye=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/markets`,{...o,params:{side:r}}),be=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}/holders`,{...a,params:{side:n}}),we=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/holders`,{...o,params:{side:r}}),Se=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/holders`,{...o,params:{side:r}}),_e=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/graph`,{...o,params:{...r}}),ve=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/graph`,{...o,params:{...r}}),Te=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}/graph`,{...a,params:{...n}}),Ae=(e,t,r={},o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/activity`,{...o,params:{...r}}),ke=(e,t,r={},o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/activity/page`,{...o,params:{...r}}),Ee=(e,t={},r)=>e.fetchWithTimeout(`${ee}/governance/proposals`,{...r,params:{...t}}),Ie=(e,t={},r)=>e.fetchWithTimeout(`${ee}/positions`,{...r,params:{...t}}),qe=(e,t={},r)=>e.fetchWithTimeout(`${ee}/participants`,{...r,params:{...t}}),Re=(e,t={},r)=>e.fetchWithTimeout(`${ee}/liquidations/leaderboard`,{...r,params:{...t}}),Be=(e,t={},r)=>e.fetchWithTimeout(`${ee}/distribution`,{...r,params:{...t}}),Pe=(e,t={},r)=>e.fetchWithTimeout(`${ee}/campaign/leaderboard`,{...r,params:{...t}}),Ue=(e,t,r)=>e.fetchWithTimeout(`${ee}/stats/history`,{...r,params:{...t}}),Oe=(e,t,r)=>e.fetchWithTimeout(`${ee}/revenue`,{...r,params:{...t}}),Ce=(e,t,r)=>e.fetchWithTimeout(`${ee}/revenue/fees`,{...r,params:{...t}}),$e=(e,t,r)=>e.fetchWithTimeout(`${ee}/liquidations`,{...r,params:{...t}}),Ne=(e,t,r)=>e.fetchWithTimeout(`${ee}/volume`,{...r,params:{...t}}),Le=(e,t,r)=>e.fetchWithTimeout(`${ee}/active-users`,{...r,params:{...t}}),Me=(e,t,r)=>e.fetchWithTimeout(`${ee}/rate-spread`,{...r,params:{...t}}),We=(e,t,r)=>e.fetchWithTimeout(`${ee}/defillama`,{...r,params:{...t}}),De=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/history`,{...o,params:{...r}}),Fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/pnl`,{...r,params:{accountId:t}}),ze=(e,t,r)=>e.fetchWithTimeout(`${ee}/pnl/scope`,{...r,params:{scope:t}}),Ge=(e,t,r)=>e.fetchWithTimeout(`${ee}/campaign/me`,{...r,params:{owner:t}}),Ve=e=>({context:t=>re(e,t),liveState:t=>oe(e,t),marketsDetailed:t=>ne(e,t),assets:t=>ae(e,t),hubs:t=>ie(e,t),spokes:t=>se(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?le(e,t,r):le(e,{},t),reserve:(t,r,o,n)=>ue(e,t,r,o,n),asset:(t,r)=>ce(e,t,r),hub:(t,r)=>pe(e,t,r),spoke:(t,r)=>fe(e,t,r),userPositions:(t,r)=>de(e,t,r),accountPositions:(t,r)=>he(e,t,r),walletBalance:(t,r,o)=>ge(e,t,r,o),assetPage:(t,r,o)=>me(e,t,r,o),assetMarkets:(t,r,o)=>ye(e,t,r,o),reserveHolders:(t,r,o,n,a)=>be(e,t,r,o,n,a),hubHolders:(t,r,o)=>we(e,t,r,o),spokeHolders:(t,r,o)=>Se(e,t,r,o),assetGraph:(t,r,o)=>_e(e,t,r,o),hubGraph:(t,r,o)=>ve(e,t,r,o),spokeGraph:(t,r,o)=>Te(e,t,r,o),reserveGraph:(t,r,o,n,a)=>xe(e,t,r,o,n,a),userActivity:(t,r={},o)=>Ae(e,t,r,o),userActivityPage:(t,r={},o)=>ke(e,t,r,o),governanceProposals:(t={},r)=>Ee(e,t,r),positionsLeaderboard:(t={},r)=>Ie(e,t,r),participants:(t={},r)=>qe(e,t,r),liquidationsLeaderboard:(t={},r)=>Re(e,t,r),distribution:(t={},r)=>Be(e,t,r),campaignLeaderboard:(t={},r)=>Pe(e,t,r),statsHistory:(t,r)=>Ue(e,t,r),revenue:(t,r)=>Oe(e,t,r),feeRevenue:(t,r)=>Ce(e,t,r),liquidations:(t,r)=>$e(e,t,r),volume:(t,r)=>Ne(e,t,r),activeUsers:(t,r)=>Le(e,t,r),rateSpread:(t,r)=>Me(e,t,r),defillama:(t,r)=>We(e,t,r),userHistory:(t,r,o)=>De(e,t,r,o),positionsPnl:(t,r)=>Fe(e,t,r),pnlByScope:(t,r)=>ze(e,t,r),campaignMe:(t,r)=>Ge(e,t,r)}),Xe=e=>I({base_borrow_rate:d(e.baseBorrowRateRay),max_borrow_rate:d(e.maxBorrowRateRay),max_utilization:d(e.maxUtilizationRay),mid_utilization:d(e.midUtilizationRay),optimal_utilization:d(e.optimalUtilizationRay),reserve_factor:h(e.reserveFactorBps),slope1:d(e.slope1Ray),slope2:d(e.slope2Ray),slope3:d(e.slope3Ray)}),He=e=>I({asset_decimals:h(e.assetDecimals),asset_id:f(e.assetId),base_borrow_rate:d(e.baseBorrowRateRay),flashloan_fee:h(e.flashloanFeeBps),is_flashloanable:m(e.isFlashloanable),max_borrow_rate:d(e.maxBorrowRateRay),max_utilization:d(e.maxUtilizationRay),mid_utilization:d(e.midUtilizationRay),optimal_utilization:d(e.optimalUtilizationRay),reserve_factor:h(e.reserveFactorBps),slope1:d(e.slope1Ray),slope2:d(e.slope2Ray),slope3:d(e.slope3Ray)}),je=e=>I({max_borrow_positions:h(e.maxBorrowPositions),max_supply_positions:h(e.maxSupplyPositions)}),Ke=e=>{if("Token"in e&&e.Token)return S([b("Token"),f(e.Token)]);if("Ref"in e&&e.Ref)return S([b("Ref"),b(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Je=e=>{if("Stellar"in e)return S([b("Stellar"),f(e.Stellar)]);if("Symbol"in e)return S([b("Symbol"),b(e.Symbol)]);if("String"in e)return S([b("String"),y(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ye=e=>{if("Spot"===e)return S([b("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return S([b("Twap"),h(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ze=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return S([b(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Qe=e=>{if("Market"===e||"Fundamental"===e)return S([b(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},et=e=>{if("Reflector"in e){const t=e.Reflector;return S([b("Reflector"),I({asset:Je(t.asset),contract:f(t.contract),read_mode:Ye(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return S([b("MultiFeed"),I({contract:f(t.contract),feed_id:y(t.feedId),kind:Ze(t.kind),nature:Qe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},tt=e=>{const t=e;return I({decimals:h(t.decimals),max_stale_seconds:g(t.maxStaleSeconds),provider:et(t.provider)})},rt=e=>{if("RequireDisjoint"===e)return S([b("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return S([b("AllowShared"),S(t.map((e=>I({contract:f(e.contract),kind:Ze(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},ot=e=>{const t=e,r=t.sources??[];let o,n;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,n=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),n=Number(e.lowerRatioBps)}return I({asset_decimals:h(Number(t.assetDecimals)),independence:rt(t.independence),max_price_stale_seconds:g(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:d(String(t.maxSanityPriceWad)),min_sanity_price_wad:d(String(t.minSanityPriceWad)),sources:S(r.map((e=>(e=>{if("Feed"in e)return S([b("Feed"),tt(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return S([b("Scaled"),I({factor:tt(t.factor),max_factor_wad:d(t.maxFactorWad),min_factor_wad:d(t.minFactorWad),quote:Ke(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return S([b("LpShare"),I({key_a:Ke(t.keyA),key_b:Ke(t.keyB),kind:S([b(t.kind||"ConstantProduct")]),pool:f(t.pool),reserve_a_decimals:h(t.reserveADecimals),reserve_b_decimals:h(t.reserveBDecimals),share_decimals:h(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:I({lower_ratio_bps:h(n),upper_ratio_bps:h(o)})})},nt=ot;function at(e,t){return $(e,"upgrade",[_(t.wasmHash)])}function it(e,t){return $(e,"migrate",[h(t.newVersion)])}function st(e){return $(e,"pause",[])}function lt(e){return $(e,"unpause",[])}function ut(e,t){return $(e,"grant_role",[f(t.account),b(t.role)])}function ct(e,t){return $(e,"revoke_role",[f(t.account),b(t.role)])}function pt(e,t){return $(e,"transfer_ownership",[f(t.newOwner),h(t.liveUntilLedger)])}function ft(e){return $(e,"accept_ownership",[])}function dt(e,t){return $(e,"set_swap_aggregator",[f(t.aggregator)])}function ht(e,t){return $(e,"set_price_aggregator",[f(t.aggregator)])}const gt=dt;function mt(e,t){return $(e,"set_accumulator",[f(t.accumulator)])}function yt(e,t){return $(e,"set_position_limits",[je(t)])}function bt(e,t){return $(e,"approve_blend_pool",[f(t.pool)])}function wt(e,t){return $(e,"revoke_blend_pool",[f(t.pool)])}const St=bt,_t=wt;function vt(e,t){return $(e,"set_oracle",[Ke(t.key),ot(t.oracle)])}const Tt=vt;function xt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,n=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return $(e,"set_tolerance",[Ke(t.key),I({lower_ratio_bps:h(n),upper_ratio_bps:h(o)})])}function At(e,t){return $(e,"set_spoke_asset_flags",[h(t.spokeId),x(t.hubId,t.asset),m(t.paused),m(t.frozen),m(t.noSeize)])}function kt(e,t){return $(e,"set_oracle_sanity_bounds",[f(t.asset),d(t.minPriceWad),d(t.maxPriceWad)])}function Et(e,t){return $(e,"update_indexes",[f(e.caller),S(t.assets.map((e=>x(e.hubId,e.asset))))])}function It(e,t){return $(e,"renew_account",[f(e.caller),g(t.accountNonce)])}function qt(e,t){return $(e,"create_liquidity_pool",[h(t.hubId),f(t.asset),He(t.params)])}function Rt(e,t){return $(e,"upgrade_liquidity_pool_params",[x(t.hubId,t.asset),Xe(t.params)])}function Bt(e,t){return $(e,"claim_revenue",[f(e.caller),S(t.assets.map((e=>x(e.hubId,e.asset))))])}function Pt(e,t){return $(e,"add_rewards",[f(e.caller),k(t.rewards)])}function Ut(e,t){return $(e,"update_account_threshold",[f(e.caller),m(t.hasRisks),S(t.accountNonces.map((e=>g(e))))])}const Ot="00".repeat(32),Ct=e=>{if("string"==typeof e)return _(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)},$t=(e,...t)=>S([b(e),...t]),Nt=e=>I({asset:f(e.asset),hub_id:h(e.hubId),params:He(e.params)}),Lt=e=>I({hub_asset:x(e.hubId,e.asset),params:Xe(e.params)}),Mt=e=>I({new_owner:f(e.newOwner),live_until_ledger:h(e.liveUntilLedger)}),Wt=e=>I({key:Ke(e.key),oracle:ot(e.oracle)}),Dt=e=>I({asset:f(e.asset),bonus:h(e.bonus),borrow_cap:d(e.borrowCap),can_borrow:m(e.canBorrow),can_collateral:m(e.canCollateral),frozen:m(e.frozen),hub_id:h(e.hubId),paused:m(e.paused),liquidation_fees:h(e.liquidationFees),ltv:h(e.ltv),no_seize:m(e.noSeize),spoke_id:h(e.spokeId),supply_cap:d(e.supplyCap),threshold:h(e.threshold)}),Ft=e=>I({hub_asset:x(e.hubId,e.asset),spoke_id:h(e.spokeId)}),zt=e=>I({hf_for_max_bonus_wad:d(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:h(e.liquidationBonusFactorBps),spoke_id:h(e.spokeId),target_hf_wad:d(e.targetHfWad)}),Gt=e=>I({key:Ke(e.key),tolerance:h(e.tolerance)}),Vt=e=>I({account:f(e.account),role:b(e.role)});function Xt(e,t,r){if(!e.governanceAddress)throw new Error("Stellar governanceAddress is required");const o=new s.Contract(e.governanceAddress),n=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Ht=(e,t,r)=>Xt(e,"propose",[f(e.caller),t,Ct(r)]),jt=(e,t,r)=>Xt(e,"execute_self",[w(),t,Ct(r)]);function Kt(e,t,r){return Ht(e,$t("SetSwapAggregator",f(t.aggregator)),r)}function Jt(e,t,r){return Ht(e,$t("SetPriceAggregator",f(t.aggregator)),r)}const Yt=Kt;function Zt(e,t,r){return Ht(e,$t("SetAccumulator",f(t.accumulator)),r)}function Qt(e,t,r){return Ht(e,$t("SetPositionLimits",je(t)),r)}function er(e,t){return Ht(e,$t("CreateHub"),t)}function tr(e,t){return Ht(e,$t("AddSpoke"),t)}function rr(e,t,r){return Ht(e,$t("RemoveSpoke",h(t.spokeId)),r)}function or(e,t,r){return Ht(e,$t("AddAssetToSpoke",Dt(t)),r)}function nr(e,t,r){return Ht(e,$t("EditAssetInSpoke",Dt(t)),r)}function ar(e,t,r){return Ht(e,$t("RemoveAssetFromSpoke",Ft(t)),r)}function ir(e,t,r){return Ht(e,$t("SetSpokeLiquidationCurve",zt(t)),r)}function sr(e,t,r){return Ht(e,$t("SetPositionManager",f(t.manager),m(t.isActive)),r)}function lr(e,t,r){return Ht(e,$t("SetMinBorrowCollateralUsd",d(t.floorWad)),r)}function ur(e,t,r){return Ht(e,$t("ApproveToken",f(t.token)),r)}function cr(e,t,r){return Ht(e,$t("RevokeToken",f(t.token)),r)}function pr(e,t,r){return Ht(e,$t("ApproveBlendPool",f(t.pool)),r)}function fr(e,t,r){return Ht(e,$t("RevokeBlendPool",f(t.pool)),r)}function dr(e,t,r){return Ht(e,$t("CreateLiquidityPool",Nt(t)),r)}function hr(e,t,r){return Ht(e,$t("UpgradeLiquidityPoolParams",Lt(t)),r)}function gr(e,t,r){return Ht(e,$t("DeployPool",_(t.wasmHash)),r)}function mr(e,t,r){return Ht(e,$t("UpgradePool",_(t.wasmHash)),r)}function yr(e,t,r){return Ht(e,$t("UpgradeController",_(t.wasmHash)),r)}function br(e,t,r){return Ht(e,$t("MigrateController",h(t.newVersion)),r)}function wr(e,t,r){return Ht(e,$t("TransferCtrlOwnership",Mt(t)),r)}function Sr(e,t,r){return Ht(e,$t("ConfigureAssetOracle",Wt(t)),r)}const _r=Sr;function vr(e,t,r){return Ht(e,$t("EditOracleTolerance",Gt(t)),r)}function Tr(e,t,r){return Ht(e,$t("UpgradeGov",_(t.wasmHash)),r)}function xr(e,t,r){return Ht(e,$t("UpdateGovDelay",h(t.newDelay)),r)}function Ar(e,t,r){return Ht(e,$t("GrantGovRole",Vt(t)),r)}function kr(e,t,r){return Ht(e,$t("RevokeGovRole",Vt(t)),r)}function Er(e,t,r){return Ht(e,$t("TransferGovOwnership",Mt(t)),r)}function Ir(e,t){const r=S(t.argsXdr.map((e=>s.xdr.ScVal.fromXDR(e,"base64")))),o=Ct(t.predecessor??Ot);return Xt(e,"execute",[w(),f(t.target),b(t.functionName),r,o,Ct(t.salt)])}function qr(e,t,r){return jt(e,$t("UpgradeGov",_(t.wasmHash)),r)}function Rr(e,t,r){return jt(e,$t("UpdateGovDelay",h(t.newDelay)),r)}function Br(e,t,r){return jt(e,$t("GrantGovRole",Vt(t)),r)}function Pr(e,t,r){return jt(e,$t("RevokeGovRole",Vt(t)),r)}function Ur(e,t,r){return jt(e,$t("TransferGovOwnership",Mt(t)),r)}const Or=e=>S(e.map(f));function Cr(e,t,r){return Xt(e,"propose_canceller_reset",[Or(t.newCancellers),Ct(r)])}function $r(e,t,r){return Xt(e,"execute_canceller_reset",[v(t.executor,f),Or(t.newCancellers),Ct(r)])}function Nr(e,t){return Xt(e,"set_spoke_asset_flags",[f(e.caller),h(t.spokeId),x(t.hubId,t.asset),m(t.paused),m(t.frozen),m(t.noSeize)])}function Lr(e,t){return Xt(e,"set_oracle_sanity_bounds",[f(e.caller),f(t.asset),d(t.minPriceWad),d(t.maxPriceWad)])}function Mr(e){return Xt(e,"create_hub",[f(e.caller)])}function Wr(e){return Xt(e,"add_spoke",[f(e.caller)])}function Dr(e,t){return Xt(e,"revoke_role_immediate",[f(t.account),b(t.role)])}function Fr(e){return Xt(e,"pause",[f(e.caller)])}function zr(e,t){return Ht(e,$t("Unpause"),t)}const Gr=e=>e.toXDR("base64"),Vr=e=>s.xdr.ScVal.fromXDR(e,"base64"),Xr=e=>e.map((e=>String((0,s.scValToNative)(Vr(e))))).join(":"),Hr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),jr=e=>Number(e),Kr=e=>String(e),Jr=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),Yr=["None","Multiply","Long","Short"],Zr=["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"],Qr=e=>Array.isArray(e)?e:[],eo=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Zr[jr(o)]??Hr(o)),positionType:t,hubId:jr(e[1]),asset:Kr(e[2]),scaledAmountRay:Hr(e[3]),indexRay:Hr(e[4]),amount:Hr(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 o},to=e=>{return{owner:Kr(e[0]),spokeId:jr(e[1]),mode:(t=e[2],Yr[jr(t)]??"None")};var t},ro=e=>Array.isArray(e)?e[1]:void 0,oo=e=>{const t=(r=e,Array.isArray(r)?Kr(r[0]):Kr(r));var r;if("Token"===t)return{Token:Kr(ro(e))};if("Ref"===t)return{Ref:Kr(ro(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Kr(t.Token)};if(void 0!==t.Ref)return{Ref:Kr(t.Ref)}}return{Token:Kr(e)}},no=e=>{const t=e.tolerance??{};return{assetDecimals:jr(e.asset_decimals),maxPriceStaleSeconds:jr(e.max_price_stale_seconds),sources:Qr(e.sources).map((e=>e)),tolerance:{upperRatio:jr(t.upper_ratio_bps),lowerRatio:jr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Hr(e.min_sanity_price_wad),maxSanityPriceWad:Hr(e.max_sanity_price_wad)}},ao={"market:create":e=>({topic:"market:create",data:{hubId:jr(e.hub_id),baseAsset:Kr(e.base_asset),maxBorrowRate:Hr(e.max_borrow_rate),baseBorrowRate:Hr(e.base_borrow_rate),slope1:Hr(e.slope1),slope2:Hr(e.slope2),slope3:Hr(e.slope3),midUtilization:Hr(e.mid_utilization),optimalUtilization:Hr(e.optimal_utilization),maxUtilization:Hr(e.max_utilization),reserveFactor:jr(e.reserve_factor),marketAddress:Kr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Kr(e.asset),maxBorrowRateRay:Hr(e.max_borrow_rate),baseBorrowRateRay:Hr(e.base_borrow_rate),slope1Ray:Hr(e.slope1),slope2Ray:Hr(e.slope2),slope3Ray:Hr(e.slope3),midUtilizationRay:Hr(e.mid_utilization),optimalUtilizationRay:Hr(e.optimal_utilization),maxUtilizationRay:Hr(e.max_utilization),reserveFactorBps:jr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Qr(e).map((e=>{return t=Qr(e),{hubId:jr(t[0]),asset:Kr(t[1]),timestamp:jr(t[2]),supplyIndexRay:Hr(t[3]),borrowIndexRay:Hr(t[4]),cash:Hr(t[5]),suppliedRay:Hr(t[6]),borrowedRay:Hr(t[7]),revenueRay:Hr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Qr(e).map((e=>{const t=e;return{hubId:jr(t.hub_id),asset:Kr(t.asset),params:(r=t.params,{maxBorrowRateRay:Hr(r.max_borrow_rate),baseBorrowRateRay:Hr(r.base_borrow_rate),slope1Ray:Hr(r.slope1),slope2Ray:Hr(r.slope2),slope3Ray:Hr(r.slope3),midUtilizationRay:Hr(r.mid_utilization),optimalUtilizationRay:Hr(r.optimal_utilization),maxUtilizationRay:Hr(r.max_utilization),reserveFactorBps:jr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:jr(r.flashloan_fee),assetId:Kr(r.asset_id),assetDecimals:jr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Qr(e);return{topic:"position:batch_update",data:{accountId:Hr(t[0]),accountAttributes:to(Qr(t[1])),updates:[...Qr(t[2]).map((e=>eo(Qr(e),"Deposit"))),...Qr(t[3]).map((e=>eo(Qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:jr(e.hub_id),asset:Kr(e.asset),receiver:Kr(e.receiver),caller:Kr(e.caller),amount:Hr(e.amount),fee:Hr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:oo(e.key),oracle:no(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Kr(e.asset),oracle:no(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Kr(e.liquidator),accountId:Hr(e.account_id),repaidUsdWad:Hr(e.repaid_usd_wad),bonusBps:Hr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Hr(e.account_id),totalBorrowUsdWad:Hr(e.total_borrow_usd_wad),totalCollateralUsdWad:Hr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Kr(e.token),amount:Hr(e.amount),usdValueWad:Hr(e.usd_value_wad),accountId:Hr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:jr(e.hub_id),asset:Kr(e.asset),amount:Hr(e.amount),fee:Hr(e.fee),amountSent:Hr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Kr(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:Jr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Kr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Kr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Kr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Kr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Jr(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:Hr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Kr(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:Hr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Hr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:jr(t.liquidation_bonus_factor_bps)}}}},io=Object.freeze(Object.keys(ao));function so(e,t){const r=Xr(e),o=ao[r];return o?o((0,s.scValToNative)(Vr(t))):null}const lo=1e4;function uo(e,t){return`${e}-${BigInt(t).toString(10)}`}function co(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function po(e,t=0){return e*lo+t}function fo(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 ho=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()};async function go(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=ho(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,router:e.router,referralId:e.referralId,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function mo(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=ho(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()}const yo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,bo=e=>R(e).toXDR("base64");function wo(e,t){if(!e.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const r=new s.Contract(e.routerAddress),o=new s.Account(e.caller,e.sourceSequence),n=O(yo(t,e.referralId));return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(r.call("execute_strategy",f(e.caller),d(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function So(e,t){return wo(e,t)}function _o(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(xo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(xo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function vo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:_o(e,t)}const To=_o,xo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Ao(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function ko(e,t,r){const o=s.TransactionBuilder.fromXDR(t,r?.network?i[r.network]:"");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw Ao(r.invokedContractId,e);throw e}}async function Eo(e,t,r){return ko(e,t.xdr,r)}function Io(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 qo(e,t){return new Uint8Array(0)}const Ro=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 Bo(e){const t=new s.Account(e.caller,e.sourceSequence),r=new s.Contract(e.forwarderAddress).call("mint_and_forward",s.xdr.ScVal.scvBytes(Ro(e.message)),s.xdr.ScVal.scvBytes(Ro(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 Po={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."},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 Uo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=Po[r];return o?{code:r,...o}:null}})(),module.exports=o})();
|
|
2
|
+
"undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{var e={526(e,t){"use strict";t.byteLength=function(e){var t=s(e),r=t[0],o=t[1];return 3*(r+o)/4-o},t.toByteArray=function(e){var t,r,a=s(e),i=a[0],l=a[1],u=new n(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=o[e.charCodeAt(r)]<<18|o[e.charCodeAt(r+1)]<<12|o[e.charCodeAt(r+2)]<<6|o[e.charCodeAt(r+3)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===l&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===l&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,o=e.length,n=o%3,a=[],i=16383,s=0,u=o-n;s<u;s+=i)a.push(l(e,s,s+i>u?u:s+i));return 1===n?(t=e[o-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===n&&(t=(e[o-2]<<8)+e[o-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")};for(var r=[],o=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)r[i]=a[i],o[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,o){for(var n,a,i=[],s=t;s<o;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(r[(a=n)>>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const o=r(526),n=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const 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|g(e,t);let o=s(r);const n=o.write(e,t);return n!==r&&(o=o.slice(0,n)),o}(e,t);if(ArrayBuffer.isView(e))return function(e){if(K(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(K(e,ArrayBuffer)||e&&K(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(K(e,SharedArrayBuffer)||e&&K(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return l.from(o,t,r);const n=function(e){if(l.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return c(e),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 o=0;o<t;o+=1)r[o]=255&e[o];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let o;return o=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(o,l.prototype),o}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function g(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,o=arguments.length>2&&!0===arguments[2];if(!o&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(e).length;default:if(n)return o?-1:j(e).length;t=(""+t).toLowerCase(),n=!0}}function m(e,t,r){let o=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return q(this,t,r);case"base64":return I(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function y(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function b(e,t,r,o,n){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Y(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=l.from(t,o)),l.isBuffer(t))return 0===t.length?-1:w(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,o,n){let a,i=1,s=e.length,l=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;i=2,s/=2,l/=2,r/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(n){let o=-1;for(a=r;a<s;a++)if(u(e,a)===u(t,-1===o?0:a-o)){if(-1===o&&(o=a),a-o+1===l)return o*i}else-1!==o&&(a-=a-o),o=-1}else for(r+l>s&&(r=s-l),a=r;a>=0;a--){let r=!0;for(let o=0;o<l;o++)if(u(e,a+o)!==u(t,o)){r=!1;break}if(r)return a}return-1}function S(e,t,r,o){r=Number(r)||0;const n=e.length-r;o?(o=Number(o))>n&&(o=n):o=n;const a=t.length;let i;for(o>a/2&&(o=a/2),i=0;i<o;++i){const o=parseInt(t.substr(2*i,2),16);if(Y(o))return i;e[r+i]=o}return i}function v(e,t,r,o){return H(j(t,e.length-r),e,r,o)}function B(e,t,r,o){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,o)}function x(e,t,r,o){return H(X(t),e,r,o)}function _(e,t,r,o){return H(function(e,t){let r,o,n;const a=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)r=e.charCodeAt(i),o=r>>8,n=r%256,a.push(n),a.push(o);return a}(t,e.length-r),e,r,o)}function I(e,t,r){return 0===t&&r===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,r))}function T(e,t,r){r=Math.min(e.length,r);const o=[];let n=t;for(;n<r;){const t=e[n];let a=null,i=t>239?4:t>223?3:t>191?2:1;if(n+i<=r){let r,o,s,l;switch(i){case 1:t<128&&(a=t);break;case 2:r=e[n+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[n+1],o=e[n+2],128==(192&r)&&128==(192&o)&&(l=(15&t)<<12|(63&r)<<6|63&o,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[n+1],o=e[n+2],s=e[n+3],128==(192&r)&&128==(192&o)&&128==(192&s)&&(l=(15&t)<<18|(63&r)<<12|(63&o)<<6|63&s,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),n+=i}return function(e){const t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=R));return r}(o)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?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,o=t.length;for(let n=0,a=Math.min(r,o);n<a;++n)if(e[n]!==t[n]){r=e[n],o=t[n];break}return r<o?-1:o<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const o=l.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(K(t,Uint8Array))n+t.length>o.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(o,n)):Uint8Array.prototype.set.call(o,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(o,n)}n+=t.length}return o},l.byteLength=g,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?T(this,0,e):m.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},a&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,r,o,n){if(K(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===o&&(o=0),void 0===n&&(n=this.length),t<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(o>=n&&t>=r)return 0;if(o>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let a=(n>>>=0)-(o>>>=0),i=(r>>>=0)-(t>>>=0);const s=Math.min(a,i),u=this.slice(o,n),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,o){if(void 0===t)o="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)o=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===o&&(o="utf8")):(o=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let a=!1;for(;;)switch(o){case"hex":return S(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return B(this,e,t,r);case"base64":return x(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const R=4096;function A(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(127&e[n]);return o}function q(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(e[n]);return o}function E(e,t,r){const o=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>o)&&(r=o);let n="";for(let o=t;o<r;++o)n+=J[e[o]];return n}function k(e,t,r){const o=e.slice(t,r);let n="";for(let e=0;e<o.length-1;e+=2)n+=String.fromCharCode(o[e]+256*o[e+1]);return n}function 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,o,n,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<a)throw new RangeError('"value" argument is out of bounds');if(r+o>e.length)throw new RangeError("Index out of range")}function C(e,t,r,o,n){F(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a;let 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 $(e,t,r,o,n){F(t,o,n,e,r,7);let a=Number(t&BigInt(4294967295));e[r+7]=a,a>>=8,e[r+6]=a,a>>=8,e[r+5]=a,a>>=8,e[r+4]=a;let 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 O(e,t,r,o,n,a){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,o,a){return t=+t,r>>>=0,a||O(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function W(e,t,r,o,a){return t=+t,r>>>=0,a||O(e,0,r,8),n.write(e,t,r,o,52,8),r+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const o=this.subarray(e,t);return Object.setPrototypeOf(o,l.prototype),o},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return o},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let o=this[e+--t],n=1;for(;t>0&&(n*=256);)o+=this[e+--t]*n;return o},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||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=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(o)+(BigInt(n)<<BigInt(32))})),l.prototype.readBigUInt64BE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(o)<<BigInt(32))+BigInt(n)})),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let o=this[e],n=1,a=0;for(;++a<t&&(n*=256);)o+=this[e+a]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);let o=t,n=1,a=this[e+--o];for(;o>0&&(n*=256);)a+=this[e+--o]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||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=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),l.prototype.readBigInt64BE=Z((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||G(e,this.length-8);const o=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),n.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),n.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),n.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),n.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||P(this,e,t,r,Math.pow(2,8*r)-1,0);let n=1,a=0;for(this[t]=255&e;++a<r&&(n*=256);)this[t+a]=e/n&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||P(this,e,t,r,Math.pow(2,8*r)-1,0);let n=r-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||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=Z((function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=Z((function(e,t=0){return $(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);P(this,e,t,r,o-1,-o)}let n=0,a=1,i=0;for(this[t]=255&e;++n<r&&(a*=256);)e<0&&0===i&&0!==this[t+n-1]&&(i=1),this[t+n]=(e/a|0)-i&255;return t+r},l.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);P(this,e,t,r,o-1,-o)}let n=r-1,a=1,i=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===i&&0!==this[t+n+1]&&(i=1),this[t+n]=(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=Z((function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=Z((function(e,t=0){return $(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 W(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return W(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,o){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o<r&&(o=r),o===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t<o-r&&(o=e.length-t+r);const n=o-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,o):Uint8Array.prototype.set.call(e,this.subarray(r,o),t),n},l.prototype.fill=function(e,t,r,o){if("string"==typeof e){if("string"==typeof t?(o=t,t=0,r=this.length):"string"==typeof r&&(o=r,r=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!l.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===e.length){const t=e.charCodeAt(0);("utf8"===o&&t<128||"latin1"===o)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const a=l.isBuffer(e)?e:l.from(e,o),i=a.length;if(0===i)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=a[n%i]}return this};const N={};function D(e,t,r){N[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 M(e){let t="",r=e.length;const o="-"===e[0]?1:0;for(;r>=o+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function F(e,t,r,o,n,a){if(e>r||e<t){const o="bigint"==typeof t?"n":"";let n;throw n=a>3?0===t||t===BigInt(0)?`>= 0${o} and < 2${o} ** ${8*(a+1)}${o}`:`>= -(2${o} ** ${8*(a+1)-1}${o}) and < 2 ** ${8*(a+1)-1}${o}`:`>= ${t}${o} and <= ${r}${o}`,new N.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||G(t,e.length-(r+1))}(o,n,a)}function z(e,t){if("number"!=typeof e)throw new N.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new N.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new N.ERR_BUFFER_OUT_OF_BOUNDS;throw new N.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let o=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=M(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=M(n)),n+="n"),o+=` It must be ${t}. Received ${n}`,o}),RangeError);const V=/[^+/0-9A-Za-z-_]/g;function j(e,t){let r;t=t||1/0;const o=e.length;let n=null;const a=[];for(let i=0;i<o;++i){if(r=e.charCodeAt(i),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===o){(t-=3)>-1&&a.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&a.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function X(e){return o.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(V,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(e,t,r,o){let n;for(n=0;n<o&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const o=16*r;for(let n=0;n<16;++n)t[o+n]=e[r]+e[n]}return t}();function Z(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},251(e,t){t.read=function(e,t,r,o,n){var a,i,s=8*n-o-1,l=(1<<s)-1,u=l>>1,c=-7,d=r?n-1:0,p=r?-1:1,f=e[t+d];for(d+=p,a=f&(1<<-c)-1,f>>=-c,c+=s;c>0;a=256*a+e[t+d],d+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=o;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,o),a-=u}return(f?-1:1)*i*Math.pow(2,a-o)},t.write=function(e,t,r,o,n,a){var i,s,l,u=8*a-n-1,c=(1<<u)-1,d=c>>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=o?0:a-1,h=o?1:-1,g=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,n),i+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,n),i=0));n>=8;e[r+f]=255&s,f+=h,s/=256,n-=8);for(i=i<<n|s,u+=n;u>0;e[r+f]=255&i,f+=h,i/=256,u-=8);e[r+f-h]|=128*g}},387(e,t,r){"use strict";r.d(t,{GW:()=>a});var o,n=r(564);!function(e){e.MAINNET="1",e.DEVNET="D"}(o||(o={}));class a{apiUrl;chain;init;config;constructor(e){if(!e?.apiUrl?.trim())throw new Error("XOXNOClient: apiUrl is required");const{chain:t=o.MAINNET,apiUrl:r,...a}=e;this.apiUrl=r.trim().replace(/\/$/,""),this.chain=t,this.init=a,this.config=t==o.MAINNET?{mediaUrl:"https://media.xoxno.com",gatewayUrl:"https://gateway.xoxno.com",XO_SC:n.s0,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.V,Manager_SC:n.Rh,P2P_SC:n.EP}:{mediaUrl:"https://devnet-media.xoxno.com",gatewayUrl:"https://devnet-gateway.xoxno.com",XO_SC:n.cM,FM_SC:n.ZZ,DR_SC:n.sM,KG_SC:n.KL,Staking_SC:n.J6,Manager_SC:n.Ff,P2P_SC:n.gx}}fetchWithTimeout=async(e,{params:t,...r}={})=>{const{next:o,cache:n,debug:a,timeout:i,...s}=this.init,{next:l,cache:u,debug:c,timeout:d,headers:p,method:f="GET",...h}=r,g=p?.Authorization,m="Bearer undefined"===g?void 0:g,y="GET"!==f&&"HEAD"!==f&&"PUT"!==f,b={...p,Referer:"https://xoxno.sdk","User-Agent":"XOXNO/1.0/SDK",...y?{"Content-Type":"application/json"}:{},...m?{Authorization:m}:{}},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,...B}=o??{},{revalidate:x,..._}=l??{},I="GET"!==f||m?void 0:x??v,T="GET"!==f||m||I?void 0:u??n,R=h.body,A=d??i??(null==R?3e4:0),q=A>0?AbortSignal.timeout(A):void 0,E=h.signal??s.signal,k=q&&E?AbortSignal.any([E,q]):q??E,U={...s,...h,method:f,...Object.keys(b).length?{headers:b}:{},...k?{signal:k}:{},cache:T,next:{...B,..._,revalidate:I}};(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})),C=await P.text();if(!P.ok){let e;try{e=JSON.parse(C)}catch{e={message:C}}const t=[S,P.status,P.statusText,e.message].filter(Boolean).join(";;");throw new Error(t)}try{return JSON.parse(C)}catch{return C}}}},564(e,t,r){"use strict";r.d(t,{EP:()=>u,Ff:()=>p,J6:()=>d,KL:()=>i,Rh:()=>l,V:()=>s,ZZ:()=>n,cM:()=>c,gx:()=>f,s0:()=>o,sM:()=>a});const o="erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8",n="erd1qqqqqqqqqqqqqpgq705fxpfrjne0tl3ece0rrspykq88mynn4kxs2cg43s",a="erd1qqqqqqqqqqqqqpgqd9rvv2n378e27jcts8vfwynpx0gfl5ufz6hqhfy0u0",i="erd1qqqqqqqqqqqqqpgq8xwzu82v8ex3h4ayl5lsvxqxnhecpwyvwe0sf2qj4e",s="erd1qqqqqqqqqqqqqpgqvpkd3g3uwludduv3797j54qt6c888wa59w2shntt6z",l="erd1qqqqqqqqqqqqqpgqg9fa0dmpn8fu3fnleeqn5zt8rl8mdqjkys5s2gtas7",u="erd1qqqqqqqqqqqqqpgq47y8hnct68v6asjv6gxem6h9rumn9frzah0skhxxt6",c="erd1qqqqqqqqqqqqqpgql0dnz6n5hpuw8cptlt00khd0nn4ja8eadsfq2xrqw4",d="erd1qqqqqqqqqqqqqpgqsc5hnewwpep8qq0d7kjjzrquapuucrygah0s85zres",p="erd1qqqqqqqqqqqqqpgqluclyhfsa2uw7q9cjwd8knk989hg57u8ah0slq2nlr",f="erd1qqqqqqqqqqqqqpgqfja7ukpngrun78ueq583l0vd6aj4ekhrah0sa9wyrv"}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={exports:{}};return e[o](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";r.r(o),r.d(o,{BPS:()=>Co,DEFAULT_MIN_BORROW_COLLATERAL_USD_WAD:()=>hn,LIQUIDATION_BUFFER_BPS:()=>Un,RAY:()=>Uo,RAY_DECIMALS:()=>$o,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>Ct,STELLAR_LENDING_TOPICS:()=>io,STELLAR_NETWORKS:()=>t,STELLAR_NETWORK_PASSPHRASE:()=>i,SYNTHETIC_EVENT_ORDER_STRIDE:()=>lo,WAD:()=>Po,WAD_DECIMALS:()=>Oo,XOXNOClient:()=>e.GW,aggregateAccountRisk:()=>En,annualBorrowRateRay:()=>cn,baseToRay:()=>Zo,baseToShort:()=>on,baseValueWad:()=>en,buildLiveSnapshot:()=>Sn,buildSameTokenRepaySwapSteps:()=>qo,buildStellarAcceptOwnershipTx:()=>pt,buildStellarAddRewardsTx:()=>Ut,buildStellarApproveBlendPoolTx:()=>bt,buildStellarApproveTokenTx:()=>St,buildStellarBatchSwapTx:()=>So,buildStellarBorrowBatchTx:()=>D,buildStellarBorrowTx:()=>M,buildStellarCctpForwardTx:()=>ko,buildStellarClaimRevenueTx:()=>kt,buildStellarCreateLiquidityPoolTx:()=>qt,buildStellarExecuteCancellerResetTx:()=>Or,buildStellarExecuteStrategyTx:()=>wo,buildStellarFlashLoanTx:()=>H,buildStellarGovernanceAddSpokeImmediateTx:()=>Dr,buildStellarGovernanceCreateHubImmediateTx:()=>Nr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>qr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>kr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>Ur,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Pr,buildStellarGovernanceExecuteTx:()=>Ar,buildStellarGovernanceExecuteUpdateDelayTx:()=>Er,buildStellarGovernancePauseTx:()=>Fr,buildStellarGovernanceRevokeRoleImmediateTx:()=>Mr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Wr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>Lr,buildStellarGrantRoleTx:()=>ut,buildStellarLendingIdentifier:()=>uo,buildStellarLiquidateTx:()=>j,buildStellarMigrateFromBlendTx:()=>K,buildStellarMigrateTx:()=>it,buildStellarMultiplyTx:()=>Y,buildStellarPauseTx:()=>st,buildStellarProposeAddAssetToSpokeTx:()=>or,buildStellarProposeAddSpokeTx:()=>tr,buildStellarProposeApproveBlendPoolTx:()=>dr,buildStellarProposeApproveTokenTx:()=>ur,buildStellarProposeCancellerResetTx:()=>$r,buildStellarProposeConfigureAssetOracleTx:()=>Sr,buildStellarProposeConfigureMarketOracleTx:()=>vr,buildStellarProposeCreateHubTx:()=>er,buildStellarProposeCreateLiquidityPoolTx:()=>fr,buildStellarProposeDeployPoolTx:()=>gr,buildStellarProposeEditAssetInSpokeTx:()=>nr,buildStellarProposeEditOracleToleranceTx:()=>Br,buildStellarProposeGovernanceUpgradeTx:()=>xr,buildStellarProposeGrantGovernanceRoleTx:()=>Ir,buildStellarProposeMigrateControllerTx:()=>br,buildStellarProposeRemoveAssetFromSpokeTx:()=>ar,buildStellarProposeRemoveSpokeTx:()=>rr,buildStellarProposeRevokeBlendPoolTx:()=>pr,buildStellarProposeRevokeGovernanceRoleTx:()=>Tr,buildStellarProposeRevokeTokenTx:()=>cr,buildStellarProposeSetAccumulatorTx:()=>Zt,buildStellarProposeSetAggregatorTx:()=>Jt,buildStellarProposeSetMinBorrowCollatTx:()=>lr,buildStellarProposeSetPositionLimitsTx:()=>Qt,buildStellarProposeSetPositionManagerTx:()=>sr,buildStellarProposeSetPriceAggregatorTx:()=>Yt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>ir,buildStellarProposeSetSwapAggregatorTx:()=>Kt,buildStellarProposeTransferCtrlOwnershipTx:()=>wr,buildStellarProposeTransferGovOwnTx:()=>Rr,buildStellarProposeUnpauseTx:()=>zr,buildStellarProposeUpdateDelayTx:()=>_r,buildStellarProposeUpgradeControllerTx:()=>yr,buildStellarProposeUpgradePoolParamsTx:()=>hr,buildStellarProposeUpgradePoolTx:()=>mr,buildStellarRenewAccountTx:()=>At,buildStellarRepayBatchTx:()=>G,buildStellarRepayDebtWithCollateralTx:()=>Q,buildStellarRepayTx:()=>V,buildStellarRevokeBlendPoolTx:()=>wt,buildStellarRevokeRoleTx:()=>ct,buildStellarRevokeTokenTx:()=>vt,buildStellarSetAccumulatorTx:()=>mt,buildStellarSetAggregatorTx:()=>gt,buildStellarSetMarketOracleConfigTx:()=>xt,buildStellarSetOracleSanityBoundsTx:()=>Tt,buildStellarSetOracleToleranceTx:()=>_t,buildStellarSetOracleTx:()=>Bt,buildStellarSetPositionLimitsTx:()=>yt,buildStellarSetPriceAggregatorTx:()=>ht,buildStellarSetSpokeAssetFlagsTx:()=>It,buildStellarSetSwapAggregatorTx:()=>ft,buildStellarSupplyBatchTx:()=>W,buildStellarSupplyTx:()=>N,buildStellarSwapCollateralTx:()=>Z,buildStellarSwapDebtTx:()=>J,buildStellarTransferOwnershipTx:()=>dt,buildStellarUnpauseTx:()=>lt,buildStellarUpdateAccountThresholdTx:()=>Pt,buildStellarUpdateIndexesTx:()=>Rt,buildStellarUpgradeControllerTx:()=>at,buildStellarUpgradeLiquidityPoolParamsTx:()=>Et,buildStellarWithdrawBatchTx:()=>F,buildStellarWithdrawTx:()=>z,buildTx:()=>O,burnShares:()=>In,computeAccountRisk:()=>kn,decodeStellarLendingEvent:()=>so,decodeStellarLiquidateReturn:()=>X,depositRateRay:()=>dn,divByIntHalfUp:()=>Mo,encodeAssetOracle:()=>ot,encodeInterestRateModel:()=>je,encodeMarketOracleConfigInput:()=>nt,encodeMarketParamsRaw:()=>Xe,encodePositionLimits:()=>He,encodePriceKey:()=>Ke,encodeStrategyPayloadToRouteXdr:()=>bo,extractEventOrder:()=>co,getStellarAccountPositions:()=>he,getStellarActiveUsersSeries:()=>We,getStellarAggregatorQuote:()=>go,getStellarAsset:()=>ce,getStellarAssetGraph:()=>ve,getStellarAssetMarkets:()=>ye,getStellarAssetPage:()=>me,getStellarAssets:()=>ae,getStellarCampaignLeaderboard:()=>Ue,getStellarCampaignMe:()=>Ge,getStellarDefiLlamaDimensions:()=>De,getStellarDeployment:()=>a,getStellarDetailedMarkets:()=>ne,getStellarFeeRevenueSeries:()=>$e,getStellarGovernanceProposals:()=>Re,getStellarHolderDistribution:()=>ke,getStellarHub:()=>de,getStellarHubGraph:()=>Be,getStellarHubHolders:()=>we,getStellarHubs:()=>ie,getStellarLendingContext:()=>re,getStellarLendingLiveState:()=>oe,getStellarLiquidationsLeaderboard:()=>Ee,getStellarLiquidationsSeries:()=>Oe,getStellarParticipantCounts:()=>qe,getStellarPnlByScope:()=>ze,getStellarPositionsLeaderboard:()=>Ae,getStellarPositionsPnl:()=>Fe,getStellarQuoteTokens:()=>mo,getStellarRateSpreadSeries:()=>Ne,getStellarReserve:()=>ue,getStellarReserveGraph:()=>_e,getStellarReserveHolders:()=>be,getStellarReserves:()=>le,getStellarRevenueSeries:()=>Ce,getStellarSpoke:()=>pe,getStellarSpokeGraph:()=>xe,getStellarSpokeHolders:()=>Se,getStellarSpokes:()=>se,getStellarStatsHistory:()=>Pe,getStellarUserActivity:()=>Ie,getStellarUserActivityPage:()=>Te,getStellarUserHistory:()=>Me,getStellarUserPositions:()=>fe,getStellarVolumeSeries:()=>Le,getStellarWalletBalance:()=>ge,liveIndexKey:()=>wn,mapQuoteResponseToAggregatorSwap:()=>xo,mapQuoteResponseToStrategyPayload:()=>vo,mapQuoteResponseToStrategySwap:()=>Bo,mapSorobanError:()=>Zn,mapStellarPositionActivityType:()=>fo,maxBorrow:()=>Fn,maxRepay:()=>Vn,maxSupply:()=>Gn,maxWithdraw:()=>zn,mintShares:()=>_n,mulDivCeil:()=>No,mulDivFloor:()=>Wo,mulDivHalfUp:()=>Do,numberToScaled:()=>nn,numberToWad:()=>an,positionValueWad:()=>Qo,prepareStellarBuiltTx:()=>Ro,prepareStellarTxXdr:()=>To,projectAccountRisk:()=>Hn,projectReserveApy:()=>Yn,rayAprToApy:()=>fn,rayAprToNumber:()=>pn,rayToNumber:()=>rn,rescaleCeil:()=>Go,rescaleFloor:()=>zo,rescaleHalfUp:()=>Vo,reserveKey:()=>gn,resolveReserve:()=>mn,stellarLendingDispatchKey:()=>jr,stellarLendingRead:()=>Ve,stellarNetworks:()=>n,syntheticEventOrder:()=>po,tagStellarInvokedContractError:()=>Io,toBase64Xdr:()=>Gr,toBigInt:()=>Lo,toStellarPositionMode:()=>Ao,unscale:()=>Ho,unscaleBorrowCeil:()=>Yo,unscaleHalfUp:()=>Jo,unscaleSupplyFloor:()=>Ko,utilizationRay:()=>un,valueBasePosition:()=>Tn,valueScaledPosition:()=>xn,wadToNumber:()=>tn});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",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",aggregatorRouter:"CDNTWMWW2WGYTKIZTJYNGNVQQZI4KTC5BQRZ3275KESRX5T4O3AYECL5",governance:"CDS33JDOYH3F3FL4QUQ6DV4WKHML2AKHF4LADTZ57FRUAEBTE7NMY5FQ",priceAggregator:"CAALOOTIDXCX7D7FMQIBSSAJLPKOM3GMXS4UUSTDIG42JCRRJHOPUHOP",positionNftContract:"CDVN5JU675MEDPVRPCYC45AHFC275UH57WEU5OTFE4WFGZBNN7HTLPSY"}},n=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=1e6,p=e=>new s.Address(e).toScVal(),f=e=>new s.ScInt(e).toI128(),h=e=>s.xdr.ScVal.scvU32(e),g=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()},m=e=>s.xdr.ScVal.scvBool(e),y=e=>s.xdr.ScVal.scvString(e),b=e=>s.xdr.ScVal.scvSymbol(e),w=()=>s.xdr.ScVal.scvVoid(),S=e=>s.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=l.hp.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return s.xdr.ScVal.scvBytes(o)},B=(e,t)=>null==e?w():t(e),x=e=>s.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,s.xdr.ScVal.scvVec([p(t),f(r)]);var t,r}))),_=(e,t)=>A({asset:p(t),hub_id:h(e)}),I=(e,t,r)=>s.xdr.ScVal.scvVec([_(e,t),f(r)]),T=e=>s.xdr.ScVal.scvVec(e.map((e=>I(e.hubId,e.asset,e.amount)))),R=e=>{if("Transfer"===e)return S([b("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return S([b("Credit"),g(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},A=e=>{const t=Object.keys(e).sort().map((t=>new s.xdr.ScMapEntry({key:b(t),val:e[t]})));return s.xdr.ScVal.scvMap(t)};class q{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>=256)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>=126)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>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>d)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,n){this.ops.push([e,t,r,o,n])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const n=e.hops[o-1];if(n&&r.tokenIn!==n.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(c[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,n=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&n.push(r);const a=n.reduce(((e,r)=>e+t[r].splitPpm),0);if(a>d)throw new Error(`Stellar builder: split weights for one token sum to ${a}, above 1000000`);const i=a===d;let s=d;n.forEach(((e,o)=>{r[e]=!0;const a=t[e];let l;if(o+1===n.length&&i)l=0;else{if(0===s)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(a.splitPpm*d/s);s-=Math.min(a.splitPpm,s),l=128+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>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return l.hp.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const E=e=>{const t=new q(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),n=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,n)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[n,a]=o,[i,s]=e.preSwapFromA?[n,a]:[a,n];t.emit(c.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(i),t.asset(s))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const n=Number(e.referralId??0);if(!Number.isInteger(n)||n<0||n>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return A({amounts:s.xdr.ScVal.scvVec(t.amountList.map((e=>f(e)))),assets:s.xdr.ScVal.scvVec(t.assetList.map((e=>p(e)))),ops:s.xdr.ScVal.scvBytes(t.toBytes(r,o,n))})},k=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)},U=()=>s.xdr.ScVal.scvBytes(l.hp.alloc(0)),P=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return l.hp.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=l.hp.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},C=e=>{if("string"==typeof e)return k(P(e));if(e instanceof Uint8Array)return 0===e.length?U():k(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?k(P(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?k(P(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?k(P(e.bytes)):0===e.bytes.length?U():k(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length&&!t.burnPool&&!t.mintPool)throw new Error("Stellar builder: `steps.paths` needs a strategy path or a liquidity burn/mint operation");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!u.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>d)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==d)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),s.xdr.ScVal.scvBytes(l.hp.from(E(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},$=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 O(e,t,r){if(!e.controllerAddress)throw new Error("Stellar lending controllerAddress is required");const o=new s.Contract(e.controllerAddress),n=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function L(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("Stellar builder: spokeId must be an integer from 1 to 4294967295");return h(e)}function W(e,t){const r=t.accountNonce??0;return O(e,"supply",[p(e.caller),g(r),L(t.spokeId),T([...t.assets])])}function N(e,t){return W(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function D(e,t){return O(e,"borrow",[p(e.caller),g(t.accountNonce),T([...t.borrows]),B(t.to,p)])}function M(e,t){return D(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function F(e,t){return O(e,"withdraw",[p(e.caller),g(t.accountNonce),T([...t.withdrawals]),B(t.to,p)])}function z(e,t){return F(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function G(e,t){return O(e,"repay",[p(e.caller),g(t.accountNonce),T([...t.payments])])}function V(e,t){return G(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return O(e,"liquidate",[p(e.caller),g(t.accountNonce),T([...t.debtPayments]),R(t.seizeMode??"Transfer")])}function X(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 H(e,t){return O(e,"flash_loan",[p(e.caller),_(t.hubId,t.asset),f(t.amount),p(t.receiver),$(t.data)])}function K(e,t){return O(e,"migrate_from_blend",[p(e.caller),g(t.accountId),L(t.spokeId),h(t.hubId),p(t.blendPool),S(t.collateralTokens.map(p)),S(t.supplyTokens.map(p)),x(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function Y(e,t){const r=t.accountNonce??0;return O(e,"multiply",[p(e.caller),g(r),L(t.spokeId),_(t.collateral.hubId,t.collateral.asset),f(t.debtToFlashLoan),_(t.debt.hubId,t.debt.asset),h(t.mode),C(t.steps),B(t.initialPayment,(e=>I(e.hubId,e.asset,e.amount))),B(t.convertSwap,C)])}function J(e,t){return O(e,"swap_debt",[p(e.caller),g(t.accountNonce),_(t.existingDebt.hubId,t.existingDebt.asset),f(t.newDebtAmount),_(t.newDebt.hubId,t.newDebt.asset),C(t.steps)])}function Z(e,t){return O(e,"swap_collateral",[p(e.caller),g(t.accountNonce),_(t.current.hubId,t.current.asset),f(t.fromAmount),_(t.newCollateral.hubId,t.newCollateral.asset),C(t.steps)])}function Q(e,t){return O(e,"repay_debt_with_collateral",[p(e.caller),g(t.accountNonce),_(t.collateral.hubId,t.collateral.asset),f(t.collateralAmount),_(t.debt.hubId,t.debt.asset),C(t.steps),m(t.closePosition)])}const ee="/stellar-lending",te=encodeURIComponent,re=(e,t)=>e.fetchWithTimeout(`${ee}/context`,t),oe=(e,t)=>e.fetchWithTimeout(`${ee}/live-state`,t),ne=(e,t)=>e.fetchWithTimeout(`${ee}/markets/detailed`,t),ae=(e,t)=>e.fetchWithTimeout(`${ee}/assets`,t),ie=(e,t)=>e.fetchWithTimeout(`${ee}/hubs`,t),se=(e,t)=>e.fetchWithTimeout(`${ee}/spokes`,t),le=(e,t={},r)=>e.fetchWithTimeout(`${ee}/reserves`,{...r,params:{...t}}),ue=(e,t,r,o,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}`,n),ce=(e,t,r)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}`,r),de=(e,t,r)=>e.fetchWithTimeout(`${ee}/hubs/${t}`,r),pe=(e,t,r)=>e.fetchWithTimeout(`${ee}/spokes/${t}`,r),fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/positions`,r),he=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${te(t)}/positions`,r),ge=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/assets/${te(r)}/balance`,o),me=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/page`,{...o,params:{...r}}),ye=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/markets`,{...o,params:{side:r}}),be=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}/holders`,{...a,params:{side:n}}),we=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/holders`,{...o,params:{side:r}}),Se=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/holders`,{...o,params:{side:r}}),ve=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${te(t)}/graph`,{...o,params:{...r}}),Be=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/graph`,{...o,params:{...r}}),_e=(e,t,r,o,n,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${te(o)}/graph`,{...a,params:{...n}}),Ie=(e,t,r={},o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/activity`,{...o,params:{...r}}),Te=(e,t,r={},o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/activity/page`,{...o,params:{...r}}),Re=(e,t={},r)=>e.fetchWithTimeout(`${ee}/governance/proposals`,{...r,params:{...t}}),Ae=(e,t={},r)=>e.fetchWithTimeout(`${ee}/positions`,{...r,params:{...t}}),qe=(e,t={},r)=>e.fetchWithTimeout(`${ee}/participants`,{...r,params:{...t}}),Ee=(e,t={},r)=>e.fetchWithTimeout(`${ee}/liquidations/leaderboard`,{...r,params:{...t}}),ke=(e,t={},r)=>e.fetchWithTimeout(`${ee}/distribution`,{...r,params:{...t}}),Ue=(e,t={},r)=>e.fetchWithTimeout(`${ee}/campaign/leaderboard`,{...r,params:{...t}}),Pe=(e,t,r)=>e.fetchWithTimeout(`${ee}/stats/history`,{...r,params:{...t}}),Ce=(e,t,r)=>e.fetchWithTimeout(`${ee}/revenue`,{...r,params:{...t}}),$e=(e,t,r)=>e.fetchWithTimeout(`${ee}/revenue/fees`,{...r,params:{...t}}),Oe=(e,t,r)=>e.fetchWithTimeout(`${ee}/liquidations`,{...r,params:{...t}}),Le=(e,t,r)=>e.fetchWithTimeout(`${ee}/volume`,{...r,params:{...t}}),We=(e,t,r)=>e.fetchWithTimeout(`${ee}/active-users`,{...r,params:{...t}}),Ne=(e,t,r)=>e.fetchWithTimeout(`${ee}/rate-spread`,{...r,params:{...t}}),De=(e,t,r)=>e.fetchWithTimeout(`${ee}/defillama`,{...r,params:{...t}}),Me=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/users/${te(t)}/history`,{...o,params:{...r}}),Fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/pnl`,{...r,params:{accountId:t}}),ze=(e,t,r)=>e.fetchWithTimeout(`${ee}/pnl/scope`,{...r,params:{scope:t}}),Ge=(e,t,r)=>e.fetchWithTimeout(`${ee}/campaign/me`,{...r,params:{owner:t}}),Ve=e=>({context:t=>re(e,t),liveState:t=>oe(e,t),marketsDetailed:t=>ne(e,t),assets:t=>ae(e,t),hubs:t=>ie(e,t),spokes:t=>se(e,t),reserves:(t={},r)=>void 0!==r||"hubId"in t||"spokeId"in t||"asset"in t?le(e,t,r):le(e,{},t),reserve:(t,r,o,n)=>ue(e,t,r,o,n),asset:(t,r)=>ce(e,t,r),hub:(t,r)=>de(e,t,r),spoke:(t,r)=>pe(e,t,r),userPositions:(t,r)=>fe(e,t,r),accountPositions:(t,r)=>he(e,t,r),walletBalance:(t,r,o)=>ge(e,t,r,o),assetPage:(t,r,o)=>me(e,t,r,o),assetMarkets:(t,r,o)=>ye(e,t,r,o),reserveHolders:(t,r,o,n,a)=>be(e,t,r,o,n,a),hubHolders:(t,r,o)=>we(e,t,r,o),spokeHolders:(t,r,o)=>Se(e,t,r,o),assetGraph:(t,r,o)=>ve(e,t,r,o),hubGraph:(t,r,o)=>Be(e,t,r,o),spokeGraph:(t,r,o)=>xe(e,t,r,o),reserveGraph:(t,r,o,n,a)=>_e(e,t,r,o,n,a),userActivity:(t,r={},o)=>Ie(e,t,r,o),userActivityPage:(t,r={},o)=>Te(e,t,r,o),governanceProposals:(t={},r)=>Re(e,t,r),positionsLeaderboard:(t={},r)=>Ae(e,t,r),participants:(t={},r)=>qe(e,t,r),liquidationsLeaderboard:(t={},r)=>Ee(e,t,r),distribution:(t={},r)=>ke(e,t,r),campaignLeaderboard:(t={},r)=>Ue(e,t,r),statsHistory:(t,r)=>Pe(e,t,r),revenue:(t,r)=>Ce(e,t,r),feeRevenue:(t,r)=>$e(e,t,r),liquidations:(t,r)=>Oe(e,t,r),volume:(t,r)=>Le(e,t,r),activeUsers:(t,r)=>We(e,t,r),rateSpread:(t,r)=>Ne(e,t,r),defillama:(t,r)=>De(e,t,r),userHistory:(t,r,o)=>Me(e,t,r,o),positionsPnl:(t,r)=>Fe(e,t,r),pnlByScope:(t,r)=>ze(e,t,r),campaignMe:(t,r)=>Ge(e,t,r)}),je=e=>A({base_borrow_rate:f(e.baseBorrowRateRay),max_borrow_rate:f(e.maxBorrowRateRay),max_utilization:f(e.maxUtilizationRay),mid_utilization:f(e.midUtilizationRay),optimal_utilization:f(e.optimalUtilizationRay),reserve_factor:h(e.reserveFactorBps),slope1:f(e.slope1Ray),slope2:f(e.slope2Ray),slope3:f(e.slope3Ray)}),Xe=e=>A({asset_decimals:h(e.assetDecimals),asset_id:p(e.assetId),base_borrow_rate:f(e.baseBorrowRateRay),flashloan_fee:h(e.flashloanFeeBps),is_flashloanable:m(e.isFlashloanable),max_borrow_rate:f(e.maxBorrowRateRay),max_utilization:f(e.maxUtilizationRay),mid_utilization:f(e.midUtilizationRay),optimal_utilization:f(e.optimalUtilizationRay),reserve_factor:h(e.reserveFactorBps),slope1:f(e.slope1Ray),slope2:f(e.slope2Ray),slope3:f(e.slope3Ray)}),He=e=>A({max_borrow_positions:h(e.maxBorrowPositions),max_supply_positions:h(e.maxSupplyPositions)}),Ke=e=>{if("Token"in e&&e.Token)return S([b("Token"),p(e.Token)]);if("Ref"in e&&e.Ref)return S([b("Ref"),b(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Ye=e=>{if("Stellar"in e)return S([b("Stellar"),p(e.Stellar)]);if("Symbol"in e)return S([b("Symbol"),b(e.Symbol)]);if("String"in e)return S([b("String"),y(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Je=e=>{if("Spot"===e)return S([b("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return S([b("Twap"),h(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ze=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return S([b(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Qe=e=>{if("Market"===e||"Fundamental"===e)return S([b(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},et=e=>{if("Reflector"in e){const t=e.Reflector;return S([b("Reflector"),A({asset:Ye(t.asset),contract:p(t.contract),read_mode:Je(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return S([b("MultiFeed"),A({contract:p(t.contract),feed_id:y(t.feedId),kind:Ze(t.kind),nature:Qe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},tt=e=>{const t=e;return A({decimals:h(t.decimals),max_stale_seconds:g(t.maxStaleSeconds),provider:et(t.provider)})},rt=e=>{if("RequireDisjoint"===e)return S([b("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return S([b("AllowShared"),S(t.map((e=>A({contract:p(e.contract),kind:Ze(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},ot=e=>{const t=e,r=t.sources??[];let o,n;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,n=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),n=Number(e.lowerRatioBps)}return A({asset_decimals:h(Number(t.assetDecimals)),independence:rt(t.independence),max_price_stale_seconds:g(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:f(String(t.maxSanityPriceWad)),min_sanity_price_wad:f(String(t.minSanityPriceWad)),sources:S(r.map((e=>(e=>{if("Feed"in e)return S([b("Feed"),tt(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return S([b("Scaled"),A({factor:tt(t.factor),max_factor_wad:f(t.maxFactorWad),min_factor_wad:f(t.minFactorWad),quote:Ke(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return S([b("LpShare"),A({key_a:Ke(t.keyA),key_b:Ke(t.keyB),kind:S([b(t.kind||"ConstantProduct")]),pool:p(t.pool),reserve_a_decimals:h(t.reserveADecimals),reserve_b_decimals:h(t.reserveBDecimals),share_decimals:h(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:A({lower_ratio_bps:h(n),upper_ratio_bps:h(o)})})},nt=ot;function at(e,t){return O(e,"upgrade",[v(t.wasmHash)])}function it(e,t){return O(e,"migrate",[h(t.newVersion)])}function st(e){return O(e,"pause",[])}function lt(e){return O(e,"unpause",[])}function ut(e,t){return O(e,"grant_role",[p(t.account),b(t.role)])}function ct(e,t){return O(e,"revoke_role",[p(t.account),b(t.role)])}function dt(e,t){return O(e,"transfer_ownership",[p(t.newOwner),h(t.liveUntilLedger)])}function pt(e){return O(e,"accept_ownership",[])}function ft(e,t){return O(e,"set_swap_aggregator",[p(t.aggregator)])}function ht(e,t){return O(e,"set_price_aggregator",[p(t.aggregator)])}const gt=ft;function mt(e,t){return O(e,"set_accumulator",[p(t.accumulator)])}function yt(e,t){return O(e,"set_position_limits",[He(t)])}function bt(e,t){return O(e,"approve_blend_pool",[p(t.pool)])}function wt(e,t){return O(e,"revoke_blend_pool",[p(t.pool)])}const St=bt,vt=wt;function Bt(e,t){return O(e,"set_oracle",[Ke(t.key),ot(t.oracle)])}const xt=Bt;function _t(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,n=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return O(e,"set_tolerance",[Ke(t.key),A({lower_ratio_bps:h(n),upper_ratio_bps:h(o)})])}function It(e,t){return O(e,"set_spoke_asset_flags",[h(t.spokeId),_(t.hubId,t.asset),m(t.paused),m(t.frozen),m(t.noSeize)])}function Tt(e,t){return O(e,"set_oracle_sanity_bounds",[p(t.asset),f(t.minPriceWad),f(t.maxPriceWad)])}function Rt(e,t){return O(e,"update_indexes",[p(e.caller),S(t.assets.map((e=>_(e.hubId,e.asset))))])}function At(e,t){return O(e,"renew_account",[p(e.caller),g(t.accountNonce)])}function qt(e,t){return O(e,"create_liquidity_pool",[h(t.hubId),p(t.asset),Xe(t.params)])}function Et(e,t){return O(e,"upgrade_liquidity_pool_params",[_(t.hubId,t.asset),je(t.params)])}function kt(e,t){return O(e,"claim_revenue",[p(e.caller),S(t.assets.map((e=>_(e.hubId,e.asset))))])}function Ut(e,t){return O(e,"add_rewards",[p(e.caller),T(t.rewards)])}function Pt(e,t){return O(e,"update_account_threshold",[p(e.caller),m(t.hasRisks),S(t.accountNonces.map((e=>g(e))))])}const Ct="00".repeat(32),$t=e=>{if("string"==typeof e)return v(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)},Ot=(e,...t)=>S([b(e),...t]),Lt=e=>A({asset:p(e.asset),hub_id:h(e.hubId),params:Xe(e.params)}),Wt=e=>A({hub_asset:_(e.hubId,e.asset),params:je(e.params)}),Nt=e=>A({new_owner:p(e.newOwner),live_until_ledger:h(e.liveUntilLedger)}),Dt=e=>A({key:Ke(e.key),oracle:ot(e.oracle)}),Mt=e=>A({asset:p(e.asset),bonus:h(e.bonus),borrow_cap:f(e.borrowCap),can_borrow:m(e.canBorrow),can_collateral:m(e.canCollateral),frozen:m(e.frozen),hub_id:h(e.hubId),paused:m(e.paused),liquidation_fees:h(e.liquidationFees),ltv:h(e.ltv),no_seize:m(e.noSeize),spoke_id:h(e.spokeId),supply_cap:f(e.supplyCap),threshold:h(e.threshold)}),Ft=e=>A({hub_asset:_(e.hubId,e.asset),spoke_id:h(e.spokeId)}),zt=e=>A({hf_for_max_bonus_wad:f(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:h(e.liquidationBonusFactorBps),spoke_id:h(e.spokeId),target_hf_wad:f(e.targetHfWad)}),Gt=e=>A({key:Ke(e.key),tolerance:h(e.tolerance)}),Vt=e=>A({account:p(e.account),role:b(e.role)});function jt(e,t,r){if(!e.governanceAddress)throw new Error("Stellar governanceAddress is required");const o=new s.Contract(e.governanceAddress),n=new s.Account(e.caller,e.sourceSequence);return{xdr:new s.TransactionBuilder(n,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Xt=(e,t,r)=>jt(e,"propose",[p(e.caller),t,$t(r)]),Ht=(e,t,r)=>jt(e,"execute_self",[w(),t,$t(r)]);function Kt(e,t,r){return Xt(e,Ot("SetSwapAggregator",p(t.aggregator)),r)}function Yt(e,t,r){return Xt(e,Ot("SetPriceAggregator",p(t.aggregator)),r)}const Jt=Kt;function Zt(e,t,r){return Xt(e,Ot("SetAccumulator",p(t.accumulator)),r)}function Qt(e,t,r){return Xt(e,Ot("SetPositionLimits",He(t)),r)}function er(e,t){return Xt(e,Ot("CreateHub"),t)}function tr(e,t){return Xt(e,Ot("AddSpoke"),t)}function rr(e,t,r){return Xt(e,Ot("RemoveSpoke",h(t.spokeId)),r)}function or(e,t,r){return Xt(e,Ot("AddAssetToSpoke",Mt(t)),r)}function nr(e,t,r){return Xt(e,Ot("EditAssetInSpoke",Mt(t)),r)}function ar(e,t,r){return Xt(e,Ot("RemoveAssetFromSpoke",Ft(t)),r)}function ir(e,t,r){return Xt(e,Ot("SetSpokeLiquidationCurve",zt(t)),r)}function sr(e,t,r){return Xt(e,Ot("SetPositionManager",p(t.manager),m(t.isActive)),r)}function lr(e,t,r){return Xt(e,Ot("SetMinBorrowCollateralUsd",f(t.floorWad)),r)}function ur(e,t,r){return Xt(e,Ot("ApproveToken",p(t.token)),r)}function cr(e,t,r){return Xt(e,Ot("RevokeToken",p(t.token)),r)}function dr(e,t,r){return Xt(e,Ot("ApproveBlendPool",p(t.pool)),r)}function pr(e,t,r){return Xt(e,Ot("RevokeBlendPool",p(t.pool)),r)}function fr(e,t,r){return Xt(e,Ot("CreateLiquidityPool",Lt(t)),r)}function hr(e,t,r){return Xt(e,Ot("UpgradeLiquidityPoolParams",Wt(t)),r)}function gr(e,t,r){return Xt(e,Ot("DeployPool",v(t.wasmHash)),r)}function mr(e,t,r){return Xt(e,Ot("UpgradePool",v(t.wasmHash)),r)}function yr(e,t,r){return Xt(e,Ot("UpgradeController",v(t.wasmHash)),r)}function br(e,t,r){return Xt(e,Ot("MigrateController",h(t.newVersion)),r)}function wr(e,t,r){return Xt(e,Ot("TransferCtrlOwnership",Nt(t)),r)}function Sr(e,t,r){return Xt(e,Ot("ConfigureAssetOracle",Dt(t)),r)}const vr=Sr;function Br(e,t,r){return Xt(e,Ot("EditOracleTolerance",Gt(t)),r)}function xr(e,t,r){return Xt(e,Ot("UpgradeGov",v(t.wasmHash)),r)}function _r(e,t,r){return Xt(e,Ot("UpdateGovDelay",h(t.newDelay)),r)}function Ir(e,t,r){return Xt(e,Ot("GrantGovRole",Vt(t)),r)}function Tr(e,t,r){return Xt(e,Ot("RevokeGovRole",Vt(t)),r)}function Rr(e,t,r){return Xt(e,Ot("TransferGovOwnership",Nt(t)),r)}function Ar(e,t){const r=S(t.argsXdr.map((e=>s.xdr.ScVal.fromXDR(e,"base64")))),o=$t(t.predecessor??Ct);return jt(e,"execute",[w(),p(t.target),b(t.functionName),r,o,$t(t.salt)])}function qr(e,t,r){return Ht(e,Ot("UpgradeGov",v(t.wasmHash)),r)}function Er(e,t,r){return Ht(e,Ot("UpdateGovDelay",h(t.newDelay)),r)}function kr(e,t,r){return Ht(e,Ot("GrantGovRole",Vt(t)),r)}function Ur(e,t,r){return Ht(e,Ot("RevokeGovRole",Vt(t)),r)}function Pr(e,t,r){return Ht(e,Ot("TransferGovOwnership",Nt(t)),r)}const Cr=e=>S(e.map(p));function $r(e,t,r){return jt(e,"propose_canceller_reset",[Cr(t.newCancellers),$t(r)])}function Or(e,t,r){return jt(e,"execute_canceller_reset",[B(t.executor,p),Cr(t.newCancellers),$t(r)])}function Lr(e,t){return jt(e,"set_spoke_asset_flags",[p(e.caller),h(t.spokeId),_(t.hubId,t.asset),m(t.paused),m(t.frozen),m(t.noSeize)])}function Wr(e,t){return jt(e,"set_oracle_sanity_bounds",[p(e.caller),p(t.asset),f(t.minPriceWad),f(t.maxPriceWad)])}function Nr(e){return jt(e,"create_hub",[p(e.caller)])}function Dr(e){return jt(e,"add_spoke",[p(e.caller)])}function Mr(e,t){return jt(e,"revoke_role_immediate",[p(t.account),b(t.role)])}function Fr(e){return jt(e,"pause",[p(e.caller)])}function zr(e,t){return Xt(e,Ot("Unpause"),t)}const Gr=e=>e.toXDR("base64"),Vr=e=>s.xdr.ScVal.fromXDR(e,"base64"),jr=e=>e.map((e=>String((0,s.scValToNative)(Vr(e))))).join(":"),Xr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Hr=e=>Number(e),Kr=e=>String(e),Yr=e=>e instanceof Uint8Array?l.hp.from(e).toString("hex"):l.hp.isBuffer(e)?e.toString("hex"):String(e),Jr=["None","Multiply","Long","Short"],Zr=["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"],Qr=e=>Array.isArray(e)?e:[],eo=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Zr[Hr(o)]??Xr(o)),positionType:t,hubId:Hr(e[1]),asset:Kr(e[2]),scaledAmountRay:Xr(e[3]),indexRay:Xr(e[4]),amount:Xr(e[5]),liquidationThresholdBps:r?void 0:Hr(e[6]),liquidationBonusBps:r?void 0:Hr(e[7]),loanToValueBps:r?void 0:Hr(e[8]),liquidationFeesBps:r?void 0:Hr(e[9])};var o},to=e=>{return{owner:Kr(e[0]),spokeId:Hr(e[1]),mode:(t=e[2],Jr[Hr(t)]??"None")};var t},ro=e=>Array.isArray(e)?e[1]:void 0,oo=e=>{const t=(r=e,Array.isArray(r)?Kr(r[0]):Kr(r));var r;if("Token"===t)return{Token:Kr(ro(e))};if("Ref"===t)return{Ref:Kr(ro(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Kr(t.Token)};if(void 0!==t.Ref)return{Ref:Kr(t.Ref)}}return{Token:Kr(e)}},no=e=>{const t=e.tolerance??{};return{assetDecimals:Hr(e.asset_decimals),maxPriceStaleSeconds:Hr(e.max_price_stale_seconds),sources:Qr(e.sources).map((e=>e)),tolerance:{upperRatio:Hr(t.upper_ratio_bps),lowerRatio:Hr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Xr(e.min_sanity_price_wad),maxSanityPriceWad:Xr(e.max_sanity_price_wad)}},ao={"market:create":e=>({topic:"market:create",data:{hubId:Hr(e.hub_id),baseAsset:Kr(e.base_asset),maxBorrowRate:Xr(e.max_borrow_rate),baseBorrowRate:Xr(e.base_borrow_rate),slope1:Xr(e.slope1),slope2:Xr(e.slope2),slope3:Xr(e.slope3),midUtilization:Xr(e.mid_utilization),optimalUtilization:Xr(e.optimal_utilization),maxUtilization:Xr(e.max_utilization),reserveFactor:Hr(e.reserve_factor),marketAddress:Kr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Kr(e.asset),maxBorrowRateRay:Xr(e.max_borrow_rate),baseBorrowRateRay:Xr(e.base_borrow_rate),slope1Ray:Xr(e.slope1),slope2Ray:Xr(e.slope2),slope3Ray:Xr(e.slope3),midUtilizationRay:Xr(e.mid_utilization),optimalUtilizationRay:Xr(e.optimal_utilization),maxUtilizationRay:Xr(e.max_utilization),reserveFactorBps:Hr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Qr(e).map((e=>{return t=Qr(e),{hubId:Hr(t[0]),asset:Kr(t[1]),timestamp:Hr(t[2]),supplyIndexRay:Xr(t[3]),borrowIndexRay:Xr(t[4]),cash:Xr(t[5]),suppliedRay:Xr(t[6]),borrowedRay:Xr(t[7]),revenueRay:Xr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Qr(e).map((e=>{const t=e;return{hubId:Hr(t.hub_id),asset:Kr(t.asset),params:(r=t.params,{maxBorrowRateRay:Xr(r.max_borrow_rate),baseBorrowRateRay:Xr(r.base_borrow_rate),slope1Ray:Xr(r.slope1),slope2Ray:Xr(r.slope2),slope3Ray:Xr(r.slope3),midUtilizationRay:Xr(r.mid_utilization),optimalUtilizationRay:Xr(r.optimal_utilization),maxUtilizationRay:Xr(r.max_utilization),reserveFactorBps:Hr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Hr(r.flashloan_fee),assetId:Kr(r.asset_id),assetDecimals:Hr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Qr(e);return{topic:"position:batch_update",data:{accountId:Xr(t[0]),accountAttributes:to(Qr(t[1])),updates:[...Qr(t[2]).map((e=>eo(Qr(e),"Deposit"))),...Qr(t[3]).map((e=>eo(Qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Hr(e.hub_id),asset:Kr(e.asset),receiver:Kr(e.receiver),caller:Kr(e.caller),amount:Xr(e.amount),fee:Xr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:oo(e.key),oracle:no(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Kr(e.asset),oracle:no(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Kr(e.liquidator),accountId:Xr(e.account_id),repaidUsdWad:Xr(e.repaid_usd_wad),bonusBps:Xr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Xr(e.account_id),totalBorrowUsdWad:Xr(e.total_borrow_usd_wad),totalCollateralUsdWad:Xr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Kr(e.token),amount:Xr(e.amount),usdValueWad:Xr(e.usd_value_wad),accountId:Xr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Hr(e.hub_id),asset:Kr(e.asset),amount:Xr(e.amount),fee:Xr(e.fee),amountSent:Xr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Kr(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:Yr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Kr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Kr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Kr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Kr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Yr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Hr(e.max_supply_positions),maxBorrowPositions:Hr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Xr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Kr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Hr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Xr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Xr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Hr(t.liquidation_bonus_factor_bps)}}}},io=Object.freeze(Object.keys(ao));function so(e,t){const r=jr(e),o=ao[r];return o?o((0,s.scValToNative)(Vr(t))):null}const lo=1e4;function uo(e,t){return`${e}-${BigInt(t).toString(10)}`}function co(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function po(e,t=0){return e*lo+t}function fo(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 ho=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()};async function go(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=ho(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,router:e.router,referralId:e.referralId,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function mo(e){if(!e.baseUrl)throw new Error("Stellar quote baseUrl is required");const t=ho(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()}const yo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,bo=e=>E(e).toXDR("base64");function wo(e,t){if(!e.routerAddress)throw new Error("Stellar aggregator routerAddress is required");const r=new s.Contract(e.routerAddress),o=new s.Account(e.caller,e.sourceSequence),n=C(yo(t,e.referralId));return{xdr:new s.TransactionBuilder(o,{fee:e.fee??s.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(r.call("execute_strategy",p(e.caller),f(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function So(e,t){return wo(e,t)}function vo(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(_o),splitPpm:e.splitPpm}))):[{hops:e.hops.map(_o),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function Bo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:vo(e,t)}const xo=vo,_o=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Io(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function To(e,t,r){const o=s.TransactionBuilder.fromXDR(t,r?.network?i[r.network]:"");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw Io(r.invokedContractId,e);throw e}}async function Ro(e,t,r){return To(e,t.xdr,r)}function Ao(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 qo(e,t){return new Uint8Array(0)}const Eo=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 ko(e){const t=new s.Account(e.caller,e.sourceSequence),r=new s.Contract(e.forwarderAddress).call("mint_and_forward",s.xdr.ScVal.scvBytes(Eo(e.message)),s.xdr.ScVal.scvBytes(Eo(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 Uo=10n**27n,Po=10n**18n,Co=10000n,$o=27,Oo=18;function Lo(e,t="value"){let r;if("bigint"==typeof e)r=e;else if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Stellar math: ${t} must be a safe integer, got ${e}`);r=BigInt(e)}else{const o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`Stellar math: ${t} must be a decimal integer string, got "${e}"`);r=BigInt(o)}if(r<0n)throw new Error(`Stellar math: ${t} must be non-negative, got ${r}`);return r}function Wo(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return e*t/r}function No(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");const o=e*t,n=o/r;return o%r===0n?n:n+1n}function Do(e,t,r){if(0n===r)throw new Error("Stellar math: division by zero");return(e*t+r/2n)/r}function Mo(e,t){if(0n===t)throw new Error("Stellar math: division by zero");const r=e/t;return e%t>=t/2n+t%2n?r+1n:r}const Fo=e=>10n**BigInt(e);function zo(e,t,r){return t===r?e:r>t?e*Fo(r-t):e/Fo(t-r)}function Go(e,t,r){if(t===r)return e;if(r>t)return e*Fo(r-t);const o=Fo(t-r),n=e/o;return e%o===0n?n:n+1n}function Vo(e,t,r){return t===r?e:r>t?e*Fo(r-t):Mo(e,Fo(t-r))}const jo={floor:Wo,ceil:No,halfUp:Do},Xo={floor:zo,ceil:Go,halfUp:Vo};function Ho(e,t,r,o){return Xo[o](jo[o](e,t,Uo),$o,r)}function Ko(e,t,r){return Ho(Lo(e,"scaledRay"),Lo(t,"indexRay"),r,"floor")}function Yo(e,t,r){return Ho(Lo(e,"scaledRay"),Lo(t,"indexRay"),r,"ceil")}function Jo(e,t,r){return Ho(Lo(e,"scaledRay"),Lo(t,"indexRay"),r,"halfUp")}function Zo(e,t){if(t>$o)throw new Error(`Stellar math: decimals ${t} exceed RAY scale`);return zo(e,t,$o)}function Qo(e,t,r,o){const n=jo[o](e,t,Uo),a=Xo[o](n,$o,Oo);return jo[o](a,r,Po)}function en(e,t,r,o){const n=Xo[o](Zo(e,t),$o,Oo);return jo[o](n,r,Po)}const tn=e=>Number(e)/1e18,rn=e=>Number(e)/1e27,on=(e,t)=>Number(e)/10**t;function nn(e,t){if(!Number.isFinite(e)||e<=0||e>=1e21)return 0n;const r=e.toFixed(t),[o="0",n=""]=r.split(".");return BigInt(o+n.padEnd(t,"0"))}const an=e=>nn(e,Oo),sn=(e,t)=>Do(e,t,Uo),ln=(e,t)=>Do(e,Uo,t);function un(e,t){return 0n===t?0n:ln(e,t)}function cn(e,t){const r=e>Uo?Uo:e,o=Lo(t.baseRateRay,"irm.baseRateRay"),n=Lo(t.slope1Ray,"irm.slope1Ray"),a=Lo(t.slope2Ray,"irm.slope2Ray"),i=Lo(t.slope3Ray,"irm.slope3Ray"),s=Lo(t.midUtilizationRay,"irm.midUtilizationRay"),l=Lo(t.optimalUtilizationRay,"irm.optimalUtilizationRay"),u=Lo(t.maxBorrowRateRay,"irm.maxBorrowRateRay");let c;if(r<s)c=o+ln(sn(r,n),s);else if(r<l){const e=l-s;c=o+n+ln(sn(r-s,a),e)}else{const e=Uo-l;c=o+n+a+(0n===e?0n:ln(sn(r-l,i),e))}return c>u?u:c}function dn(e,t,r){return 0n===e||!Number.isInteger(r)||r<0||r>=1e4?0n:Do(sn(e,t),Co-BigInt(r),Co)}const pn=e=>rn(e),fn=e=>Math.expm1(rn(e)),hn=5n*Po,gn=(e,t,r)=>`${e}:${t}:${r}`;function mn(e,t,r,o){const n=Array.isArray(e)?e:void 0,a=n?n.find((e=>e.spokeId===t&&e.hubId===r&&e.asset===o)):e[gn(t,r,o)]??Object.values(e).find((e=>e.spokeId===t&&e.hubId===r&&e.asset===o));if(!a)throw new Error(`Stellar math: no reserve for ${gn(t,r,o)}`);return a}const yn=/^0*[1-9]\d*$/,bn=e=>"string"==typeof e&&yn.test(e)?BigInt(e).toString():null,wn=(e,t)=>`${e}:${t}`;function Sn(e){const t=new Map,r=new Map,o=new Set,n=new Set;for(const a of e?.indexes??[]){const e=wn(a.hubId,a.asset),i=bn(a.supplyIndex),s=bn(a.borrowIndex),l=bn(a.usdPrice),u=t.get(e),c=u&&bn(u.supplyIndex)===i&&bn(u.borrowIndex)===s&&bn(u.usdPrice)===l;null==i||null==s||null==l||u&&!c?o.add(e):u||t.set(e,a);const d=!1===a.valid||!0===a.stale||!0===a.deviation,p=r.get(a.asset);null==l||d||void 0!==p&&p.toString()!==l?n.add(a.asset):void 0===p&&r.set(a.asset,BigInt(l))}for(const e of o)t.delete(e);for(const e of n)r.delete(e);return{indexes:t,prices:r,rejectedIndexKeys:o,rejectedAssets:n}}const vn=(e,t)=>Wo(e,BigInt(t),Co);function Bn(e,t,r,o){const n="supply"===e.side,a=Math.min(e.entryLtvBps,e.entryLiquidationThresholdBps);return{side:e.side,hubId:e.hubId,asset:e.asset,decimals:e.decimals,scaledRay:e.scaledRay.toString(),indexRay:e.indexRay.toString(),usdPriceWad:e.priceWad.toString(),usdPrice:tn(e.priceWad),amountBase:t.toString(),amountShort:on(t,e.decimals),usdWad:r.toString(),usd:tn(r),gateUsdWad:o.toString(),entryLtvBps:e.entryLtvBps,entryLiquidationThresholdBps:e.entryLiquidationThresholdBps,entryLiquidationBonusBps:e.entryLiquidationBonusBps,entryLiquidationFeesBps:e.entryLiquidationFeesBps,ltvWeightedUsdWad:n?vn(o,a).toString():"0",liquidationWeightedUsdWad:n?vn(o,e.entryLiquidationThresholdBps).toString():"0",liveDataUsed:e.liveDataUsed}}function xn(e){if("supply"===e.side)return Bn(e,Ho(e.scaledRay,e.indexRay,e.decimals,"floor"),Qo(e.scaledRay,e.indexRay,e.priceWad,"halfUp"),Qo(e.scaledRay,e.indexRay,e.priceWad,"floor"));const t=Ho(e.scaledRay,e.indexRay,e.decimals,"ceil"),r=Qo(e.scaledRay,e.indexRay,e.priceWad,"ceil");return Bn(e,t,r,r)}function _n(e,t,r,o){const n=Zo(t,r);return"supply"===e?Wo(n,Uo,o):No(n,Uo,o)}function In(e,t,r,o){const n=Zo(t,r);return"supply"===e?No(n,Uo,o):Wo(n,Uo,o)}function Tn(e,t){return xn({...e,scaledRay:_n(e.side,t,e.decimals,e.indexRay)})}const Rn=(...e)=>{for(const t of e){const e=bn(t);if(null!=e)return BigInt(e)}return Uo};function An(e,t,r,o){const n=Lo("supply"===e?t.supplyScaledRay:t.borrowScaledRay,`${e}ScaledRay`);if(0n===n)return null;const a=o.indexes.get(wn(t.hubId,t.asset)),i=o.prices.get(t.asset),s="supply"===e?Rn(a?.supplyIndex,t.liveSupplyIndexRay,r.liveSupplyIndexRay,t.supplyIndexRay):Rn(a?.borrowIndex,t.liveBorrowIndexRay,r.liveBorrowIndexRay,t.borrowIndexRay),l=i??an(r.usdPrice);return xn({side:e,hubId:t.hubId,asset:t.asset,decimals:r.assetDecimals,scaledRay:n,indexRay:s,priceWad:l,entryLtvBps:t.entryLtvBps,entryLiquidationThresholdBps:t.entryLiquidationThresholdBps,entryLiquidationBonusBps:t.entryLiquidationBonusBps,entryLiquidationFeesBps:t.entryLiquidationFeesBps,liveDataUsed:void 0!==a&&void 0!==i})}const qn=(e,t)=>e.reduce(((e,r)=>e+BigInt(t(r))),0n);function En(e,t,r,o,n){const a=qn(t,(e=>e.usdWad)),i=qn(t,(e=>e.ltvWeightedUsdWad)),s=qn(t,(e=>e.liquidationWeightedUsdWad)),l=qn(r,(e=>e.usdWad)),u=0n===l?null:Wo(s,Po,l),c=0n===s?0:Number(l)/Number(s)*100,d=i<o||i<=l?0n:i-l;return{...e,supplies:t,borrows:r,totalCollateralUsdWad:a.toString(),totalCollateralUsd:tn(a),ltvWeightedCollateralUsdWad:i.toString(),ltvWeightedCollateralUsd:tn(i),liquidationWeightedCollateralUsdWad:s.toString(),liquidationWeightedCollateralUsd:tn(s),totalDebtUsdWad:l.toString(),totalDebtUsd:tn(l),healthFactorWad:null===u?null:u.toString(),healthFactor:null===u?null:tn(u),healthPercent:c,borrowLimitUsdWad:i.toString(),borrowLimitUsd:tn(i),availableBorrowUsdWad:d.toString(),availableBorrowUsd:tn(d),minBorrowCollateralUsdWad:o.toString(),minBorrowCollateralUsd:tn(o),isLiquidatable:null!==u&&u<Po,liveDataValid:n}}function kn(e){const{positions:t,reserves:r,liveState:o}=e,n=t[0];if(!n)throw new Error("Stellar math: computeAccountRisk needs at least one position row");for(const e of t)if(e.accountId!==n.accountId)throw new Error(`Stellar math: computeAccountRisk received mixed account ids (${n.accountId}, ${e.accountId})`);const a=Sn(o),i=[],s=[];for(const e of t){const t=mn(r,e.spokeId,e.hubId,e.asset),o=An("supply",e,t,a);o&&i.push(o);const n=An("borrow",e,t,a);n&&s.push(n)}const l=null!=o?.minBorrowCollateralUsdWad?Lo(o.minBorrowCollateralUsdWad,"minBorrowCollateralUsdWad"):hn,u=void 0!==o&&[...i,...s].every((e=>e.liveDataUsed));return En({accountId:n.accountId,owner:n.owner,spokeId:n.spokeId,mode:n.positionMode},i,s,l,u)}const Un=200n,Pn=e=>e.reduce(((e,t)=>t.amount<e.amount?t:e)),Cn=e=>e<0n?0n:e,$n=(e,t,r,o)=>({amountBase:e.amount,amountShort:on(e.amount,t),isFullClose:r,reason:e.reason,projectedUtilization:o}),On=e=>({amountBase:0n,amountShort:0,isFullClose:!1,reason:e,projectedUtilization:null});function Ln(e){const t=e.assetDecimals,r=Lo(e.irm.maxUtilizationRay,"irm.maxUtilizationRay");return{suppliedBase:nn(e.hubPool.suppliedShort,t),borrowedBase:nn(e.hubPool.borrowedShort,t),cashBase:nn(e.availableLiquidityShort,t),spokeSuppliedBase:nn(e.suppliedShort,t),spokeBorrowedBase:nn(e.borrowedShort,t),maxUtilizationRay:r>=Uo?null:r}}const Wn=(e,t)=>e<=0n?null:Number(t)/Number(e);function Nn(e,t){if(e<=0n||!t(0n))return 0n;let r=0n,o=e+1n;for(;o-r>1n;){const e=(r+o)/2n;t(e)?r=e:o=e}return r}const Dn=16n,Mn=(e,t)=>e.find((e=>e.hubId===t.hubId&&e.asset===t.asset));function Fn(e,t,r){if(t.paused)return On("paused");if(t.frozen)return On("frozen");if(!t.isBorrowable)return On("cap");const o=t.assetDecimals,n=Ln(t),a=Mn(e.borrows,t),i=Sn(r).indexes.get(wn(t.hubId,t.asset)),s=a?BigInt(a.indexRay):Lo(i?.borrowIndex??t.liveBorrowIndexRay,"borrowIndex"),l=a?BigInt(a.usdPriceWad):function(e,t){return Sn(t).prices.get(e.asset)??an(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:Wo(t,10n**BigInt(o),l),n=e=>c+Qo(u+_n("borrow",e,o,s),s,l,"ceil");f.push({amount:0n===r?0n:Nn(r+Dn,(e=>n(e)<=d)),reason:"ltv"})}f.push({amount:Cn(Lo(t.borrowCap,"borrowCap")-n.spokeBorrowedBase),reason:"cap"});const h=Do(n.suppliedBase,Un,Co);f.push({amount:Cn(n.cashBase-h),reason:"liquidity"});const g=function(e,t){const r=e.maxUtilizationRay;if(null===r)return null;const o=Zo(e.suppliedBase,t);return 0n===o?null:Nn(Cn(Wo(e.suppliedBase,r,Uo)-e.borrowedBase)+Dn,(n=>un(Zo(e.borrowedBase+n,t),o)<=r))}(n,o);null!==g&&f.push({amount:g,reason:"utilizationCap"});const m=Pn(f);return $n(m,o,!1,Wn(n.suppliedBase,n.borrowedBase+m.amount))}function zn(e,t,r){if(t.paused)return On("paused");const o=Mn(e.supplies,t);if(!o)return On(null);const n=o.decimals,a=Ln(t),i=BigInt(o.scaledRay),s=BigInt(o.indexRay),l=BigInt(o.usdPriceWad),u=BigInt(o.amountBase),c=Ho(i,s,n,"halfUp"),d=BigInt(e.totalDebtUsdWad),p=BigInt(e.minBorrowCollateralUsdWad),f=BigInt(Math.min(o.entryLtvBps,o.entryLiquidationThresholdBps)),h=[];let g=!0;if(d>0n&&f>0n){const t=d>p?d:p,r=p>d?"minCollateral":"healthFactor",a=BigInt(e.ltvWeightedCollateralUsdWad)-BigInt(o.ltvWeightedUsdWad);if(a<t){g=!1;const e=t-a,u=No(e,Co,f),d=BigInt(o.gateUsdWad)-u,p=d<=0n?0n:Wo(d,10n**BigInt(n),l),m=c>0n?c-1n:0n,y=p+Dn>m?m:p+Dn,b=e=>{const t=In("supply",e,n,s);return Wo(Qo(t>=i?0n:i-t,s,l,"floor"),f,Co)};h.push({amount:Nn(y,(t=>b(t)>=e)),reason:r})}}h.push({amount:u,reason:null}),h.push({amount:a.cashBase,reason:"liquidity"});const m=function(e,t){const r=e.maxUtilizationRay;if(null===r||0n===e.borrowedBase)return null;if(0n===r)return 0n;const o=No(e.borrowedBase,Uo,r),n=e.suppliedBase<o?0n:e.suppliedBase-o+Dn,a=Zo(e.borrowedBase,t);return Nn(n>e.suppliedBase?e.suppliedBase:n,(o=>{const n=Zo(e.suppliedBase-o,t);return n>0n&&un(a,n)<=r}))}(a,n);null!==m&&h.push({amount:m,reason:"utilizationCap"});const y=Pn(h),b=g&&y.amount>=u;return $n(y,n,b,Wn(a.suppliedBase-y.amount,a.borrowedBase))}function Gn(e){if(e.paused)return On("paused");if(e.frozen)return On("frozen");const t=e.assetDecimals,r=Ln(e),o={amount:Cn(Lo(e.supplyCap,"supplyCap")-r.spokeSuppliedBase),reason:"cap"};return $n(o,t,!1,Wn(r.suppliedBase+o.amount,r.borrowedBase))}function Vn(e,t,r){if(t.paused)return On("paused");const o=Mn(e.borrows,t);if(!o)return On(null);const n=o.decimals,a=Ln(t),i=BigInt(o.amountBase),s=void 0===r?null:Lo(r,"walletBalance"),l=null!==s&&s<i?{amount:s,reason:"liquidity"}:{amount:i,reason:null};return $n(l,n,l.amount>=i,Wn(a.suppliedBase,Cn(a.borrowedBase-l.amount)))}const jn=(e,t)=>e.hubId===t.hubId&&e.asset===t.asset,Xn=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 Hn(e,t){const r=[...e.supplies],o=[...e.borrows];for(const e of t){const t="supply"===e.side?r:o,n=t.findIndex((t=>jn(t,e))),a=-1===n?void 0:t[n],i=Xn(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+_n(e.side,i,e.decimals,e.indexRay);else{const o=-i,n=o>=("supply"===e.side?Ho(t,e.indexRay,e.decimals,"halfUp"):BigInt(a.amountBase))?t:In(e.side,o,e.decimals,e.indexRay);r=n>=t?0n:t-n}s=0n===r?null:xn({...e,scaledRay:r})}else s=i<=0n?null:Tn(Kn(e),i);-1===n?s&&t.push(s):s?t[n]=s:t.splice(n,1)}return En({accountId:e.accountId,owner:e.owner,spokeId:e.spokeId,mode:e.mode},r,o,BigInt(e.minBorrowCollateralUsdWad),e.liveDataValid)}function Kn(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:Lo("supply"===e.side?t.liveSupplyIndexRay:t.liveBorrowIndexRay,"reserve live index"),priceWad:an(t.usdPrice),entryLtvBps:t.collateralFactorBps,entryLiquidationThresholdBps:t.liquidationThresholdBps,entryLiquidationBonusBps:t.liquidationPenaltyBps,entryLiquidationFeesBps:t.liquidationFeesBps,liveDataUsed:!1}}function Yn(e,t=0n,r=0n){const o=e.assetDecimals,n=e=>e<0n?0n:e,a=n(nn(e.hubPool.suppliedShort,o)+Xn(t)),i=un(Zo(n(nn(e.hubPool.borrowedShort,o)+Xn(r)),o),Zo(a,o)),s=cn(i,e.irm),l=dn(i,s,e.irm.reserveFactorBps);return{utilization:rn(i),utilizationRay:i.toString(),borrowAprRay:s.toString(),supplyAprRay:l.toString(),borrowApr:pn(s),supplyApr:pn(l),borrowApy:fn(s),supplyApy:fn(l)}}const Jn={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."},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 Zn(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=Jn[r];return o?{code:r,...o}:null}})(),module.exports=o})();
|
|
@@ -18,5 +18,6 @@ export * from './prepare.js';
|
|
|
18
18
|
export * from './position-mode.js';
|
|
19
19
|
export * from './repay-swap.js';
|
|
20
20
|
export * from './cctp.js';
|
|
21
|
+
export * from './math/index.js';
|
|
21
22
|
export type { StellarStrategySwapInput, StellarStrategySwapPathInput, StellarStrategySwapHopInput, } from './scval-encode.js';
|
|
22
23
|
export { mapSorobanError } from '../../utils/soroban-errors.js';
|