@xoxno/sdk-js 1.0.223 → 1.0.224

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