@xoxno/sdk-js 1.0.205 → 1.0.207

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{STELLAR_AGGREGATOR_ROUTER:()=>o,STELLAR_GOVERNANCE:()=>a,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>bt,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>zr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>Hr,XOXNO_LENDING_STELLAR_TICKER:()=>Xr,buildSameTokenRepaySwapSteps:()=>ho,buildStellarAcceptOwnershipTx:()=>Je,buildStellarAddRewardsTx:()=>gt,buildStellarApproveBlendPoolTx:()=>rt,buildStellarApproveTokenTx:()=>at,buildStellarBatchSwapTx:()=>no,buildStellarBorrowBatchTx:()=>W,buildStellarBorrowTx:()=>M,buildStellarCctpForwardTx:()=>So,buildStellarClaimRevenueTx:()=>ht,buildStellarCreateLiquidityPoolTx:()=>mt,buildStellarExecuteCancellerResetTx:()=>wr,buildStellarExecuteStrategyTx:()=>ao,buildStellarFlashLoanTx:()=>j,buildStellarGovernanceAddSpokeImmediateTx:()=>vr,buildStellarGovernanceCreateHubImmediateTx:()=>xr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>mr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>hr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>gr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Sr,buildStellarGovernanceExecuteTx:()=>pr,buildStellarGovernanceExecuteUpdateDelayTx:()=>fr,buildStellarGovernancePauseTx:()=>Rr,buildStellarGovernanceRevokeRoleImmediateTx:()=>kr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Tr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>yr,buildStellarGrantRoleTx:()=>He,buildStellarLendingIdentifier:()=>jr,buildStellarLiquidateTx:()=>H,buildStellarMigrateFromBlendTx:()=>Q,buildStellarMigrateTx:()=>ze,buildStellarMultiplyTx:()=>J,buildStellarPauseTx:()=>Fe,buildStellarProposeAddAssetToSpokeTx:()=>Wt,buildStellarProposeAddSpokeTx:()=>Dt,buildStellarProposeApproveBlendPoolTx:()=>Qt,buildStellarProposeApproveTokenTx:()=>Ht,buildStellarProposeCancellerResetTx:()=>_r,buildStellarProposeConfigureAssetOracleTx:()=>ar,buildStellarProposeConfigureMarketOracleTx:()=>nr,buildStellarProposeCreateHubTx:()=>Gt,buildStellarProposeCreateLiquidityPoolTx:()=>Kt,buildStellarProposeDeployPoolTx:()=>Yt,buildStellarProposeEditAssetInSpokeTx:()=>Mt,buildStellarProposeEditOracleToleranceTx:()=>sr,buildStellarProposeGovernanceUpgradeTx:()=>ir,buildStellarProposeGrantGovernanceRoleTx:()=>ur,buildStellarProposeMigrateControllerTx:()=>rr,buildStellarProposeRemoveAssetFromSpokeTx:()=>Vt,buildStellarProposeRemoveSpokeTx:()=>qt,buildStellarProposeRevokeBlendPoolTx:()=>Jt,buildStellarProposeRevokeGovernanceRoleTx:()=>cr,buildStellarProposeRevokeTokenTx:()=>jt,buildStellarProposeSetAccumulatorTx:()=>Ct,buildStellarProposeSetAggregatorTx:()=>$t,buildStellarProposeSetMinBorrowCollatTx:()=>Xt,buildStellarProposeSetPositionLimitsTx:()=>Ut,buildStellarProposeSetPositionManagerTx:()=>Ft,buildStellarProposeSetPriceAggregatorTx:()=>Lt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>zt,buildStellarProposeSetSwapAggregatorTx:()=>Nt,buildStellarProposeTransferCtrlOwnershipTx:()=>or,buildStellarProposeTransferGovOwnTx:()=>dr,buildStellarProposeUnpauseTx:()=>Ar,buildStellarProposeUpdateDelayTx:()=>lr,buildStellarProposeUpgradeControllerTx:()=>tr,buildStellarProposeUpgradePoolParamsTx:()=>Zt,buildStellarProposeUpgradePoolTx:()=>er,buildStellarRenewAccountTx:()=>pt,buildStellarRepayBatchTx:()=>F,buildStellarRepayDebtWithCollateralTx:()=>Y,buildStellarRepayTx:()=>X,buildStellarRevokeBlendPoolTx:()=>ot,buildStellarRevokeRoleTx:()=>je,buildStellarRevokeTokenTx:()=>nt,buildStellarSetAccumulatorTx:()=>et,buildStellarSetAggregatorTx:()=>Ye,buildStellarSetMarketOracleConfigTx:()=>it,buildStellarSetOracleSanityBoundsTx:()=>ct,buildStellarSetOracleToleranceTx:()=>lt,buildStellarSetOracleTx:()=>st,buildStellarSetPositionLimitsTx:()=>tt,buildStellarSetPriceAggregatorTx:()=>Ze,buildStellarSetSpokeAssetFlagsTx:()=>ut,buildStellarSetSwapAggregatorTx:()=>Ke,buildStellarSupplyBatchTx:()=>D,buildStellarSupplyTx:()=>q,buildStellarSwapCollateralTx:()=>Z,buildStellarSwapDebtTx:()=>K,buildStellarTransferOwnershipTx:()=>Qe,buildStellarUnpauseTx:()=>Xe,buildStellarUpdateAccountThresholdTx:()=>St,buildStellarUpdateIndexesTx:()=>dt,buildStellarUpgradeControllerTx:()=>Ve,buildStellarUpgradeLiquidityPoolParamsTx:()=>ft,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>z,buildTx:()=>G,decodeStellarLendingEvent:()=>Fr,encodeAssetOracle:()=>We,encodeInterestRateModel:()=>Ie,encodeMarketOracleConfigInput:()=>Me,encodeMarketParamsRaw:()=>Be,encodePositionLimits:()=>Oe,encodePriceKey:()=>Ne,encodeStrategyPayloadToRouteXdr:()=>oo,extractEventOrder:()=>Qr,getStellarAccountDelegates:()=>Ae,getStellarAccountPositions:()=>be,getStellarAggregatorQuote:()=>eo,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>de,getStellarAssetGraph:()=>we,getStellarAssetMarkets:()=>me,getStellarAssetPage:()=>pe,getStellarAssets:()=>ne,getStellarBlendPools:()=>Pe,getStellarContractConfig:()=>ke,getStellarContractRoles:()=>Re,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>_e,getStellarHub:()=>fe,getStellarHubGraph:()=>ye,getStellarHubs:()=>se,getStellarLendingContext:()=>oe,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>ae,getStellarProtocolConfig:()=>ve,getStellarQuoteTokens:()=>to,getStellarReserve:()=>ue,getStellarReserveGraph:()=>xe,getStellarReserveHolders:()=>ce,getStellarReserves:()=>le,getStellarSpoke:()=>he,getStellarSpokeGraph:()=>Te,getStellarSpokes:()=>ie,getStellarUserActivity:()=>Se,getStellarUserPositions:()=>ge,mapQuoteResponseToAggregatorSwap:()=>lo,mapQuoteResponseToStrategyPayload:()=>so,mapQuoteResponseToStrategySwap:()=>io,mapSorobanError:()=>_o,mapStellarPositionActivityType:()=>Kr,prepareStellarBuiltTx:()=>mo,prepareStellarTxXdr:()=>po,stellarLendingDispatchKey:()=>Ir,stellarLendingRead:()=>Ee,syntheticEventOrder:()=>Jr,tagStellarInvokedContractError:()=>co,toBase64Xdr:()=>Pr,toStellarPositionMode:()=>fo});const r={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},o={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},a={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},n={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},s={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},i={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function l(e){const t=r[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function u(e){const t=o[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function c(e){const t=a[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const d=require("@stellar/stellar-sdk"),p=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],m={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},f=1e6,h=e=>new d.Address(e).toScVal(),g=e=>new d.ScInt(e).toI128(),S=e=>d.xdr.ScVal.scvU32(e),b=e=>new d.ScInt("string"==typeof e?e:e.toString()).toU64(),_=e=>d.xdr.ScVal.scvBool(e),w=e=>d.xdr.ScVal.scvString(e),y=e=>d.xdr.ScVal.scvSymbol(e),T=()=>d.xdr.ScVal.scvVoid(),x=e=>d.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return d.xdr.ScVal.scvBytes(o)},k=(e,t)=>null==e?T():t(e),R=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([h(t),g(r)]);var t,r}))),A=(e,t)=>I({asset:h(t),hub_id:S(e)}),P=(e,t,r)=>d.xdr.ScVal.scvVec([A(e,t),g(r)]),E=e=>d.xdr.ScVal.scvVec(e.map((e=>P(e.hubId,e.asset,e.amount)))),I=e=>{const t=Object.keys(e).sort().map((t=>new d.xdr.ScMapEntry({key:y(t),val:e[t]})));return d.xdr.ScVal.scvMap(t)};class B{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>f)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(m[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>f)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===f;let i=f;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*f/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const O=e=>{const t=new B(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(m.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return I({amounts:d.xdr.ScVal.scvVec(t.amountList.map((e=>g(e)))),assets:d.xdr.ScVal.scvVec(t.assetList.map((e=>h(e)))),ops:d.xdr.ScVal.scvBytes(t.toBytes(r,o,a))})},N=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return d.xdr.ScVal.scvBytes(t)},L=()=>d.xdr.ScVal.scvBytes(Buffer.alloc(0)),$=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},C=e=>{if("string"==typeof e)return N($(e));if(e instanceof Uint8Array)return 0===e.length?L():N(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?N($(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?N($(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?N($(e.bytes)):0===e.bytes.length?L():N(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!p.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(O(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},U=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return d.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return d.xdr.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function G(e,t,r){const o=e.controllerAddress??l(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return G(e,"supply",[h(e.caller),b(r),S(o),E([...t.assets])])}function q(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function W(e,t){return G(e,"borrow",[h(e.caller),b(t.accountNonce),E([...t.borrows]),k(t.to,h)])}function M(e,t){return W(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function V(e,t){return G(e,"withdraw",[h(e.caller),b(t.accountNonce),E([...t.withdrawals]),k(t.to,h)])}function z(e,t){return V(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function F(e,t){return G(e,"repay",[h(e.caller),b(t.accountNonce),E([...t.payments])])}function X(e,t){return F(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function H(e,t){return G(e,"liquidate",[h(e.caller),b(t.accountNonce),E([...t.debtPayments])])}function j(e,t){return G(e,"flash_loan",[h(e.caller),A(t.hubId,t.asset),g(t.amount),h(t.receiver),U(t.data)])}function Q(e,t){return G(e,"migrate_from_blend",[h(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),h(t.blendPool),x(t.collateralTokens.map(h)),x(t.supplyTokens.map(h)),R(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function J(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return G(e,"multiply",[h(e.caller),b(r),S(o),A(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),A(t.debt.hubId,t.debt.asset),S(t.mode),C(t.steps),k(t.initialPayment,(e=>P(e.hubId,e.asset,e.amount))),k(t.convertSwap,C)])}function K(e,t){return G(e,"swap_debt",[h(e.caller),b(t.accountNonce),A(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),A(t.newDebt.hubId,t.newDebt.asset),C(t.steps)])}function Z(e,t){return G(e,"swap_collateral",[h(e.caller),b(t.accountNonce),A(t.current.hubId,t.current.asset),g(t.fromAmount),A(t.newCollateral.hubId,t.newCollateral.asset),C(t.steps)])}function Y(e,t){return G(e,"repay_debt_with_collateral",[h(e.caller),b(t.accountNonce),A(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),A(t.debt.hubId,t.debt.asset),C(t.steps),_(t.closePosition)])}const ee="/stellar-lending",te=25,re=encodeURIComponent,oe=(e,t)=>e.fetchWithTimeout(`${ee}/context`,t),ae=(e,t)=>e.fetchWithTimeout(`${ee}/live-state`,t),ne=(e,t)=>e.fetchWithTimeout(`${ee}/assets`,t),se=(e,t)=>e.fetchWithTimeout(`${ee}/hubs`,t),ie=(e,t)=>e.fetchWithTimeout(`${ee}/spokes`,t),le=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${ee}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},ue=(e,t,r,o,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}`,a),ce=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}/holders`,{...n,params:{side:a}}),de=(e,t,r)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}`,r),pe=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/page`,{...o,params:{...r}}),me=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/markets`,{...o,params:{side:r}}),fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/hubs/${t}`,r),he=(e,t,r)=>e.fetchWithTimeout(`${ee}/spokes/${t}`,r),ge=(e,t,r)=>e.fetchWithTimeout(`${ee}/users/${re(t)}/positions`,r),Se=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${ee}/users/${re(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},be=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${re(t)}/positions`,r),_e=(e,t={},r)=>{const{top:o=te,continuationToken:a}=t;return e.fetchWithTimeout(`${ee}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},we=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/graph`,{...o,params:{...r}}),ye=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/graph`,{...o,params:{...r}}),Te=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}/graph`,{...n,params:{...a}}),ve=(e,t)=>e.fetchWithTimeout(`${ee}/protocol-config`,t),ke=(e,t,r)=>e.fetchWithTimeout(`${ee}/protocol-config/${re(t)}`,r),Re=(e,t,r)=>e.fetchWithTimeout(t?`${ee}/roles?contractAddress=${re(t)}`:`${ee}/roles`,r),Ae=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${re(String(t))}/delegates`,r),Pe=(e,t)=>e.fetchWithTimeout(`${ee}/blend-pools`,t),Ee=e=>({context:t=>oe(e,t),liveState:t=>ae(e,t),protocolConfig:t=>ve(e,t),contractConfig:(t,r)=>ke(e,t,r),contractRoles:(t,r)=>Re(e,t,r),accountDelegates:(t,r)=>Ae(e,t,r),blendPools:t=>Pe(e,t),assets:t=>ne(e,t),hubs:t=>se(e,t),spokes:t=>ie(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?le(e,t,r):le(e,{},t);var o},reserve:(t,r,o,a)=>ue(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ce(e,t,r,o,a,n),asset:(t,r)=>de(e,t,r),assetMarkets:(t,r,o)=>me(e,t,r,o),hub:(t,r)=>fe(e,t,r),spoke:(t,r)=>he(e,t,r),userPositions:(t,r)=>ge(e,t,r),userActivity:(t,r,o)=>Se(e,t,r,o),accountPositions:(t,r)=>be(e,t,r),governanceProposals:(t,r)=>_e(e,t,r),assetGraph:(t,r,o)=>we(e,t,r,o),hubGraph:(t,r,o)=>ye(e,t,r,o),spokeGraph:(t,r,o)=>Te(e,t,r,o),reserveGraph:(t,r,o,a,n)=>xe(e,t,r,o,a,n)}),Ie=e=>I({base_borrow_rate:g(e.baseBorrowRateRay),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Be=e=>I({asset_decimals:S(e.assetDecimals),asset_id:h(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:_(e.isFlashloanable),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Oe=e=>I({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),Ne=e=>{if("Token"in e&&e.Token)return x([y("Token"),h(e.Token)]);if("Ref"in e&&e.Ref)return x([y("Ref"),y(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Le=e=>{if("Stellar"in e)return x([y("Stellar"),h(e.Stellar)]);if("Symbol"in e)return x([y("Symbol"),y(e.Symbol)]);if("String"in e)return x([y("String"),w(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},$e=e=>{if("Spot"===e)return x([y("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([y("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ce=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ue=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ge=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),I({asset:Le(t.asset),contract:h(t.contract),read_mode:$e(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([y("MultiFeed"),I({contract:h(t.contract),feed_id:w(t.feedId),kind:Ce(t.kind),nature:Ue(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},De=e=>{const t=e;return I({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:Ge(t.provider)})},qe=e=>{if("RequireDisjoint"===e)return x([y("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return x([y("AllowShared"),x(t.map((e=>I({contract:h(e.contract),kind:Ce(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},We=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return I({asset_decimals:S(Number(t.assetDecimals)),independence:qe(t.independence),max_price_stale_seconds:b(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:g(String(t.maxSanityPriceWad)),min_sanity_price_wad:g(String(t.minSanityPriceWad)),sources:x(r.map((e=>(e=>{if("Feed"in e)return x([y("Feed"),De(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),I({factor:De(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:Ne(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),I({key_a:Ne(t.keyA),key_b:Ne(t.keyB),kind:x([y(t.kind||"ConstantProduct")]),pool:h(t.pool),reserve_a_decimals:S(t.reserveADecimals),reserve_b_decimals:S(t.reserveBDecimals),share_decimals:S(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:I({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Me=We;function Ve(e,t){return G(e,"upgrade",[v(t.wasmHash)])}function ze(e,t){return G(e,"migrate",[S(t.newVersion)])}function Fe(e){return G(e,"pause",[])}function Xe(e){return G(e,"unpause",[])}function He(e,t){return G(e,"grant_role",[h(t.account),y(t.role)])}function je(e,t){return G(e,"revoke_role",[h(t.account),y(t.role)])}function Qe(e,t){return G(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Je(e){return G(e,"accept_ownership",[])}function Ke(e,t){return G(e,"set_swap_aggregator",[h(t.aggregator)])}function Ze(e,t){return G(e,"set_price_aggregator",[h(t.aggregator)])}const Ye=Ke;function et(e,t){return G(e,"set_accumulator",[h(t.accumulator)])}function tt(e,t){return G(e,"set_position_limits",[Oe(t)])}function rt(e,t){return G(e,"approve_blend_pool",[h(t.pool)])}function ot(e,t){return G(e,"revoke_blend_pool",[h(t.pool)])}const at=rt,nt=ot;function st(e,t){return G(e,"set_oracle",[Ne(t.key),We(t.oracle)])}const it=st;function lt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return G(e,"set_tolerance",[Ne(t.key),I({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function ut(e,t){return G(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function ct(e,t){return G(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function dt(e,t){return G(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function pt(e,t){return G(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function mt(e,t){return G(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Be(t.params)])}function ft(e,t){return G(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),Ie(t.params)])}function ht(e,t){return G(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function gt(e,t){return G(e,"add_rewards",[h(e.caller),E(t.rewards)])}function St(e,t){return G(e,"update_account_threshold",[h(e.caller),_(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const bt="00".repeat(32),_t=e=>{if("string"==typeof e)return v(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return d.xdr.ScVal.scvBytes(t)},wt=(e,...t)=>x([y(e),...t]),yt=e=>I({asset:h(e.asset),hub_id:S(e.hubId),params:Be(e.params)}),Tt=e=>I({hub_asset:A(e.hubId,e.asset),params:Ie(e.params)}),xt=e=>I({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),vt=e=>I({key:Ne(e.key),oracle:We(e.oracle)}),kt=e=>I({asset:h(e.asset),bonus:S(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:_(e.canBorrow),can_collateral:_(e.canCollateral),frozen:_(e.frozen),hub_id:S(e.hubId),paused:_(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),oracle_override:x([y("None")]),spoke_id:S(e.spokeId),supply_cap:g(e.supplyCap),threshold:S(e.threshold)}),Rt=e=>I({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),At=e=>I({hf_for_max_bonus_wad:g(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:g(e.targetHfWad)}),Pt=e=>I({key:Ne(e.key),tolerance:S(e.tolerance)}),Et=e=>I({account:h(e.account),role:y(e.role)});function It(e,t,r){const o=e.governanceAddress??c(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Bt=(e,t,r)=>It(e,"propose",[h(e.caller),t,_t(r)]),Ot=(e,t,r)=>It(e,"execute_self",[T(),t,_t(r)]);function Nt(e,t,r){return Bt(e,wt("SetSwapAggregator",h(t.aggregator)),r)}function Lt(e,t,r){return Bt(e,wt("SetPriceAggregator",h(t.aggregator)),r)}const $t=Nt;function Ct(e,t,r){return Bt(e,wt("SetAccumulator",h(t.accumulator)),r)}function Ut(e,t,r){return Bt(e,wt("SetPositionLimits",Oe(t)),r)}function Gt(e,t){return Bt(e,wt("CreateHub"),t)}function Dt(e,t){return Bt(e,wt("AddSpoke"),t)}function qt(e,t,r){return Bt(e,wt("RemoveSpoke",S(t.spokeId)),r)}function Wt(e,t,r){return Bt(e,wt("AddAssetToSpoke",kt(t)),r)}function Mt(e,t,r){return Bt(e,wt("EditAssetInSpoke",kt(t)),r)}function Vt(e,t,r){return Bt(e,wt("RemoveAssetFromSpoke",Rt(t)),r)}function zt(e,t,r){return Bt(e,wt("SetSpokeLiquidationCurve",At(t)),r)}function Ft(e,t,r){return Bt(e,wt("SetPositionManager",h(t.manager),_(t.isActive)),r)}function Xt(e,t,r){return Bt(e,wt("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Ht(e,t,r){return Bt(e,wt("ApproveToken",h(t.token)),r)}function jt(e,t,r){return Bt(e,wt("RevokeToken",h(t.token)),r)}function Qt(e,t,r){return Bt(e,wt("ApproveBlendPool",h(t.pool)),r)}function Jt(e,t,r){return Bt(e,wt("RevokeBlendPool",h(t.pool)),r)}function Kt(e,t,r){return Bt(e,wt("CreateLiquidityPool",yt(t)),r)}function Zt(e,t,r){return Bt(e,wt("UpgradeLiquidityPoolParams",Tt(t)),r)}function Yt(e,t,r){return Bt(e,wt("DeployPool",v(t.wasmHash)),r)}function er(e,t,r){return Bt(e,wt("UpgradePool",v(t.wasmHash)),r)}function tr(e,t,r){return Bt(e,wt("UpgradeController",v(t.wasmHash)),r)}function rr(e,t,r){return Bt(e,wt("MigrateController",S(t.newVersion)),r)}function or(e,t,r){return Bt(e,wt("TransferCtrlOwnership",xt(t)),r)}function ar(e,t,r){return Bt(e,wt("ConfigureAssetOracle",vt(t)),r)}const nr=ar;function sr(e,t,r){return Bt(e,wt("EditOracleTolerance",Pt(t)),r)}function ir(e,t,r){return Bt(e,wt("UpgradeGov",v(t.wasmHash)),r)}function lr(e,t,r){return Bt(e,wt("UpdateGovDelay",S(t.newDelay)),r)}function ur(e,t,r){return Bt(e,wt("GrantGovRole",Et(t)),r)}function cr(e,t,r){return Bt(e,wt("RevokeGovRole",Et(t)),r)}function dr(e,t,r){return Bt(e,wt("TransferGovOwnership",xt(t)),r)}function pr(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=_t(t.predecessor??bt);return It(e,"execute",[T(),h(t.target),y(t.functionName),r,o,_t(t.salt)])}function mr(e,t,r){return Ot(e,wt("UpgradeGov",v(t.wasmHash)),r)}function fr(e,t,r){return Ot(e,wt("UpdateGovDelay",S(t.newDelay)),r)}function hr(e,t,r){return Ot(e,wt("GrantGovRole",Et(t)),r)}function gr(e,t,r){return Ot(e,wt("RevokeGovRole",Et(t)),r)}function Sr(e,t,r){return Ot(e,wt("TransferGovOwnership",xt(t)),r)}const br=e=>x(e.map(h));function _r(e,t,r){return It(e,"propose_canceller_reset",[br(t.newCancellers),_t(r)])}function wr(e,t,r){return It(e,"execute_canceller_reset",[k(t.executor,h),br(t.newCancellers),_t(r)])}function yr(e,t){return It(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function Tr(e,t){return It(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function xr(e){return It(e,"create_hub",[h(e.caller)])}function vr(e){return It(e,"add_spoke",[h(e.caller)])}function kr(e,t){return It(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function Rr(e){return It(e,"pause",[h(e.caller)])}function Ar(e,t){return Bt(e,wt("Unpause"),t)}const Pr=e=>e.toXDR("base64"),Er=e=>d.xdr.ScVal.fromXDR(e,"base64"),Ir=e=>e.map((e=>String((0,d.scValToNative)(Er(e))))).join(":"),Br=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Or=e=>Number(e),Nr=e=>String(e),Lr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),$r=["None","Multiply","Long","Short"],Cr=["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"],Ur=e=>Array.isArray(e)?e:[],Gr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Cr[Or(o)]??Br(o)),positionType:t,hubId:Or(e[1]),asset:Nr(e[2]),scaledAmountRay:Br(e[3]),indexRay:Br(e[4]),amount:Br(e[5]),liquidationThresholdBps:r?void 0:Or(e[6]),liquidationBonusBps:r?void 0:Or(e[7]),loanToValueBps:r?void 0:Or(e[8]),liquidationFeesBps:r?void 0:Or(e[9])};var o},Dr=e=>{return{owner:Nr(e[0]),spokeId:Or(e[1]),mode:(t=e[2],$r[Or(t)]??"None")};var t},qr=e=>Array.isArray(e)?e[1]:void 0,Wr=e=>{const t=(r=e,Array.isArray(r)?Nr(r[0]):Nr(r));var r;if("Token"===t)return{Token:Nr(qr(e))};if("Ref"===t)return{Ref:Nr(qr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Nr(t.Token)};if(void 0!==t.Ref)return{Ref:Nr(t.Ref)}}return{Token:Nr(e)}},Mr=e=>{const t=e.tolerance??{};return{assetDecimals:Or(e.asset_decimals),maxPriceStaleSeconds:Or(e.max_price_stale_seconds),sources:Ur(e.sources).map((e=>e)),tolerance:{upperRatio:Or(t.upper_ratio_bps),lowerRatio:Or(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Br(e.min_sanity_price_wad),maxSanityPriceWad:Br(e.max_sanity_price_wad)}},Vr={"market:create":e=>({topic:"market:create",data:{hubId:Or(e.hub_id),baseAsset:Nr(e.base_asset),maxBorrowRate:Br(e.max_borrow_rate),baseBorrowRate:Br(e.base_borrow_rate),slope1:Br(e.slope1),slope2:Br(e.slope2),slope3:Br(e.slope3),midUtilization:Br(e.mid_utilization),optimalUtilization:Br(e.optimal_utilization),maxUtilization:Br(e.max_utilization),reserveFactor:Or(e.reserve_factor),marketAddress:Nr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Nr(e.asset),maxBorrowRateRay:Br(e.max_borrow_rate),baseBorrowRateRay:Br(e.base_borrow_rate),slope1Ray:Br(e.slope1),slope2Ray:Br(e.slope2),slope3Ray:Br(e.slope3),midUtilizationRay:Br(e.mid_utilization),optimalUtilizationRay:Br(e.optimal_utilization),maxUtilizationRay:Br(e.max_utilization),reserveFactorBps:Or(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ur(e).map((e=>{return t=Ur(e),{hubId:Or(t[0]),asset:Nr(t[1]),timestamp:Or(t[2]),supplyIndexRay:Br(t[3]),borrowIndexRay:Br(t[4]),cash:Br(t[5]),suppliedRay:Br(t[6]),borrowedRay:Br(t[7]),revenueRay:Br(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ur(e).map((e=>{const t=e;return{hubId:Or(t.hub_id),asset:Nr(t.asset),params:(r=t.params,{maxBorrowRateRay:Br(r.max_borrow_rate),baseBorrowRateRay:Br(r.base_borrow_rate),slope1Ray:Br(r.slope1),slope2Ray:Br(r.slope2),slope3Ray:Br(r.slope3),midUtilizationRay:Br(r.mid_utilization),optimalUtilizationRay:Br(r.optimal_utilization),maxUtilizationRay:Br(r.max_utilization),reserveFactorBps:Or(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Or(r.flashloan_fee),assetId:Nr(r.asset_id),assetDecimals:Or(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ur(e);return{topic:"position:batch_update",data:{accountId:Br(t[0]),accountAttributes:Dr(Ur(t[1])),updates:[...Ur(t[2]).map((e=>Gr(Ur(e),"Deposit"))),...Ur(t[3]).map((e=>Gr(Ur(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Or(e.hub_id),asset:Nr(e.asset),receiver:Nr(e.receiver),caller:Nr(e.caller),amount:Br(e.amount),fee:Br(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Wr(e.key),oracle:Mr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Nr(e.asset),oracle:Mr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Nr(e.liquidator),accountId:Br(e.account_id),repaidUsdWad:Br(e.repaid_usd_wad),bonusBps:Br(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Br(e.account_id),totalBorrowUsdWad:Br(e.total_borrow_usd_wad),totalCollateralUsdWad:Br(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Nr(e.token),amount:Br(e.amount),usdValueWad:Br(e.usd_value_wad),accountId:Br(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Or(e.hub_id),asset:Nr(e.asset),amount:Br(e.amount),fee:Br(e.fee),amountSent:Br(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Nr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Lr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Nr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Nr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Nr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Nr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Lr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Or(e.max_supply_positions),maxBorrowPositions:Or(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Br(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Nr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Or(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Br(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Br(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Or(t.liquidation_bonus_factor_bps)}}}},zr=Object.freeze(Object.keys(Vr));function Fr(e,t){const r=Ir(e),o=Vr[r];return o?o((0,d.scValToNative)(Er(t))):null}const Xr="XLENDXLM-a7c9f3",Hr=1e4;function jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Xr}-${r}`}function Qr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Jr(e,t=0){return e*Hr+t}function Kr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Zr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Yr=e=>e.baseUrl??s[e.network];async function eo(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Zr(Yr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function to(e){const t=Zr(Yr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ro=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,oo=e=>O(e).toXDR("base64");function ao(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=C(ro(t,e.referralId));return{xdr:new d.TransactionBuilder(a,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call("execute_strategy",h(e.caller),g(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function no(e,t){return ao(e,t)}function so(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(uo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(uo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function io(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:so(e,t)}const lo=so,uo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function co(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function po(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw co(r.invokedContractId,e);throw e}}async function mo(e,t,r){return po(e,t.xdr,r)}function fo(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function ho(e,t){return new Uint8Array(0)}const go=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function So(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(go(e.message)),d.xdr.ScVal.scvBytes(go(e.attestation)));return{xdr:new d.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const bo={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},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 _o(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=bo[r];return o?{code:r,...o}:null}module.exports=t})();
1
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{STELLAR_AGGREGATOR_ROUTER:()=>o,STELLAR_GOVERNANCE:()=>a,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>_t,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>Xr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>Qr,XOXNO_LENDING_STELLAR_TICKER:()=>jr,buildSameTokenRepaySwapSteps:()=>So,buildStellarAcceptOwnershipTx:()=>Ze,buildStellarAddRewardsTx:()=>bt,buildStellarApproveBlendPoolTx:()=>at,buildStellarApproveTokenTx:()=>st,buildStellarBatchSwapTx:()=>io,buildStellarBorrowBatchTx:()=>W,buildStellarBorrowTx:()=>z,buildStellarCctpForwardTx:()=>wo,buildStellarClaimRevenueTx:()=>St,buildStellarCreateLiquidityPoolTx:()=>ht,buildStellarExecuteCancellerResetTx:()=>Tr,buildStellarExecuteStrategyTx:()=>so,buildStellarFlashLoanTx:()=>J,buildStellarGovernanceAddSpokeImmediateTx:()=>Rr,buildStellarGovernanceCreateHubImmediateTx:()=>kr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>hr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Sr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>br,buildStellarGovernanceExecuteTransferGovOwnTx:()=>wr,buildStellarGovernanceExecuteTx:()=>fr,buildStellarGovernanceExecuteUpdateDelayTx:()=>gr,buildStellarGovernancePauseTx:()=>Er,buildStellarGovernanceRevokeRoleImmediateTx:()=>Ar,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>vr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>xr,buildStellarGrantRoleTx:()=>Qe,buildStellarLendingIdentifier:()=>Jr,buildStellarLiquidateTx:()=>j,buildStellarMigrateFromBlendTx:()=>K,buildStellarMigrateTx:()=>Xe,buildStellarMultiplyTx:()=>Z,buildStellarPauseTx:()=>He,buildStellarProposeAddAssetToSpokeTx:()=>zt,buildStellarProposeAddSpokeTx:()=>Mt,buildStellarProposeApproveBlendPoolTx:()=>Kt,buildStellarProposeApproveTokenTx:()=>Qt,buildStellarProposeCancellerResetTx:()=>yr,buildStellarProposeConfigureAssetOracleTx:()=>sr,buildStellarProposeConfigureMarketOracleTx:()=>ir,buildStellarProposeCreateHubTx:()=>Dt,buildStellarProposeCreateLiquidityPoolTx:()=>Yt,buildStellarProposeDeployPoolTx:()=>tr,buildStellarProposeEditAssetInSpokeTx:()=>Vt,buildStellarProposeEditOracleToleranceTx:()=>lr,buildStellarProposeGovernanceUpgradeTx:()=>ur,buildStellarProposeGrantGovernanceRoleTx:()=>dr,buildStellarProposeMigrateControllerTx:()=>ar,buildStellarProposeRemoveAssetFromSpokeTx:()=>Ft,buildStellarProposeRemoveSpokeTx:()=>Wt,buildStellarProposeRevokeBlendPoolTx:()=>Zt,buildStellarProposeRevokeGovernanceRoleTx:()=>pr,buildStellarProposeRevokeTokenTx:()=>Jt,buildStellarProposeSetAccumulatorTx:()=>Gt,buildStellarProposeSetAggregatorTx:()=>Ut,buildStellarProposeSetMinBorrowCollatTx:()=>jt,buildStellarProposeSetPositionLimitsTx:()=>qt,buildStellarProposeSetPositionManagerTx:()=>Ht,buildStellarProposeSetPriceAggregatorTx:()=>Ct,buildStellarProposeSetSpokeLiquidationCurveTx:()=>Xt,buildStellarProposeSetSwapAggregatorTx:()=>$t,buildStellarProposeTransferCtrlOwnershipTx:()=>nr,buildStellarProposeTransferGovOwnTx:()=>mr,buildStellarProposeUnpauseTx:()=>Pr,buildStellarProposeUpdateDelayTx:()=>cr,buildStellarProposeUpgradeControllerTx:()=>or,buildStellarProposeUpgradePoolParamsTx:()=>er,buildStellarProposeUpgradePoolTx:()=>rr,buildStellarRenewAccountTx:()=>ft,buildStellarRepayBatchTx:()=>X,buildStellarRepayDebtWithCollateralTx:()=>te,buildStellarRepayTx:()=>H,buildStellarRevokeBlendPoolTx:()=>nt,buildStellarRevokeRoleTx:()=>Je,buildStellarRevokeTokenTx:()=>it,buildStellarSetAccumulatorTx:()=>rt,buildStellarSetAggregatorTx:()=>tt,buildStellarSetMarketOracleConfigTx:()=>ut,buildStellarSetOracleSanityBoundsTx:()=>pt,buildStellarSetOracleToleranceTx:()=>ct,buildStellarSetOracleTx:()=>lt,buildStellarSetPositionLimitsTx:()=>ot,buildStellarSetPriceAggregatorTx:()=>et,buildStellarSetSpokeAssetFlagsTx:()=>dt,buildStellarSetSwapAggregatorTx:()=>Ye,buildStellarSupplyBatchTx:()=>D,buildStellarSupplyTx:()=>M,buildStellarSwapCollateralTx:()=>ee,buildStellarSwapDebtTx:()=>Y,buildStellarTransferOwnershipTx:()=>Ke,buildStellarUnpauseTx:()=>je,buildStellarUpdateAccountThresholdTx:()=>wt,buildStellarUpdateIndexesTx:()=>mt,buildStellarUpgradeControllerTx:()=>Fe,buildStellarUpgradeLiquidityPoolParamsTx:()=>gt,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>F,buildTx:()=>q,decodeStellarLendingEvent:()=>Hr,decodeStellarLiquidateReturn:()=>Q,encodeAssetOracle:()=>ze,encodeInterestRateModel:()=>Be,encodeMarketOracleConfigInput:()=>Ve,encodeMarketParamsRaw:()=>Ne,encodePositionLimits:()=>Le,encodePriceKey:()=>$e,encodeStrategyPayloadToRouteXdr:()=>no,extractEventOrder:()=>Kr,getStellarAccountDelegates:()=>Pe,getStellarAccountPositions:()=>_e,getStellarAggregatorQuote:()=>ro,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>me,getStellarAssetGraph:()=>Te,getStellarAssetMarkets:()=>he,getStellarAssetPage:()=>fe,getStellarAssets:()=>ie,getStellarBlendPools:()=>Ie,getStellarContractConfig:()=>Ae,getStellarContractRoles:()=>Ee,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>ye,getStellarHub:()=>ge,getStellarHubGraph:()=>xe,getStellarHubs:()=>le,getStellarLendingContext:()=>ne,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>se,getStellarProtocolConfig:()=>Re,getStellarQuoteTokens:()=>oo,getStellarReserve:()=>de,getStellarReserveGraph:()=>ke,getStellarReserveHolders:()=>pe,getStellarReserves:()=>ce,getStellarSpoke:()=>Se,getStellarSpokeGraph:()=>ve,getStellarSpokes:()=>ue,getStellarUserActivity:()=>we,getStellarUserPositions:()=>be,mapQuoteResponseToAggregatorSwap:()=>co,mapQuoteResponseToStrategyPayload:()=>lo,mapQuoteResponseToStrategySwap:()=>uo,mapSorobanError:()=>yo,mapStellarPositionActivityType:()=>Yr,prepareStellarBuiltTx:()=>ho,prepareStellarTxXdr:()=>fo,stellarLendingDispatchKey:()=>Br,stellarLendingRead:()=>Oe,syntheticEventOrder:()=>Zr,tagStellarInvokedContractError:()=>mo,toBase64Xdr:()=>Ir,toStellarPositionMode:()=>go});const r={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},o={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},a={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},n={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},s={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},i={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function l(e){const t=r[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function u(e){const t=o[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function c(e){const t=a[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const d=require("@stellar/stellar-sdk"),p=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],m={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},f=1e6,h=e=>new d.Address(e).toScVal(),g=e=>new d.ScInt(e).toI128(),S=e=>d.xdr.ScVal.scvU32(e),b=e=>new d.ScInt("string"==typeof e?e:e.toString()).toU64(),w=e=>d.xdr.ScVal.scvBool(e),_=e=>d.xdr.ScVal.scvString(e),y=e=>d.xdr.ScVal.scvSymbol(e),T=()=>d.xdr.ScVal.scvVoid(),x=e=>d.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return d.xdr.ScVal.scvBytes(o)},k=(e,t)=>null==e?T():t(e),R=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([h(t),g(r)]);var t,r}))),A=(e,t)=>O({asset:h(t),hub_id:S(e)}),E=(e,t,r)=>d.xdr.ScVal.scvVec([A(e,t),g(r)]),P=e=>d.xdr.ScVal.scvVec(e.map((e=>E(e.hubId,e.asset,e.amount)))),I=e=>{if("Transfer"===e)return x([y("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return x([y("Credit"),b(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},O=e=>{const t=Object.keys(e).sort().map((t=>new d.xdr.ScMapEntry({key:y(t),val:e[t]})));return d.xdr.ScVal.scvMap(t)};class B{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>f)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(m[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>f)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===f;let i=f;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*f/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const N=e=>{const t=new B(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(m.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return O({amounts:d.xdr.ScVal.scvVec(t.amountList.map((e=>g(e)))),assets:d.xdr.ScVal.scvVec(t.assetList.map((e=>h(e)))),ops:d.xdr.ScVal.scvBytes(t.toBytes(r,o,a))})},L=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return d.xdr.ScVal.scvBytes(t)},$=()=>d.xdr.ScVal.scvBytes(Buffer.alloc(0)),C=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},U=e=>{if("string"==typeof e)return L(C(e));if(e instanceof Uint8Array)return 0===e.length?$():L(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?L(C(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?L(C(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?L(C(e.bytes)):0===e.bytes.length?$():L(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!p.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(N(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},G=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return d.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return d.xdr.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function q(e,t,r){const o=e.controllerAddress??l(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"supply",[h(e.caller),b(r),S(o),P([...t.assets])])}function M(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function W(e,t){return q(e,"borrow",[h(e.caller),b(t.accountNonce),P([...t.borrows]),k(t.to,h)])}function z(e,t){return W(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function V(e,t){return q(e,"withdraw",[h(e.caller),b(t.accountNonce),P([...t.withdrawals]),k(t.to,h)])}function F(e,t){return V(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return q(e,"repay",[h(e.caller),b(t.accountNonce),P([...t.payments])])}function H(e,t){return X(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return q(e,"liquidate",[h(e.caller),b(t.accountNonce),P([...t.debtPayments]),I(t.seizeMode??"Transfer")])}function Q(e){const t=(0,d.scValToNative)(d.xdr.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function J(e,t){return q(e,"flash_loan",[h(e.caller),A(t.hubId,t.asset),g(t.amount),h(t.receiver),G(t.data)])}function K(e,t){return q(e,"migrate_from_blend",[h(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),h(t.blendPool),x(t.collateralTokens.map(h)),x(t.supplyTokens.map(h)),R(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function Z(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"multiply",[h(e.caller),b(r),S(o),A(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),A(t.debt.hubId,t.debt.asset),S(t.mode),U(t.steps),k(t.initialPayment,(e=>E(e.hubId,e.asset,e.amount))),k(t.convertSwap,U)])}function Y(e,t){return q(e,"swap_debt",[h(e.caller),b(t.accountNonce),A(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),A(t.newDebt.hubId,t.newDebt.asset),U(t.steps)])}function ee(e,t){return q(e,"swap_collateral",[h(e.caller),b(t.accountNonce),A(t.current.hubId,t.current.asset),g(t.fromAmount),A(t.newCollateral.hubId,t.newCollateral.asset),U(t.steps)])}function te(e,t){return q(e,"repay_debt_with_collateral",[h(e.caller),b(t.accountNonce),A(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),A(t.debt.hubId,t.debt.asset),U(t.steps),w(t.closePosition)])}const re="/stellar-lending",oe=25,ae=encodeURIComponent,ne=(e,t)=>e.fetchWithTimeout(`${re}/context`,t),se=(e,t)=>e.fetchWithTimeout(`${re}/live-state`,t),ie=(e,t)=>e.fetchWithTimeout(`${re}/assets`,t),le=(e,t)=>e.fetchWithTimeout(`${re}/hubs`,t),ue=(e,t)=>e.fetchWithTimeout(`${re}/spokes`,t),ce=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${re}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},de=(e,t,r,o,a)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}`,a),pe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/holders`,{...n,params:{side:a}}),me=(e,t,r)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}`,r),fe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/page`,{...o,params:{...r}}),he=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/markets`,{...o,params:{side:r}}),ge=(e,t,r)=>e.fetchWithTimeout(`${re}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${re}/spokes/${t}`,r),be=(e,t,r)=>e.fetchWithTimeout(`${re}/users/${ae(t)}/positions`,r),we=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${re}/users/${ae(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},_e=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(t)}/positions`,r),ye=(e,t={},r)=>{const{top:o=oe,continuationToken:a}=t;return e.fetchWithTimeout(`${re}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Te=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/hubs/${t}/graph`,{...o,params:{...r}}),ve=(e,t,r,o)=>e.fetchWithTimeout(`${re}/spokes/${t}/graph`,{...o,params:{...r}}),ke=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/graph`,{...n,params:{...a}}),Re=(e,t)=>e.fetchWithTimeout(`${re}/protocol-config`,t),Ae=(e,t,r)=>e.fetchWithTimeout(`${re}/protocol-config/${ae(t)}`,r),Ee=(e,t,r)=>e.fetchWithTimeout(t?`${re}/roles?contractAddress=${ae(t)}`:`${re}/roles`,r),Pe=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(String(t))}/delegates`,r),Ie=(e,t)=>e.fetchWithTimeout(`${re}/blend-pools`,t),Oe=e=>({context:t=>ne(e,t),liveState:t=>se(e,t),protocolConfig:t=>Re(e,t),contractConfig:(t,r)=>Ae(e,t,r),contractRoles:(t,r)=>Ee(e,t,r),accountDelegates:(t,r)=>Pe(e,t,r),blendPools:t=>Ie(e,t),assets:t=>ie(e,t),hubs:t=>le(e,t),spokes:t=>ue(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?ce(e,t,r):ce(e,{},t);var o},reserve:(t,r,o,a)=>de(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>pe(e,t,r,o,a,n),asset:(t,r)=>me(e,t,r),assetMarkets:(t,r,o)=>he(e,t,r,o),hub:(t,r)=>ge(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>be(e,t,r),userActivity:(t,r,o)=>we(e,t,r,o),accountPositions:(t,r)=>_e(e,t,r),governanceProposals:(t,r)=>ye(e,t,r),assetGraph:(t,r,o)=>Te(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>ve(e,t,r,o),reserveGraph:(t,r,o,a,n)=>ke(e,t,r,o,a,n)}),Be=e=>O({base_borrow_rate:g(e.baseBorrowRateRay),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ne=e=>O({asset_decimals:S(e.assetDecimals),asset_id:h(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:w(e.isFlashloanable),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Le=e=>O({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),$e=e=>{if("Token"in e&&e.Token)return x([y("Token"),h(e.Token)]);if("Ref"in e&&e.Ref)return x([y("Ref"),y(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Ce=e=>{if("Stellar"in e)return x([y("Stellar"),h(e.Stellar)]);if("Symbol"in e)return x([y("Symbol"),y(e.Symbol)]);if("String"in e)return x([y("String"),_(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ue=e=>{if("Spot"===e)return x([y("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([y("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ge=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},qe=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},De=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),O({asset:Ce(t.asset),contract:h(t.contract),read_mode:Ue(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([y("MultiFeed"),O({contract:h(t.contract),feed_id:_(t.feedId),kind:Ge(t.kind),nature:qe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Me=e=>{const t=e;return O({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:De(t.provider)})},We=e=>{if("RequireDisjoint"===e)return x([y("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return x([y("AllowShared"),x(t.map((e=>O({contract:h(e.contract),kind:Ge(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},ze=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return O({asset_decimals:S(Number(t.assetDecimals)),independence:We(t.independence),max_price_stale_seconds:b(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:g(String(t.maxSanityPriceWad)),min_sanity_price_wad:g(String(t.minSanityPriceWad)),sources:x(r.map((e=>(e=>{if("Feed"in e)return x([y("Feed"),Me(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),O({factor:Me(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:$e(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),O({key_a:$e(t.keyA),key_b:$e(t.keyB),kind:x([y(t.kind||"ConstantProduct")]),pool:h(t.pool),reserve_a_decimals:S(t.reserveADecimals),reserve_b_decimals:S(t.reserveBDecimals),share_decimals:S(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:O({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Ve=ze;function Fe(e,t){return q(e,"upgrade",[v(t.wasmHash)])}function Xe(e,t){return q(e,"migrate",[S(t.newVersion)])}function He(e){return q(e,"pause",[])}function je(e){return q(e,"unpause",[])}function Qe(e,t){return q(e,"grant_role",[h(t.account),y(t.role)])}function Je(e,t){return q(e,"revoke_role",[h(t.account),y(t.role)])}function Ke(e,t){return q(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Ze(e){return q(e,"accept_ownership",[])}function Ye(e,t){return q(e,"set_swap_aggregator",[h(t.aggregator)])}function et(e,t){return q(e,"set_price_aggregator",[h(t.aggregator)])}const tt=Ye;function rt(e,t){return q(e,"set_accumulator",[h(t.accumulator)])}function ot(e,t){return q(e,"set_position_limits",[Le(t)])}function at(e,t){return q(e,"approve_blend_pool",[h(t.pool)])}function nt(e,t){return q(e,"revoke_blend_pool",[h(t.pool)])}const st=at,it=nt;function lt(e,t){return q(e,"set_oracle",[$e(t.key),ze(t.oracle)])}const ut=lt;function ct(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return q(e,"set_tolerance",[$e(t.key),O({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function dt(e,t){return q(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function pt(e,t){return q(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function mt(e,t){return q(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function ft(e,t){return q(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function ht(e,t){return q(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Ne(t.params)])}function gt(e,t){return q(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),Be(t.params)])}function St(e,t){return q(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function bt(e,t){return q(e,"add_rewards",[h(e.caller),P(t.rewards)])}function wt(e,t){return q(e,"update_account_threshold",[h(e.caller),w(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const _t="00".repeat(32),yt=e=>{if("string"==typeof e)return v(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return d.xdr.ScVal.scvBytes(t)},Tt=(e,...t)=>x([y(e),...t]),xt=e=>O({asset:h(e.asset),hub_id:S(e.hubId),params:Ne(e.params)}),vt=e=>O({hub_asset:A(e.hubId,e.asset),params:Be(e.params)}),kt=e=>O({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),Rt=e=>O({key:$e(e.key),oracle:ze(e.oracle)}),At=e=>O({asset:h(e.asset),bonus:S(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:w(e.canBorrow),can_collateral:w(e.canCollateral),frozen:w(e.frozen),hub_id:S(e.hubId),paused:w(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),no_seize:w(e.noSeize),spoke_id:S(e.spokeId),supply_cap:g(e.supplyCap),threshold:S(e.threshold)}),Et=e=>O({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),Pt=e=>O({hf_for_max_bonus_wad:g(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:g(e.targetHfWad)}),It=e=>O({key:$e(e.key),tolerance:S(e.tolerance)}),Ot=e=>O({account:h(e.account),role:y(e.role)});function Bt(e,t,r){const o=e.governanceAddress??c(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Nt=(e,t,r)=>Bt(e,"propose",[h(e.caller),t,yt(r)]),Lt=(e,t,r)=>Bt(e,"execute_self",[T(),t,yt(r)]);function $t(e,t,r){return Nt(e,Tt("SetSwapAggregator",h(t.aggregator)),r)}function Ct(e,t,r){return Nt(e,Tt("SetPriceAggregator",h(t.aggregator)),r)}const Ut=$t;function Gt(e,t,r){return Nt(e,Tt("SetAccumulator",h(t.accumulator)),r)}function qt(e,t,r){return Nt(e,Tt("SetPositionLimits",Le(t)),r)}function Dt(e,t){return Nt(e,Tt("CreateHub"),t)}function Mt(e,t){return Nt(e,Tt("AddSpoke"),t)}function Wt(e,t,r){return Nt(e,Tt("RemoveSpoke",S(t.spokeId)),r)}function zt(e,t,r){return Nt(e,Tt("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Nt(e,Tt("EditAssetInSpoke",At(t)),r)}function Ft(e,t,r){return Nt(e,Tt("RemoveAssetFromSpoke",Et(t)),r)}function Xt(e,t,r){return Nt(e,Tt("SetSpokeLiquidationCurve",Pt(t)),r)}function Ht(e,t,r){return Nt(e,Tt("SetPositionManager",h(t.manager),w(t.isActive)),r)}function jt(e,t,r){return Nt(e,Tt("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Qt(e,t,r){return Nt(e,Tt("ApproveToken",h(t.token)),r)}function Jt(e,t,r){return Nt(e,Tt("RevokeToken",h(t.token)),r)}function Kt(e,t,r){return Nt(e,Tt("ApproveBlendPool",h(t.pool)),r)}function Zt(e,t,r){return Nt(e,Tt("RevokeBlendPool",h(t.pool)),r)}function Yt(e,t,r){return Nt(e,Tt("CreateLiquidityPool",xt(t)),r)}function er(e,t,r){return Nt(e,Tt("UpgradeLiquidityPoolParams",vt(t)),r)}function tr(e,t,r){return Nt(e,Tt("DeployPool",v(t.wasmHash)),r)}function rr(e,t,r){return Nt(e,Tt("UpgradePool",v(t.wasmHash)),r)}function or(e,t,r){return Nt(e,Tt("UpgradeController",v(t.wasmHash)),r)}function ar(e,t,r){return Nt(e,Tt("MigrateController",S(t.newVersion)),r)}function nr(e,t,r){return Nt(e,Tt("TransferCtrlOwnership",kt(t)),r)}function sr(e,t,r){return Nt(e,Tt("ConfigureAssetOracle",Rt(t)),r)}const ir=sr;function lr(e,t,r){return Nt(e,Tt("EditOracleTolerance",It(t)),r)}function ur(e,t,r){return Nt(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function cr(e,t,r){return Nt(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function dr(e,t,r){return Nt(e,Tt("GrantGovRole",Ot(t)),r)}function pr(e,t,r){return Nt(e,Tt("RevokeGovRole",Ot(t)),r)}function mr(e,t,r){return Nt(e,Tt("TransferGovOwnership",kt(t)),r)}function fr(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=yt(t.predecessor??_t);return Bt(e,"execute",[T(),h(t.target),y(t.functionName),r,o,yt(t.salt)])}function hr(e,t,r){return Lt(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function gr(e,t,r){return Lt(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function Sr(e,t,r){return Lt(e,Tt("GrantGovRole",Ot(t)),r)}function br(e,t,r){return Lt(e,Tt("RevokeGovRole",Ot(t)),r)}function wr(e,t,r){return Lt(e,Tt("TransferGovOwnership",kt(t)),r)}const _r=e=>x(e.map(h));function yr(e,t,r){return Bt(e,"propose_canceller_reset",[_r(t.newCancellers),yt(r)])}function Tr(e,t,r){return Bt(e,"execute_canceller_reset",[k(t.executor,h),_r(t.newCancellers),yt(r)])}function xr(e,t){return Bt(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function vr(e,t){return Bt(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function kr(e){return Bt(e,"create_hub",[h(e.caller)])}function Rr(e){return Bt(e,"add_spoke",[h(e.caller)])}function Ar(e,t){return Bt(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function Er(e){return Bt(e,"pause",[h(e.caller)])}function Pr(e,t){return Nt(e,Tt("Unpause"),t)}const Ir=e=>e.toXDR("base64"),Or=e=>d.xdr.ScVal.fromXDR(e,"base64"),Br=e=>e.map((e=>String((0,d.scValToNative)(Or(e))))).join(":"),Nr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Lr=e=>Number(e),$r=e=>String(e),Cr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],Gr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],qr=e=>Array.isArray(e)?e:[],Dr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Gr[Lr(o)]??Nr(o)),positionType:t,hubId:Lr(e[1]),asset:$r(e[2]),scaledAmountRay:Nr(e[3]),indexRay:Nr(e[4]),amount:Nr(e[5]),liquidationThresholdBps:r?void 0:Lr(e[6]),liquidationBonusBps:r?void 0:Lr(e[7]),loanToValueBps:r?void 0:Lr(e[8]),liquidationFeesBps:r?void 0:Lr(e[9])};var o},Mr=e=>{return{owner:$r(e[0]),spokeId:Lr(e[1]),mode:(t=e[2],Ur[Lr(t)]??"None")};var t},Wr=e=>Array.isArray(e)?e[1]:void 0,zr=e=>{const t=(r=e,Array.isArray(r)?$r(r[0]):$r(r));var r;if("Token"===t)return{Token:$r(Wr(e))};if("Ref"===t)return{Ref:$r(Wr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:$r(t.Token)};if(void 0!==t.Ref)return{Ref:$r(t.Ref)}}return{Token:$r(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:Lr(e.asset_decimals),maxPriceStaleSeconds:Lr(e.max_price_stale_seconds),sources:qr(e.sources).map((e=>e)),tolerance:{upperRatio:Lr(t.upper_ratio_bps),lowerRatio:Lr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Nr(e.min_sanity_price_wad),maxSanityPriceWad:Nr(e.max_sanity_price_wad)}},Fr={"market:create":e=>({topic:"market:create",data:{hubId:Lr(e.hub_id),baseAsset:$r(e.base_asset),maxBorrowRate:Nr(e.max_borrow_rate),baseBorrowRate:Nr(e.base_borrow_rate),slope1:Nr(e.slope1),slope2:Nr(e.slope2),slope3:Nr(e.slope3),midUtilization:Nr(e.mid_utilization),optimalUtilization:Nr(e.optimal_utilization),maxUtilization:Nr(e.max_utilization),reserveFactor:Lr(e.reserve_factor),marketAddress:$r(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:$r(e.asset),maxBorrowRateRay:Nr(e.max_borrow_rate),baseBorrowRateRay:Nr(e.base_borrow_rate),slope1Ray:Nr(e.slope1),slope2Ray:Nr(e.slope2),slope3Ray:Nr(e.slope3),midUtilizationRay:Nr(e.mid_utilization),optimalUtilizationRay:Nr(e.optimal_utilization),maxUtilizationRay:Nr(e.max_utilization),reserveFactorBps:Lr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:qr(e).map((e=>{return t=qr(e),{hubId:Lr(t[0]),asset:$r(t[1]),timestamp:Lr(t[2]),supplyIndexRay:Nr(t[3]),borrowIndexRay:Nr(t[4]),cash:Nr(t[5]),suppliedRay:Nr(t[6]),borrowedRay:Nr(t[7]),revenueRay:Nr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:qr(e).map((e=>{const t=e;return{hubId:Lr(t.hub_id),asset:$r(t.asset),params:(r=t.params,{maxBorrowRateRay:Nr(r.max_borrow_rate),baseBorrowRateRay:Nr(r.base_borrow_rate),slope1Ray:Nr(r.slope1),slope2Ray:Nr(r.slope2),slope3Ray:Nr(r.slope3),midUtilizationRay:Nr(r.mid_utilization),optimalUtilizationRay:Nr(r.optimal_utilization),maxUtilizationRay:Nr(r.max_utilization),reserveFactorBps:Lr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Lr(r.flashloan_fee),assetId:$r(r.asset_id),assetDecimals:Lr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=qr(e);return{topic:"position:batch_update",data:{accountId:Nr(t[0]),accountAttributes:Mr(qr(t[1])),updates:[...qr(t[2]).map((e=>Dr(qr(e),"Deposit"))),...qr(t[3]).map((e=>Dr(qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Lr(e.hub_id),asset:$r(e.asset),receiver:$r(e.receiver),caller:$r(e.caller),amount:Nr(e.amount),fee:Nr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:zr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:$r(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:$r(e.liquidator),accountId:Nr(e.account_id),repaidUsdWad:Nr(e.repaid_usd_wad),bonusBps:Nr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Nr(e.account_id),totalBorrowUsdWad:Nr(e.total_borrow_usd_wad),totalCollateralUsdWad:Nr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:$r(e.token),amount:Nr(e.amount),usdValueWad:Nr(e.usd_value_wad),accountId:Nr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Lr(e.hub_id),asset:$r(e.asset),amount:Nr(e.amount),fee:Nr(e.fee),amountSent:Nr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:$r(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Cr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:$r(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:$r(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:$r(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:$r(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Cr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Lr(e.max_supply_positions),maxBorrowPositions:Lr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Nr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:$r(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Lr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Nr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Nr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Lr(t.liquidation_bonus_factor_bps)}}}},Xr=Object.freeze(Object.keys(Fr));function Hr(e,t){const r=Br(e),o=Fr[r];return o?o((0,d.scValToNative)(Or(t))):null}const jr="XLENDXLM-a7c9f3",Qr=1e4;function Jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${jr}-${r}`}function Kr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Zr(e,t=0){return e*Qr+t}function Yr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const eo=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},to=e=>e.baseUrl??s[e.network];async function ro(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=eo(to(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function oo(e){const t=eo(to(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ao=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,no=e=>N(e).toXDR("base64");function so(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=U(ao(t,e.referralId));return{xdr:new d.TransactionBuilder(a,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call("execute_strategy",h(e.caller),g(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function io(e,t){return so(e,t)}function lo(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(po),splitPpm:e.splitPpm}))):[{hops:e.hops.map(po),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function uo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:lo(e,t)}const co=lo,po=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function mo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function fo(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw mo(r.invokedContractId,e);throw e}}async function ho(e,t,r){return fo(e,t.xdr,r)}function go(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function So(e,t){return new Uint8Array(0)}const bo=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function wo(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(bo(e.message)),d.xdr.ScVal.scvBytes(bo(e.attestation)));return{xdr:new d.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const _o={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function yo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=_o[r];return o?{code:r,...o}:null}module.exports=t})();
@@ -1 +1 @@
1
- "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as r,Contract as o,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const l={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},u={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},c={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},p={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},d={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},m={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function f(e){const t=l[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function h(e){const t=u[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function g(e){const t=c[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const w=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],_={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},b=1e6,y=e=>new t(e).toScVal(),S=e=>new a(e).toI128(),v=e=>i.ScVal.scvU32(e),k=e=>new a("string"==typeof e?e:e.toString()).toU64(),R=e=>i.ScVal.scvBool(e),T=e=>i.ScVal.scvString(e),I=e=>i.ScVal.scvSymbol(e),x=()=>i.ScVal.scvVoid(),A=e=>i.ScVal.scvVec(e),E=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.ScVal.scvBytes(o)},$=(e,t)=>null==e?x():t(e),B=(e,t)=>O({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([B(e,t),S(r)]),P=e=>i.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),O=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:I(t),val:e[t]})));return i.ScVal.scvMap(t)};class U{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>b)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(_[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>b)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===b;let i=b;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*b/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const L=e=>{const t=new U(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(_.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return O({amounts:i.ScVal.scvVec(t.amountList.map((e=>S(e)))),assets:i.ScVal.scvVec(t.assetList.map((e=>y(e)))),ops:i.ScVal.scvBytes(t.toBytes(r,o,a))})},W=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},q=()=>i.ScVal.scvBytes(Buffer.alloc(0)),D=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},z=e=>{if("string"==typeof e)return W(D(e));if(e instanceof Uint8Array)return 0===e.length?q():W(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?W(D(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?W(D(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?W(D(e.bytes)):0===e.bytes.length?q():W(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!w.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),i.ScVal.scvBytes(Buffer.from(L(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},V=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return i.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function C(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function M(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return C(e,"supply",[y(e.caller),k(r),v(o),P([...t.assets])])}function F(e,t){return M(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function G(e,t){return C(e,"borrow",[y(e.caller),k(t.accountNonce),P([...t.borrows]),$(t.to,y)])}function X(e,t){return G(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function H(e,t){return C(e,"withdraw",[y(e.caller),k(t.accountNonce),P([...t.withdrawals]),$(t.to,y)])}function j(e,t){return H(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function J(e,t){return C(e,"repay",[y(e.caller),k(t.accountNonce),P([...t.payments])])}function Q(e,t){return J(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function K(e,t){return C(e,"liquidate",[y(e.caller),k(t.accountNonce),P([...t.debtPayments])])}function Z(e,t){return C(e,"flash_loan",[y(e.caller),B(t.hubId,t.asset),S(t.amount),y(t.receiver),V(t.data)])}function Y(e,t){return C(e,"migrate_from_blend",[y(e.caller),k(t.accountId),v(t.spokeId),v(t.hubId),y(t.blendPool),A(t.collateralTokens.map(y)),A(t.supplyTokens.map(y)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,i.ScVal.scvVec([y(t),S(r)]);var t,r}))))]);var r}function ee(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return C(e,"multiply",[y(e.caller),k(r),v(o),B(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),B(t.debt.hubId,t.debt.asset),v(t.mode),z(t.steps),$(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),$(t.convertSwap,z)])}function te(e,t){return C(e,"swap_debt",[y(e.caller),k(t.accountNonce),B(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),B(t.newDebt.hubId,t.newDebt.asset),z(t.steps)])}function re(e,t){return C(e,"swap_collateral",[y(e.caller),k(t.accountNonce),B(t.current.hubId,t.current.asset),S(t.fromAmount),B(t.newCollateral.hubId,t.newCollateral.asset),z(t.steps)])}function oe(e,t){return C(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),B(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),B(t.debt.hubId,t.debt.asset),z(t.steps),R(t.closePosition)])}const ae="/stellar-lending",ne=25,se=encodeURIComponent,ie=(e,t)=>e.fetchWithTimeout(`${ae}/context`,t),le=(e,t)=>e.fetchWithTimeout(`${ae}/live-state`,t),ue=(e,t)=>e.fetchWithTimeout(`${ae}/assets`,t),ce=(e,t)=>e.fetchWithTimeout(`${ae}/hubs`,t),pe=(e,t)=>e.fetchWithTimeout(`${ae}/spokes`,t),de=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${ae}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},me=(e,t,r,o,a)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}`,a),fe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}/holders`,{...n,params:{side:a}}),he=(e,t,r)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}`,r),ge=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/page`,{...o,params:{...r}}),we=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/markets`,{...o,params:{side:r}}),_e=(e,t,r)=>e.fetchWithTimeout(`${ae}/hubs/${t}`,r),be=(e,t,r)=>e.fetchWithTimeout(`${ae}/spokes/${t}`,r),ye=(e,t,r)=>e.fetchWithTimeout(`${ae}/users/${se(t)}/positions`,r),Se=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${ae}/users/${se(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},ve=(e,t,r)=>e.fetchWithTimeout(`${ae}/accounts/${se(t)}/positions`,r),ke=(e,t={},r)=>{const{top:o=ne,continuationToken:a}=t;return e.fetchWithTimeout(`${ae}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Re=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/graph`,{...o,params:{...r}}),Te=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/hubs/${t}/graph`,{...o,params:{...r}}),Ie=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/spokes/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}/graph`,{...n,params:{...a}}),Ae=(e,t)=>e.fetchWithTimeout(`${ae}/protocol-config`,t),Ee=(e,t,r)=>e.fetchWithTimeout(`${ae}/protocol-config/${se(t)}`,r),$e=(e,t,r)=>e.fetchWithTimeout(t?`${ae}/roles?contractAddress=${se(t)}`:`${ae}/roles`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${ae}/accounts/${se(String(t))}/delegates`,r),Ne=(e,t)=>e.fetchWithTimeout(`${ae}/blend-pools`,t),Pe=e=>({context:t=>ie(e,t),liveState:t=>le(e,t),protocolConfig:t=>Ae(e,t),contractConfig:(t,r)=>Ee(e,t,r),contractRoles:(t,r)=>$e(e,t,r),accountDelegates:(t,r)=>Be(e,t,r),blendPools:t=>Ne(e,t),assets:t=>ue(e,t),hubs:t=>ce(e,t),spokes:t=>pe(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?de(e,t,r):de(e,{},t);var o},reserve:(t,r,o,a)=>me(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>fe(e,t,r,o,a,n),asset:(t,r)=>he(e,t,r),assetMarkets:(t,r,o)=>we(e,t,r,o),hub:(t,r)=>_e(e,t,r),spoke:(t,r)=>be(e,t,r),userPositions:(t,r)=>ye(e,t,r),userActivity:(t,r,o)=>Se(e,t,r,o),accountPositions:(t,r)=>ve(e,t,r),governanceProposals:(t,r)=>ke(e,t,r),assetGraph:(t,r,o)=>Re(e,t,r,o),hubGraph:(t,r,o)=>Te(e,t,r,o),spokeGraph:(t,r,o)=>Ie(e,t,r,o),reserveGraph:(t,r,o,a,n)=>xe(e,t,r,o,a,n)}),Oe=e=>O({base_borrow_rate:S(e.baseBorrowRateRay),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),Ue=e=>O({asset_decimals:v(e.assetDecimals),asset_id:y(e.assetId),base_borrow_rate:S(e.baseBorrowRateRay),flashloan_fee:v(e.flashloanFeeBps),is_flashloanable:R(e.isFlashloanable),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),Le=e=>O({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),We=e=>{if("Token"in e&&e.Token)return A([I("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([I("Ref"),I(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},qe=e=>{if("Stellar"in e)return A([I("Stellar"),y(e.Stellar)]);if("Symbol"in e)return A([I("Symbol"),I(e.Symbol)]);if("String"in e)return A([I("String"),T(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},De=e=>{if("Spot"===e)return A([I("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return A([I("Twap"),v(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},ze=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ve=e=>{if("Market"===e||"Fundamental"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ce=e=>{if("Reflector"in e){const t=e.Reflector;return A([I("Reflector"),O({asset:qe(t.asset),contract:y(t.contract),read_mode:De(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([I("MultiFeed"),O({contract:y(t.contract),feed_id:T(t.feedId),kind:ze(t.kind),nature:Ve(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Me=e=>{const t=e;return O({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:Ce(t.provider)})},Fe=e=>{if("RequireDisjoint"===e)return A([I("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([I("AllowShared"),A(t.map((e=>O({contract:y(e.contract),kind:ze(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},Ge=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return O({asset_decimals:v(Number(t.assetDecimals)),independence:Fe(t.independence),max_price_stale_seconds:k(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:S(String(t.maxSanityPriceWad)),min_sanity_price_wad:S(String(t.minSanityPriceWad)),sources:A(r.map((e=>(e=>{if("Feed"in e)return A([I("Feed"),Me(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([I("Scaled"),O({factor:Me(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:We(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([I("LpShare"),O({key_a:We(t.keyA),key_b:We(t.keyB),kind:A([I(t.kind||"ConstantProduct")]),pool:y(t.pool),reserve_a_decimals:v(t.reserveADecimals),reserve_b_decimals:v(t.reserveBDecimals),share_decimals:v(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:O({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})})},Xe=Ge;function He(e,t){return C(e,"upgrade",[E(t.wasmHash)])}function je(e,t){return C(e,"migrate",[v(t.newVersion)])}function Je(e){return C(e,"pause",[])}function Qe(e){return C(e,"unpause",[])}function Ke(e,t){return C(e,"grant_role",[y(t.account),I(t.role)])}function Ze(e,t){return C(e,"revoke_role",[y(t.account),I(t.role)])}function Ye(e,t){return C(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function et(e){return C(e,"accept_ownership",[])}function tt(e,t){return C(e,"set_swap_aggregator",[y(t.aggregator)])}function rt(e,t){return C(e,"set_price_aggregator",[y(t.aggregator)])}const ot=tt;function at(e,t){return C(e,"set_accumulator",[y(t.accumulator)])}function nt(e,t){return C(e,"set_position_limits",[Le(t)])}function st(e,t){return C(e,"approve_blend_pool",[y(t.pool)])}function it(e,t){return C(e,"revoke_blend_pool",[y(t.pool)])}const lt=st,ut=it;function ct(e,t){return C(e,"set_oracle",[We(t.key),Ge(t.oracle)])}const pt=ct;function dt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return C(e,"set_tolerance",[We(t.key),O({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function mt(e,t){return C(e,"set_spoke_asset_flags",[v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function ft(e,t){return C(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function ht(e,t){return C(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function gt(e,t){return C(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function wt(e,t){return C(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),Ue(t.params)])}function _t(e,t){return C(e,"upgrade_liquidity_pool_params",[B(t.hubId,t.asset),Oe(t.params)])}function bt(e,t){return C(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function yt(e,t){return C(e,"add_rewards",[y(e.caller),P(t.rewards)])}function St(e,t){return C(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const vt="00".repeat(32),kt=e=>{if("string"==typeof e)return E(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return i.ScVal.scvBytes(t)},Rt=(e,...t)=>A([I(e),...t]),Tt=e=>O({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),It=e=>O({asset:y(e.asset),bonus:v(e.bonus),borrow_cap:S(e.borrowCap),can_borrow:R(e.canBorrow),can_collateral:R(e.canCollateral),frozen:R(e.frozen),hub_id:v(e.hubId),paused:R(e.paused),liquidation_fees:v(e.liquidationFees),ltv:v(e.ltv),oracle_override:A([I("None")]),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),xt=e=>O({account:y(e.account),role:I(e.role)});function At(t,a,s){const i=t.governanceAddress??g(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const Et=(e,t,r)=>At(e,"propose",[y(e.caller),t,kt(r)]),$t=(e,t,r)=>At(e,"execute_self",[x(),t,kt(r)]);function Bt(e,t,r){return Et(e,Rt("SetSwapAggregator",y(t.aggregator)),r)}function Nt(e,t,r){return Et(e,Rt("SetPriceAggregator",y(t.aggregator)),r)}const Pt=Bt;function Ot(e,t,r){return Et(e,Rt("SetAccumulator",y(t.accumulator)),r)}function Ut(e,t,r){return Et(e,Rt("SetPositionLimits",Le(t)),r)}function Lt(e,t){return Et(e,Rt("CreateHub"),t)}function Wt(e,t){return Et(e,Rt("AddSpoke"),t)}function qt(e,t,r){return Et(e,Rt("RemoveSpoke",v(t.spokeId)),r)}function Dt(e,t,r){return Et(e,Rt("AddAssetToSpoke",It(t)),r)}function zt(e,t,r){return Et(e,Rt("EditAssetInSpoke",It(t)),r)}function Vt(e,t,r){return Et(e,Rt("RemoveAssetFromSpoke",O({hub_asset:B((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function Ct(e,t,r){return Et(e,Rt("SetSpokeLiquidationCurve",O({hf_for_max_bonus_wad:S((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:v(o.liquidationBonusFactorBps),spoke_id:v(o.spokeId),target_hf_wad:S(o.targetHfWad)})),r);var o}function Mt(e,t,r){return Et(e,Rt("SetPositionManager",y(t.manager),R(t.isActive)),r)}function Ft(e,t,r){return Et(e,Rt("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Gt(e,t,r){return Et(e,Rt("ApproveToken",y(t.token)),r)}function Xt(e,t,r){return Et(e,Rt("RevokeToken",y(t.token)),r)}function Ht(e,t,r){return Et(e,Rt("ApproveBlendPool",y(t.pool)),r)}function jt(e,t,r){return Et(e,Rt("RevokeBlendPool",y(t.pool)),r)}function Jt(e,t,r){return Et(e,Rt("CreateLiquidityPool",O({asset:y((o=t).asset),hub_id:v(o.hubId),params:Ue(o.params)})),r);var o}function Qt(e,t,r){return Et(e,Rt("UpgradeLiquidityPoolParams",O({hub_asset:B((o=t).hubId,o.asset),params:Oe(o.params)})),r);var o}function Kt(e,t,r){return Et(e,Rt("DeployPool",E(t.wasmHash)),r)}function Zt(e,t,r){return Et(e,Rt("UpgradePool",E(t.wasmHash)),r)}function Yt(e,t,r){return Et(e,Rt("UpgradeController",E(t.wasmHash)),r)}function er(e,t,r){return Et(e,Rt("MigrateController",v(t.newVersion)),r)}function tr(e,t,r){return Et(e,Rt("TransferCtrlOwnership",Tt(t)),r)}function rr(e,t,r){return Et(e,Rt("ConfigureAssetOracle",O({key:We((o=t).key),oracle:Ge(o.oracle)})),r);var o}const or=rr;function ar(e,t,r){return Et(e,Rt("EditOracleTolerance",O({key:We((o=t).key),tolerance:v(o.tolerance)})),r);var o}function nr(e,t,r){return Et(e,Rt("UpgradeGov",E(t.wasmHash)),r)}function sr(e,t,r){return Et(e,Rt("UpdateGovDelay",v(t.newDelay)),r)}function ir(e,t,r){return Et(e,Rt("GrantGovRole",xt(t)),r)}function lr(e,t,r){return Et(e,Rt("RevokeGovRole",xt(t)),r)}function ur(e,t,r){return Et(e,Rt("TransferGovOwnership",Tt(t)),r)}function cr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=kt(t.predecessor??vt);return At(e,"execute",[x(),y(t.target),I(t.functionName),r,o,kt(t.salt)])}function pr(e,t,r){return $t(e,Rt("UpgradeGov",E(t.wasmHash)),r)}function dr(e,t,r){return $t(e,Rt("UpdateGovDelay",v(t.newDelay)),r)}function mr(e,t,r){return $t(e,Rt("GrantGovRole",xt(t)),r)}function fr(e,t,r){return $t(e,Rt("RevokeGovRole",xt(t)),r)}function hr(e,t,r){return $t(e,Rt("TransferGovOwnership",Tt(t)),r)}const gr=e=>A(e.map(y));function wr(e,t,r){return At(e,"propose_canceller_reset",[gr(t.newCancellers),kt(r)])}function _r(e,t,r){return At(e,"execute_canceller_reset",[$(t.executor,y),gr(t.newCancellers),kt(r)])}function br(e,t){return At(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function yr(e,t){return At(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function Sr(e){return At(e,"create_hub",[y(e.caller)])}function vr(e){return At(e,"add_spoke",[y(e.caller)])}function kr(e,t){return At(e,"revoke_role_immediate",[y(t.account),I(t.role)])}function Rr(e){return At(e,"pause",[y(e.caller)])}function Tr(e,t){return Et(e,Rt("Unpause"),t)}const Ir=e=>e.toXDR("base64"),xr=e=>i.ScVal.fromXDR(e,"base64"),Ar=e=>e.map((e=>String(s(xr(e))))).join(":"),Er=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),$r=e=>Number(e),Br=e=>String(e),Nr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Pr=["None","Multiply","Long","Short"],Or=["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"],Ur=e=>Array.isArray(e)?e:[],Lr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Or[$r(o)]??Er(o)),positionType:t,hubId:$r(e[1]),asset:Br(e[2]),scaledAmountRay:Er(e[3]),indexRay:Er(e[4]),amount:Er(e[5]),liquidationThresholdBps:r?void 0:$r(e[6]),liquidationBonusBps:r?void 0:$r(e[7]),loanToValueBps:r?void 0:$r(e[8]),liquidationFeesBps:r?void 0:$r(e[9])};var o},Wr=e=>{return{owner:Br(e[0]),spokeId:$r(e[1]),mode:(t=e[2],Pr[$r(t)]??"None")};var t},qr=e=>Array.isArray(e)?e[1]:void 0,Dr=e=>{const t=(r=e,Array.isArray(r)?Br(r[0]):Br(r));var r;if("Token"===t)return{Token:Br(qr(e))};if("Ref"===t)return{Ref:Br(qr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Br(t.Token)};if(void 0!==t.Ref)return{Ref:Br(t.Ref)}}return{Token:Br(e)}},zr=e=>{const t=e.tolerance??{};return{assetDecimals:$r(e.asset_decimals),maxPriceStaleSeconds:$r(e.max_price_stale_seconds),sources:Ur(e.sources).map((e=>e)),tolerance:{upperRatio:$r(t.upper_ratio_bps),lowerRatio:$r(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Er(e.min_sanity_price_wad),maxSanityPriceWad:Er(e.max_sanity_price_wad)}},Vr={"market:create":e=>({topic:"market:create",data:{hubId:$r(e.hub_id),baseAsset:Br(e.base_asset),maxBorrowRate:Er(e.max_borrow_rate),baseBorrowRate:Er(e.base_borrow_rate),slope1:Er(e.slope1),slope2:Er(e.slope2),slope3:Er(e.slope3),midUtilization:Er(e.mid_utilization),optimalUtilization:Er(e.optimal_utilization),maxUtilization:Er(e.max_utilization),reserveFactor:$r(e.reserve_factor),marketAddress:Br(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Br(e.asset),maxBorrowRateRay:Er(e.max_borrow_rate),baseBorrowRateRay:Er(e.base_borrow_rate),slope1Ray:Er(e.slope1),slope2Ray:Er(e.slope2),slope3Ray:Er(e.slope3),midUtilizationRay:Er(e.mid_utilization),optimalUtilizationRay:Er(e.optimal_utilization),maxUtilizationRay:Er(e.max_utilization),reserveFactorBps:$r(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ur(e).map((e=>{return t=Ur(e),{hubId:$r(t[0]),asset:Br(t[1]),timestamp:$r(t[2]),supplyIndexRay:Er(t[3]),borrowIndexRay:Er(t[4]),cash:Er(t[5]),suppliedRay:Er(t[6]),borrowedRay:Er(t[7]),revenueRay:Er(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ur(e).map((e=>{const t=e;return{hubId:$r(t.hub_id),asset:Br(t.asset),params:(r=t.params,{maxBorrowRateRay:Er(r.max_borrow_rate),baseBorrowRateRay:Er(r.base_borrow_rate),slope1Ray:Er(r.slope1),slope2Ray:Er(r.slope2),slope3Ray:Er(r.slope3),midUtilizationRay:Er(r.mid_utilization),optimalUtilizationRay:Er(r.optimal_utilization),maxUtilizationRay:Er(r.max_utilization),reserveFactorBps:$r(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:$r(r.flashloan_fee),assetId:Br(r.asset_id),assetDecimals:$r(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ur(e);return{topic:"position:batch_update",data:{accountId:Er(t[0]),accountAttributes:Wr(Ur(t[1])),updates:[...Ur(t[2]).map((e=>Lr(Ur(e),"Deposit"))),...Ur(t[3]).map((e=>Lr(Ur(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:$r(e.hub_id),asset:Br(e.asset),receiver:Br(e.receiver),caller:Br(e.caller),amount:Er(e.amount),fee:Er(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Dr(e.key),oracle:zr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Br(e.asset),oracle:zr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Br(e.liquidator),accountId:Er(e.account_id),repaidUsdWad:Er(e.repaid_usd_wad),bonusBps:Er(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Er(e.account_id),totalBorrowUsdWad:Er(e.total_borrow_usd_wad),totalCollateralUsdWad:Er(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Br(e.token),amount:Er(e.amount),usdValueWad:Er(e.usd_value_wad),accountId:Er(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:$r(e.hub_id),asset:Br(e.asset),amount:Er(e.amount),fee:Er(e.fee),amountSent:Er(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Br(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Nr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Br(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Br(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Br(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Br(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Nr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:$r(e.max_supply_positions),maxBorrowPositions:$r(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Er(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Br(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:$r(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Er(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Er(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:$r(t.liquidation_bonus_factor_bps)}}}},Cr=Object.freeze(Object.keys(Vr));function Mr(e,t){const r=Ar(e),o=Vr[r];return o?o(s(xr(t))):null}const Fr="XLENDXLM-a7c9f3",Gr=1e4;function Xr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Fr}-${r}`}function Hr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function jr(e,t=0){return 1e4*e+t}function Jr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Qr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Kr=e=>e.baseUrl??d[e.network];async function Zr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Qr(Kr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function Yr(e){const t=Qr(Kr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const eo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,to=e=>L(e).toXDR("base64");function ro(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=z(eo(a,t.referralId));return{xdr:new n(l,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",y(t.caller),S(t.totalIn),u)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function oo(e,t){return ro(e,t)}function ao(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(io),splitPpm:e.splitPpm}))):[{hops:e.hops.map(io),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function no(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:ao(e,t)}const so=ao,io=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function lo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function uo(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw lo(r.invokedContractId,e);throw e}}async function co(e,t,r){return uo(e,t.xdr,r)}function po(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function mo(e,t){return new Uint8Array(0)}const fo=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function ho(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(fo(t.message)),i.ScVal.scvBytes(fo(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const go={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},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 wo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=go[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,vt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Cr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Gr as SYNTHETIC_EVENT_ORDER_STRIDE,Fr as XOXNO_LENDING_STELLAR_TICKER,mo as buildSameTokenRepaySwapSteps,et as buildStellarAcceptOwnershipTx,yt as buildStellarAddRewardsTx,st as buildStellarApproveBlendPoolTx,lt as buildStellarApproveTokenTx,oo as buildStellarBatchSwapTx,G as buildStellarBorrowBatchTx,X as buildStellarBorrowTx,ho as buildStellarCctpForwardTx,bt as buildStellarClaimRevenueTx,wt as buildStellarCreateLiquidityPoolTx,_r as buildStellarExecuteCancellerResetTx,ro as buildStellarExecuteStrategyTx,Z as buildStellarFlashLoanTx,vr as buildStellarGovernanceAddSpokeImmediateTx,Sr as buildStellarGovernanceCreateHubImmediateTx,pr as buildStellarGovernanceExecuteGovernanceUpgradeTx,mr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,fr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,hr as buildStellarGovernanceExecuteTransferGovOwnTx,cr as buildStellarGovernanceExecuteTx,dr as buildStellarGovernanceExecuteUpdateDelayTx,Rr as buildStellarGovernancePauseTx,kr as buildStellarGovernanceRevokeRoleImmediateTx,yr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,br as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ke as buildStellarGrantRoleTx,Xr as buildStellarLendingIdentifier,K as buildStellarLiquidateTx,Y as buildStellarMigrateFromBlendTx,je as buildStellarMigrateTx,ee as buildStellarMultiplyTx,Je as buildStellarPauseTx,Dt as buildStellarProposeAddAssetToSpokeTx,Wt as buildStellarProposeAddSpokeTx,Ht as buildStellarProposeApproveBlendPoolTx,Gt as buildStellarProposeApproveTokenTx,wr as buildStellarProposeCancellerResetTx,rr as buildStellarProposeConfigureAssetOracleTx,or as buildStellarProposeConfigureMarketOracleTx,Lt as buildStellarProposeCreateHubTx,Jt as buildStellarProposeCreateLiquidityPoolTx,Kt as buildStellarProposeDeployPoolTx,zt as buildStellarProposeEditAssetInSpokeTx,ar as buildStellarProposeEditOracleToleranceTx,nr as buildStellarProposeGovernanceUpgradeTx,ir as buildStellarProposeGrantGovernanceRoleTx,er as buildStellarProposeMigrateControllerTx,Vt as buildStellarProposeRemoveAssetFromSpokeTx,qt as buildStellarProposeRemoveSpokeTx,jt as buildStellarProposeRevokeBlendPoolTx,lr as buildStellarProposeRevokeGovernanceRoleTx,Xt as buildStellarProposeRevokeTokenTx,Ot as buildStellarProposeSetAccumulatorTx,Pt as buildStellarProposeSetAggregatorTx,Ft as buildStellarProposeSetMinBorrowCollatTx,Ut as buildStellarProposeSetPositionLimitsTx,Mt as buildStellarProposeSetPositionManagerTx,Nt as buildStellarProposeSetPriceAggregatorTx,Ct as buildStellarProposeSetSpokeLiquidationCurveTx,Bt as buildStellarProposeSetSwapAggregatorTx,tr as buildStellarProposeTransferCtrlOwnershipTx,ur as buildStellarProposeTransferGovOwnTx,Tr as buildStellarProposeUnpauseTx,sr as buildStellarProposeUpdateDelayTx,Yt as buildStellarProposeUpgradeControllerTx,Qt as buildStellarProposeUpgradePoolParamsTx,Zt as buildStellarProposeUpgradePoolTx,gt as buildStellarRenewAccountTx,J as buildStellarRepayBatchTx,oe as buildStellarRepayDebtWithCollateralTx,Q as buildStellarRepayTx,it as buildStellarRevokeBlendPoolTx,Ze as buildStellarRevokeRoleTx,ut as buildStellarRevokeTokenTx,at as buildStellarSetAccumulatorTx,ot as buildStellarSetAggregatorTx,pt as buildStellarSetMarketOracleConfigTx,ft as buildStellarSetOracleSanityBoundsTx,dt as buildStellarSetOracleToleranceTx,ct as buildStellarSetOracleTx,nt as buildStellarSetPositionLimitsTx,rt as buildStellarSetPriceAggregatorTx,mt as buildStellarSetSpokeAssetFlagsTx,tt as buildStellarSetSwapAggregatorTx,M as buildStellarSupplyBatchTx,F as buildStellarSupplyTx,re as buildStellarSwapCollateralTx,te as buildStellarSwapDebtTx,Ye as buildStellarTransferOwnershipTx,Qe as buildStellarUnpauseTx,St as buildStellarUpdateAccountThresholdTx,ht as buildStellarUpdateIndexesTx,He as buildStellarUpgradeControllerTx,_t as buildStellarUpgradeLiquidityPoolParamsTx,H as buildStellarWithdrawBatchTx,j as buildStellarWithdrawTx,C as buildTx,Mr as decodeStellarLendingEvent,Ge as encodeAssetOracle,Oe as encodeInterestRateModel,Xe as encodeMarketOracleConfigInput,Ue as encodeMarketParamsRaw,Le as encodePositionLimits,We as encodePriceKey,to as encodeStrategyPayloadToRouteXdr,Hr as extractEventOrder,Be as getStellarAccountDelegates,ve as getStellarAccountPositions,Zr as getStellarAggregatorQuote,h as getStellarAggregatorRouter,he as getStellarAsset,Re as getStellarAssetGraph,we as getStellarAssetMarkets,ge as getStellarAssetPage,ue as getStellarAssets,Ne as getStellarBlendPools,Ee as getStellarContractConfig,$e as getStellarContractRoles,g as getStellarGovernance,ke as getStellarGovernanceProposals,_e as getStellarHub,Te as getStellarHubGraph,ce as getStellarHubs,ie as getStellarLendingContext,f as getStellarLendingController,le as getStellarLendingLiveState,Ae as getStellarProtocolConfig,Yr as getStellarQuoteTokens,me as getStellarReserve,xe as getStellarReserveGraph,fe as getStellarReserveHolders,de as getStellarReserves,be as getStellarSpoke,Ie as getStellarSpokeGraph,pe as getStellarSpokes,Se as getStellarUserActivity,ye as getStellarUserPositions,so as mapQuoteResponseToAggregatorSwap,ao as mapQuoteResponseToStrategyPayload,no as mapQuoteResponseToStrategySwap,wo as mapSorobanError,Jr as mapStellarPositionActivityType,co as prepareStellarBuiltTx,uo as prepareStellarTxXdr,Ar as stellarLendingDispatchKey,Pe as stellarLendingRead,jr as syntheticEventOrder,lo as tagStellarInvokedContractError,Ir as toBase64Xdr,po as toStellarPositionMode};
1
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as r,Contract as o,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const l={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},u={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},c={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},p={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},d={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},m={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function f(e){const t=l[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function h(e){const t=u[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function g(e){const t=c[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const w=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],_={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},b=1e6,y=e=>new t(e).toScVal(),S=e=>new a(e).toI128(),v=e=>i.ScVal.scvU32(e),k=e=>new a("string"==typeof e?e:e.toString()).toU64(),R=e=>i.ScVal.scvBool(e),T=e=>i.ScVal.scvString(e),I=e=>i.ScVal.scvSymbol(e),x=()=>i.ScVal.scvVoid(),A=e=>i.ScVal.scvVec(e),E=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.ScVal.scvBytes(o)},$=(e,t)=>null==e?x():t(e),B=(e,t)=>U({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([B(e,t),S(r)]),P=e=>i.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),O=e=>{if("Transfer"===e)return A([I("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return A([I("Credit"),k(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},U=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:I(t),val:e[t]})));return i.ScVal.scvMap(t)};class L{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>b)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(_[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>b)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===b;let i=b;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*b/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const q=e=>{const t=new L(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(_.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return U({amounts:i.ScVal.scvVec(t.amountList.map((e=>S(e)))),assets:i.ScVal.scvVec(t.assetList.map((e=>y(e)))),ops:i.ScVal.scvBytes(t.toBytes(r,o,a))})},z=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},W=()=>i.ScVal.scvBytes(Buffer.alloc(0)),D=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},C=e=>{if("string"==typeof e)return z(D(e));if(e instanceof Uint8Array)return 0===e.length?W():z(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?z(D(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?z(D(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?z(D(e.bytes)):0===e.bytes.length?W():z(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!w.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),i.ScVal.scvBytes(Buffer.from(q(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},V=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return i.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function M(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function F(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"supply",[y(e.caller),k(r),v(o),P([...t.assets])])}function G(e,t){return F(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function X(e,t){return M(e,"borrow",[y(e.caller),k(t.accountNonce),P([...t.borrows]),$(t.to,y)])}function H(e,t){return X(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function j(e,t){return M(e,"withdraw",[y(e.caller),k(t.accountNonce),P([...t.withdrawals]),$(t.to,y)])}function J(e,t){return j(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function Q(e,t){return M(e,"repay",[y(e.caller),k(t.accountNonce),P([...t.payments])])}function K(e,t){return Q(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function Z(e,t){return M(e,"liquidate",[y(e.caller),k(t.accountNonce),P([...t.debtPayments]),O(t.seizeMode??"Transfer")])}function Y(e){const t=s(i.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function ee(e,t){return M(e,"flash_loan",[y(e.caller),B(t.hubId,t.asset),S(t.amount),y(t.receiver),V(t.data)])}function te(e,t){return M(e,"migrate_from_blend",[y(e.caller),k(t.accountId),v(t.spokeId),v(t.hubId),y(t.blendPool),A(t.collateralTokens.map(y)),A(t.supplyTokens.map(y)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,i.ScVal.scvVec([y(t),S(r)]);var t,r}))))]);var r}function re(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"multiply",[y(e.caller),k(r),v(o),B(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),B(t.debt.hubId,t.debt.asset),v(t.mode),C(t.steps),$(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),$(t.convertSwap,C)])}function oe(e,t){return M(e,"swap_debt",[y(e.caller),k(t.accountNonce),B(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),B(t.newDebt.hubId,t.newDebt.asset),C(t.steps)])}function ae(e,t){return M(e,"swap_collateral",[y(e.caller),k(t.accountNonce),B(t.current.hubId,t.current.asset),S(t.fromAmount),B(t.newCollateral.hubId,t.newCollateral.asset),C(t.steps)])}function ne(e,t){return M(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),B(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),B(t.debt.hubId,t.debt.asset),C(t.steps),R(t.closePosition)])}const se="/stellar-lending",ie=25,le=encodeURIComponent,ue=(e,t)=>e.fetchWithTimeout(`${se}/context`,t),ce=(e,t)=>e.fetchWithTimeout(`${se}/live-state`,t),pe=(e,t)=>e.fetchWithTimeout(`${se}/assets`,t),de=(e,t)=>e.fetchWithTimeout(`${se}/hubs`,t),me=(e,t)=>e.fetchWithTimeout(`${se}/spokes`,t),fe=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${se}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},he=(e,t,r,o,a)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}`,a),ge=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/holders`,{...n,params:{side:a}}),we=(e,t,r)=>e.fetchWithTimeout(`${se}/assets/${le(t)}`,r),_e=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/page`,{...o,params:{...r}}),be=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/markets`,{...o,params:{side:r}}),ye=(e,t,r)=>e.fetchWithTimeout(`${se}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${se}/spokes/${t}`,r),ve=(e,t,r)=>e.fetchWithTimeout(`${se}/users/${le(t)}/positions`,r),ke=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${se}/users/${le(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},Re=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(t)}/positions`,r),Te=(e,t={},r)=>{const{top:o=ie,continuationToken:a}=t;return e.fetchWithTimeout(`${se}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Ie=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${se}/hubs/${t}/graph`,{...o,params:{...r}}),Ae=(e,t,r,o)=>e.fetchWithTimeout(`${se}/spokes/${t}/graph`,{...o,params:{...r}}),Ee=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/graph`,{...n,params:{...a}}),$e=(e,t)=>e.fetchWithTimeout(`${se}/protocol-config`,t),Be=(e,t,r)=>e.fetchWithTimeout(`${se}/protocol-config/${le(t)}`,r),Ne=(e,t,r)=>e.fetchWithTimeout(t?`${se}/roles?contractAddress=${le(t)}`:`${se}/roles`,r),Pe=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(String(t))}/delegates`,r),Oe=(e,t)=>e.fetchWithTimeout(`${se}/blend-pools`,t),Ue=e=>({context:t=>ue(e,t),liveState:t=>ce(e,t),protocolConfig:t=>$e(e,t),contractConfig:(t,r)=>Be(e,t,r),contractRoles:(t,r)=>Ne(e,t,r),accountDelegates:(t,r)=>Pe(e,t,r),blendPools:t=>Oe(e,t),assets:t=>pe(e,t),hubs:t=>de(e,t),spokes:t=>me(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?fe(e,t,r):fe(e,{},t);var o},reserve:(t,r,o,a)=>he(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ge(e,t,r,o,a,n),asset:(t,r)=>we(e,t,r),assetMarkets:(t,r,o)=>be(e,t,r,o),hub:(t,r)=>ye(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>ve(e,t,r),userActivity:(t,r,o)=>ke(e,t,r,o),accountPositions:(t,r)=>Re(e,t,r),governanceProposals:(t,r)=>Te(e,t,r),assetGraph:(t,r,o)=>Ie(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>Ae(e,t,r,o),reserveGraph:(t,r,o,a,n)=>Ee(e,t,r,o,a,n)}),Le=e=>U({base_borrow_rate:S(e.baseBorrowRateRay),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),qe=e=>U({asset_decimals:v(e.assetDecimals),asset_id:y(e.assetId),base_borrow_rate:S(e.baseBorrowRateRay),flashloan_fee:v(e.flashloanFeeBps),is_flashloanable:R(e.isFlashloanable),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),ze=e=>U({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),We=e=>{if("Token"in e&&e.Token)return A([I("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([I("Ref"),I(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},De=e=>{if("Stellar"in e)return A([I("Stellar"),y(e.Stellar)]);if("Symbol"in e)return A([I("Symbol"),I(e.Symbol)]);if("String"in e)return A([I("String"),T(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ce=e=>{if("Spot"===e)return A([I("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return A([I("Twap"),v(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ve=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Me=e=>{if("Market"===e||"Fundamental"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Fe=e=>{if("Reflector"in e){const t=e.Reflector;return A([I("Reflector"),U({asset:De(t.asset),contract:y(t.contract),read_mode:Ce(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([I("MultiFeed"),U({contract:y(t.contract),feed_id:T(t.feedId),kind:Ve(t.kind),nature:Me(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ge=e=>{const t=e;return U({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:Fe(t.provider)})},Xe=e=>{if("RequireDisjoint"===e)return A([I("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([I("AllowShared"),A(t.map((e=>U({contract:y(e.contract),kind:Ve(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},He=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return U({asset_decimals:v(Number(t.assetDecimals)),independence:Xe(t.independence),max_price_stale_seconds:k(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:S(String(t.maxSanityPriceWad)),min_sanity_price_wad:S(String(t.minSanityPriceWad)),sources:A(r.map((e=>(e=>{if("Feed"in e)return A([I("Feed"),Ge(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([I("Scaled"),U({factor:Ge(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:We(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([I("LpShare"),U({key_a:We(t.keyA),key_b:We(t.keyB),kind:A([I(t.kind||"ConstantProduct")]),pool:y(t.pool),reserve_a_decimals:v(t.reserveADecimals),reserve_b_decimals:v(t.reserveBDecimals),share_decimals:v(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})})},je=He;function Je(e,t){return M(e,"upgrade",[E(t.wasmHash)])}function Qe(e,t){return M(e,"migrate",[v(t.newVersion)])}function Ke(e){return M(e,"pause",[])}function Ze(e){return M(e,"unpause",[])}function Ye(e,t){return M(e,"grant_role",[y(t.account),I(t.role)])}function et(e,t){return M(e,"revoke_role",[y(t.account),I(t.role)])}function tt(e,t){return M(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function rt(e){return M(e,"accept_ownership",[])}function ot(e,t){return M(e,"set_swap_aggregator",[y(t.aggregator)])}function at(e,t){return M(e,"set_price_aggregator",[y(t.aggregator)])}const nt=ot;function st(e,t){return M(e,"set_accumulator",[y(t.accumulator)])}function it(e,t){return M(e,"set_position_limits",[ze(t)])}function lt(e,t){return M(e,"approve_blend_pool",[y(t.pool)])}function ut(e,t){return M(e,"revoke_blend_pool",[y(t.pool)])}const ct=lt,pt=ut;function dt(e,t){return M(e,"set_oracle",[We(t.key),He(t.oracle)])}const mt=dt;function ft(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return M(e,"set_tolerance",[We(t.key),U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function ht(e,t){return M(e,"set_spoke_asset_flags",[v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function gt(e,t){return M(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function wt(e,t){return M(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function _t(e,t){return M(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function bt(e,t){return M(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),qe(t.params)])}function yt(e,t){return M(e,"upgrade_liquidity_pool_params",[B(t.hubId,t.asset),Le(t.params)])}function St(e,t){return M(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function vt(e,t){return M(e,"add_rewards",[y(e.caller),P(t.rewards)])}function kt(e,t){return M(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const Rt="00".repeat(32),Tt=e=>{if("string"==typeof e)return E(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return i.ScVal.scvBytes(t)},It=(e,...t)=>A([I(e),...t]),xt=e=>U({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),At=e=>U({asset:y(e.asset),bonus:v(e.bonus),borrow_cap:S(e.borrowCap),can_borrow:R(e.canBorrow),can_collateral:R(e.canCollateral),frozen:R(e.frozen),hub_id:v(e.hubId),paused:R(e.paused),liquidation_fees:v(e.liquidationFees),ltv:v(e.ltv),no_seize:R(e.noSeize),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),Et=e=>U({account:y(e.account),role:I(e.role)});function $t(t,a,s){const i=t.governanceAddress??g(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const Bt=(e,t,r)=>$t(e,"propose",[y(e.caller),t,Tt(r)]),Nt=(e,t,r)=>$t(e,"execute_self",[x(),t,Tt(r)]);function Pt(e,t,r){return Bt(e,It("SetSwapAggregator",y(t.aggregator)),r)}function Ot(e,t,r){return Bt(e,It("SetPriceAggregator",y(t.aggregator)),r)}const Ut=Pt;function Lt(e,t,r){return Bt(e,It("SetAccumulator",y(t.accumulator)),r)}function qt(e,t,r){return Bt(e,It("SetPositionLimits",ze(t)),r)}function zt(e,t){return Bt(e,It("CreateHub"),t)}function Wt(e,t){return Bt(e,It("AddSpoke"),t)}function Dt(e,t,r){return Bt(e,It("RemoveSpoke",v(t.spokeId)),r)}function Ct(e,t,r){return Bt(e,It("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Bt(e,It("EditAssetInSpoke",At(t)),r)}function Mt(e,t,r){return Bt(e,It("RemoveAssetFromSpoke",U({hub_asset:B((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function Ft(e,t,r){return Bt(e,It("SetSpokeLiquidationCurve",U({hf_for_max_bonus_wad:S((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:v(o.liquidationBonusFactorBps),spoke_id:v(o.spokeId),target_hf_wad:S(o.targetHfWad)})),r);var o}function Gt(e,t,r){return Bt(e,It("SetPositionManager",y(t.manager),R(t.isActive)),r)}function Xt(e,t,r){return Bt(e,It("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Ht(e,t,r){return Bt(e,It("ApproveToken",y(t.token)),r)}function jt(e,t,r){return Bt(e,It("RevokeToken",y(t.token)),r)}function Jt(e,t,r){return Bt(e,It("ApproveBlendPool",y(t.pool)),r)}function Qt(e,t,r){return Bt(e,It("RevokeBlendPool",y(t.pool)),r)}function Kt(e,t,r){return Bt(e,It("CreateLiquidityPool",U({asset:y((o=t).asset),hub_id:v(o.hubId),params:qe(o.params)})),r);var o}function Zt(e,t,r){return Bt(e,It("UpgradeLiquidityPoolParams",U({hub_asset:B((o=t).hubId,o.asset),params:Le(o.params)})),r);var o}function Yt(e,t,r){return Bt(e,It("DeployPool",E(t.wasmHash)),r)}function er(e,t,r){return Bt(e,It("UpgradePool",E(t.wasmHash)),r)}function tr(e,t,r){return Bt(e,It("UpgradeController",E(t.wasmHash)),r)}function rr(e,t,r){return Bt(e,It("MigrateController",v(t.newVersion)),r)}function or(e,t,r){return Bt(e,It("TransferCtrlOwnership",xt(t)),r)}function ar(e,t,r){return Bt(e,It("ConfigureAssetOracle",U({key:We((o=t).key),oracle:He(o.oracle)})),r);var o}const nr=ar;function sr(e,t,r){return Bt(e,It("EditOracleTolerance",U({key:We((o=t).key),tolerance:v(o.tolerance)})),r);var o}function ir(e,t,r){return Bt(e,It("UpgradeGov",E(t.wasmHash)),r)}function lr(e,t,r){return Bt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function ur(e,t,r){return Bt(e,It("GrantGovRole",Et(t)),r)}function cr(e,t,r){return Bt(e,It("RevokeGovRole",Et(t)),r)}function pr(e,t,r){return Bt(e,It("TransferGovOwnership",xt(t)),r)}function dr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=Tt(t.predecessor??Rt);return $t(e,"execute",[x(),y(t.target),I(t.functionName),r,o,Tt(t.salt)])}function mr(e,t,r){return Nt(e,It("UpgradeGov",E(t.wasmHash)),r)}function fr(e,t,r){return Nt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function hr(e,t,r){return Nt(e,It("GrantGovRole",Et(t)),r)}function gr(e,t,r){return Nt(e,It("RevokeGovRole",Et(t)),r)}function wr(e,t,r){return Nt(e,It("TransferGovOwnership",xt(t)),r)}const _r=e=>A(e.map(y));function br(e,t,r){return $t(e,"propose_canceller_reset",[_r(t.newCancellers),Tt(r)])}function yr(e,t,r){return $t(e,"execute_canceller_reset",[$(t.executor,y),_r(t.newCancellers),Tt(r)])}function Sr(e,t){return $t(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function vr(e,t){return $t(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function kr(e){return $t(e,"create_hub",[y(e.caller)])}function Rr(e){return $t(e,"add_spoke",[y(e.caller)])}function Tr(e,t){return $t(e,"revoke_role_immediate",[y(t.account),I(t.role)])}function Ir(e){return $t(e,"pause",[y(e.caller)])}function xr(e,t){return Bt(e,It("Unpause"),t)}const Ar=e=>e.toXDR("base64"),Er=e=>i.ScVal.fromXDR(e,"base64"),$r=e=>e.map((e=>String(s(Er(e))))).join(":"),Br=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Nr=e=>Number(e),Pr=e=>String(e),Or=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],Lr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],qr=e=>Array.isArray(e)?e:[],zr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Lr[Nr(o)]??Br(o)),positionType:t,hubId:Nr(e[1]),asset:Pr(e[2]),scaledAmountRay:Br(e[3]),indexRay:Br(e[4]),amount:Br(e[5]),liquidationThresholdBps:r?void 0:Nr(e[6]),liquidationBonusBps:r?void 0:Nr(e[7]),loanToValueBps:r?void 0:Nr(e[8]),liquidationFeesBps:r?void 0:Nr(e[9])};var o},Wr=e=>{return{owner:Pr(e[0]),spokeId:Nr(e[1]),mode:(t=e[2],Ur[Nr(t)]??"None")};var t},Dr=e=>Array.isArray(e)?e[1]:void 0,Cr=e=>{const t=(r=e,Array.isArray(r)?Pr(r[0]):Pr(r));var r;if("Token"===t)return{Token:Pr(Dr(e))};if("Ref"===t)return{Ref:Pr(Dr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Pr(t.Token)};if(void 0!==t.Ref)return{Ref:Pr(t.Ref)}}return{Token:Pr(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:Nr(e.asset_decimals),maxPriceStaleSeconds:Nr(e.max_price_stale_seconds),sources:qr(e.sources).map((e=>e)),tolerance:{upperRatio:Nr(t.upper_ratio_bps),lowerRatio:Nr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Br(e.min_sanity_price_wad),maxSanityPriceWad:Br(e.max_sanity_price_wad)}},Mr={"market:create":e=>({topic:"market:create",data:{hubId:Nr(e.hub_id),baseAsset:Pr(e.base_asset),maxBorrowRate:Br(e.max_borrow_rate),baseBorrowRate:Br(e.base_borrow_rate),slope1:Br(e.slope1),slope2:Br(e.slope2),slope3:Br(e.slope3),midUtilization:Br(e.mid_utilization),optimalUtilization:Br(e.optimal_utilization),maxUtilization:Br(e.max_utilization),reserveFactor:Nr(e.reserve_factor),marketAddress:Pr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Pr(e.asset),maxBorrowRateRay:Br(e.max_borrow_rate),baseBorrowRateRay:Br(e.base_borrow_rate),slope1Ray:Br(e.slope1),slope2Ray:Br(e.slope2),slope3Ray:Br(e.slope3),midUtilizationRay:Br(e.mid_utilization),optimalUtilizationRay:Br(e.optimal_utilization),maxUtilizationRay:Br(e.max_utilization),reserveFactorBps:Nr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:qr(e).map((e=>{return t=qr(e),{hubId:Nr(t[0]),asset:Pr(t[1]),timestamp:Nr(t[2]),supplyIndexRay:Br(t[3]),borrowIndexRay:Br(t[4]),cash:Br(t[5]),suppliedRay:Br(t[6]),borrowedRay:Br(t[7]),revenueRay:Br(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:qr(e).map((e=>{const t=e;return{hubId:Nr(t.hub_id),asset:Pr(t.asset),params:(r=t.params,{maxBorrowRateRay:Br(r.max_borrow_rate),baseBorrowRateRay:Br(r.base_borrow_rate),slope1Ray:Br(r.slope1),slope2Ray:Br(r.slope2),slope3Ray:Br(r.slope3),midUtilizationRay:Br(r.mid_utilization),optimalUtilizationRay:Br(r.optimal_utilization),maxUtilizationRay:Br(r.max_utilization),reserveFactorBps:Nr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Nr(r.flashloan_fee),assetId:Pr(r.asset_id),assetDecimals:Nr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=qr(e);return{topic:"position:batch_update",data:{accountId:Br(t[0]),accountAttributes:Wr(qr(t[1])),updates:[...qr(t[2]).map((e=>zr(qr(e),"Deposit"))),...qr(t[3]).map((e=>zr(qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),receiver:Pr(e.receiver),caller:Pr(e.caller),amount:Br(e.amount),fee:Br(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Cr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Pr(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Pr(e.liquidator),accountId:Br(e.account_id),repaidUsdWad:Br(e.repaid_usd_wad),bonusBps:Br(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Br(e.account_id),totalBorrowUsdWad:Br(e.total_borrow_usd_wad),totalCollateralUsdWad:Br(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Pr(e.token),amount:Br(e.amount),usdValueWad:Br(e.usd_value_wad),accountId:Br(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),amount:Br(e.amount),fee:Br(e.fee),amountSent:Br(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Pr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Or(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Pr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Pr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Pr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Pr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Or(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Nr(e.max_supply_positions),maxBorrowPositions:Nr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Br(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Pr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Nr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Br(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Br(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Nr(t.liquidation_bonus_factor_bps)}}}},Fr=Object.freeze(Object.keys(Mr));function Gr(e,t){const r=$r(e),o=Mr[r];return o?o(s(Er(t))):null}const Xr="XLENDXLM-a7c9f3",Hr=1e4;function jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Xr}-${r}`}function Jr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Qr(e,t=0){return 1e4*e+t}function Kr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const Zr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Yr=e=>e.baseUrl??d[e.network];async function eo(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Zr(Yr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function to(e){const t=Zr(Yr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ro=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,oo=e=>q(e).toXDR("base64");function ao(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=C(ro(a,t.referralId));return{xdr:new n(l,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",y(t.caller),S(t.totalIn),u)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function no(e,t){return ao(e,t)}function so(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(uo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(uo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function io(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:so(e,t)}const lo=so,uo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function co(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function po(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw co(r.invokedContractId,e);throw e}}async function mo(e,t,r){return po(e,t.xdr,r)}function fo(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function ho(e,t){return new Uint8Array(0)}const go=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function wo(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(go(t.message)),i.ScVal.scvBytes(go(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const _o={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function bo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=_o[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,Rt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Fr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Hr as SYNTHETIC_EVENT_ORDER_STRIDE,Xr as XOXNO_LENDING_STELLAR_TICKER,ho as buildSameTokenRepaySwapSteps,rt as buildStellarAcceptOwnershipTx,vt as buildStellarAddRewardsTx,lt as buildStellarApproveBlendPoolTx,ct as buildStellarApproveTokenTx,no as buildStellarBatchSwapTx,X as buildStellarBorrowBatchTx,H as buildStellarBorrowTx,wo as buildStellarCctpForwardTx,St as buildStellarClaimRevenueTx,bt as buildStellarCreateLiquidityPoolTx,yr as buildStellarExecuteCancellerResetTx,ao as buildStellarExecuteStrategyTx,ee as buildStellarFlashLoanTx,Rr as buildStellarGovernanceAddSpokeImmediateTx,kr as buildStellarGovernanceCreateHubImmediateTx,mr as buildStellarGovernanceExecuteGovernanceUpgradeTx,hr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,gr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,wr as buildStellarGovernanceExecuteTransferGovOwnTx,dr as buildStellarGovernanceExecuteTx,fr as buildStellarGovernanceExecuteUpdateDelayTx,Ir as buildStellarGovernancePauseTx,Tr as buildStellarGovernanceRevokeRoleImmediateTx,vr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,Sr as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ye as buildStellarGrantRoleTx,jr as buildStellarLendingIdentifier,Z as buildStellarLiquidateTx,te as buildStellarMigrateFromBlendTx,Qe as buildStellarMigrateTx,re as buildStellarMultiplyTx,Ke as buildStellarPauseTx,Ct as buildStellarProposeAddAssetToSpokeTx,Wt as buildStellarProposeAddSpokeTx,Jt as buildStellarProposeApproveBlendPoolTx,Ht as buildStellarProposeApproveTokenTx,br as buildStellarProposeCancellerResetTx,ar as buildStellarProposeConfigureAssetOracleTx,nr as buildStellarProposeConfigureMarketOracleTx,zt as buildStellarProposeCreateHubTx,Kt as buildStellarProposeCreateLiquidityPoolTx,Yt as buildStellarProposeDeployPoolTx,Vt as buildStellarProposeEditAssetInSpokeTx,sr as buildStellarProposeEditOracleToleranceTx,ir as buildStellarProposeGovernanceUpgradeTx,ur as buildStellarProposeGrantGovernanceRoleTx,rr as buildStellarProposeMigrateControllerTx,Mt as buildStellarProposeRemoveAssetFromSpokeTx,Dt as buildStellarProposeRemoveSpokeTx,Qt as buildStellarProposeRevokeBlendPoolTx,cr as buildStellarProposeRevokeGovernanceRoleTx,jt as buildStellarProposeRevokeTokenTx,Lt as buildStellarProposeSetAccumulatorTx,Ut as buildStellarProposeSetAggregatorTx,Xt as buildStellarProposeSetMinBorrowCollatTx,qt as buildStellarProposeSetPositionLimitsTx,Gt as buildStellarProposeSetPositionManagerTx,Ot as buildStellarProposeSetPriceAggregatorTx,Ft as buildStellarProposeSetSpokeLiquidationCurveTx,Pt as buildStellarProposeSetSwapAggregatorTx,or as buildStellarProposeTransferCtrlOwnershipTx,pr as buildStellarProposeTransferGovOwnTx,xr as buildStellarProposeUnpauseTx,lr as buildStellarProposeUpdateDelayTx,tr as buildStellarProposeUpgradeControllerTx,Zt as buildStellarProposeUpgradePoolParamsTx,er as buildStellarProposeUpgradePoolTx,_t as buildStellarRenewAccountTx,Q as buildStellarRepayBatchTx,ne as buildStellarRepayDebtWithCollateralTx,K as buildStellarRepayTx,ut as buildStellarRevokeBlendPoolTx,et as buildStellarRevokeRoleTx,pt as buildStellarRevokeTokenTx,st as buildStellarSetAccumulatorTx,nt as buildStellarSetAggregatorTx,mt as buildStellarSetMarketOracleConfigTx,gt as buildStellarSetOracleSanityBoundsTx,ft as buildStellarSetOracleToleranceTx,dt as buildStellarSetOracleTx,it as buildStellarSetPositionLimitsTx,at as buildStellarSetPriceAggregatorTx,ht as buildStellarSetSpokeAssetFlagsTx,ot as buildStellarSetSwapAggregatorTx,F as buildStellarSupplyBatchTx,G as buildStellarSupplyTx,ae as buildStellarSwapCollateralTx,oe as buildStellarSwapDebtTx,tt as buildStellarTransferOwnershipTx,Ze as buildStellarUnpauseTx,kt as buildStellarUpdateAccountThresholdTx,wt as buildStellarUpdateIndexesTx,Je as buildStellarUpgradeControllerTx,yt as buildStellarUpgradeLiquidityPoolParamsTx,j as buildStellarWithdrawBatchTx,J as buildStellarWithdrawTx,M as buildTx,Gr as decodeStellarLendingEvent,Y as decodeStellarLiquidateReturn,He as encodeAssetOracle,Le as encodeInterestRateModel,je as encodeMarketOracleConfigInput,qe as encodeMarketParamsRaw,ze as encodePositionLimits,We as encodePriceKey,oo as encodeStrategyPayloadToRouteXdr,Jr as extractEventOrder,Pe as getStellarAccountDelegates,Re as getStellarAccountPositions,eo as getStellarAggregatorQuote,h as getStellarAggregatorRouter,we as getStellarAsset,Ie as getStellarAssetGraph,be as getStellarAssetMarkets,_e as getStellarAssetPage,pe as getStellarAssets,Oe as getStellarBlendPools,Be as getStellarContractConfig,Ne as getStellarContractRoles,g as getStellarGovernance,Te as getStellarGovernanceProposals,ye as getStellarHub,xe as getStellarHubGraph,de as getStellarHubs,ue as getStellarLendingContext,f as getStellarLendingController,ce as getStellarLendingLiveState,$e as getStellarProtocolConfig,to as getStellarQuoteTokens,he as getStellarReserve,Ee as getStellarReserveGraph,ge as getStellarReserveHolders,fe as getStellarReserves,Se as getStellarSpoke,Ae as getStellarSpokeGraph,me as getStellarSpokes,ke as getStellarUserActivity,ve as getStellarUserPositions,lo as mapQuoteResponseToAggregatorSwap,so as mapQuoteResponseToStrategyPayload,io as mapQuoteResponseToStrategySwap,bo as mapSorobanError,Kr as mapStellarPositionActivityType,mo as prepareStellarBuiltTx,po as prepareStellarTxXdr,$r as stellarLendingDispatchKey,Ue as stellarLendingRead,Qr as syntheticEventOrder,co as tagStellarInvokedContractError,Ar as toBase64Xdr,fo as toStellarPositionMode};
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { xdr } from '@stellar/stellar-sdk';
19
19
  import { type StellarNetwork } from './contracts';
20
- import { type StellarStrategySwapHopInput, type StellarStrategySwapInput, type StellarStrategySwapPathInput } from './scval-encode';
20
+ import { type StellarSeizeModeInput, type StellarStrategySwapHopInput, type StellarStrategySwapInput, type StellarStrategySwapPathInput } from './scval-encode';
21
21
  /**
22
22
  * Stellar `G...` public key of the caller (tx source account).
23
23
  */
@@ -68,7 +68,7 @@ export interface BuiltStellarTx {
68
68
  export type StellarSwapStepsInput = StellarStrategySwapInput;
69
69
  export type StellarSwapHopInput = StellarStrategySwapHopInput;
70
70
  export type StellarSwapPathInput = StellarStrategySwapPathInput;
71
- export type { StellarSwapVenue } from './scval-encode';
71
+ export type { StellarSeizeModeInput, StellarSwapVenue } from './scval-encode';
72
72
  /**
73
73
  * Assemble an unsigned XDR that invokes a single Soroban contract method.
74
74
  *
@@ -133,6 +133,13 @@ export interface StellarRepayBatchArgs {
133
133
  export interface StellarLiquidateArgs {
134
134
  accountNonce: number;
135
135
  debtPayments: ReadonlyArray<StellarHubAssetAmount>;
136
+ /**
137
+ * How the liquidator takes delivery of the seized collateral. Defaults to
138
+ * `'Transfer'` — the pool pays out underlying tokens, which is the only
139
+ * behaviour the pre-`SeizeMode` ABI had. `{ Credit: 0 }` opens a fresh
140
+ * receiving account; `{ Credit: id }` credits an existing one.
141
+ */
142
+ seizeMode?: StellarSeizeModeInput;
136
143
  }
137
144
  export interface StellarFlashLoanArgs extends StellarHubAsset {
138
145
  amount: string;
@@ -219,9 +226,25 @@ export declare function buildStellarRepayBatchTx(opts: StellarBuilderOptions, ar
219
226
  /** Single-asset `repay`. */
220
227
  export declare function buildStellarRepayTx(opts: StellarBuilderOptions, args: StellarRepayArgs): BuiltStellarTx;
221
228
  /**
222
- * liquidate(liquidator, account_id: u64, debt_payments: Vec<(HubAssetKey, i128)>)
229
+ * liquidate(liquidator, account_id: u64, debt_payments: Vec<(HubAssetKey, i128)>,
230
+ * seize_mode: SeizeMode) -> u64
231
+ *
232
+ * The `u64` return is the account credited with the seized supply shares under
233
+ * `SeizeMode::Credit` (freshly opened when `Credit(0)` was passed), and `0`
234
+ * under `SeizeMode::Transfer`. Read it from the simulation / tx result with
235
+ * `decodeStellarLiquidateReturn`.
223
236
  */
224
237
  export declare function buildStellarLiquidateTx(opts: StellarBuilderOptions, args: StellarLiquidateArgs): BuiltStellarTx;
238
+ /**
239
+ * Decode `liquidate`'s `u64` return value from its base64 XDR — the receiving
240
+ * account id, as a decimal string. `'0'` means `SeizeMode::Transfer` (the
241
+ * liquidator was paid in underlying tokens, no account was touched).
242
+ *
243
+ * Takes base64 XDR (as Soroban RPC delivers `returnValue` / `result.retval`)
244
+ * so no live `xdr.ScVal` crosses the consumer boundary — same contract as
245
+ * `decodeStellarLendingEvent`. Hold a parsed ScVal? Pass `toBase64Xdr(scv)`.
246
+ */
247
+ export declare function decodeStellarLiquidateReturn(returnValueB64: string): string;
225
248
  /**
226
249
  * flash_loan(caller, asset: HubAssetKey, amount: i128, receiver, data: Bytes)
227
250
  */
@@ -118,6 +118,28 @@ export declare const tupleHubAssetAmountVec: (entries: Array<{
118
118
  asset: string;
119
119
  amount: string;
120
120
  }>) => xdr.ScVal;
121
+ /**
122
+ * How a liquidator takes delivery of seized collateral — the Soroban
123
+ * `SeizeMode` enum.
124
+ *
125
+ * - `'Transfer'` — the pool withdraws the collateral and pays the liquidator
126
+ * in underlying tokens, withholding the protocol fee from the transfer.
127
+ * - `{ Credit: accountId }` — the seized *supply shares* are credited to a
128
+ * controller account instead. `0` opens a fresh account owned by the
129
+ * liquidator and bound to the liquidated account's spoke; any other id must
130
+ * already exist, be owned by (or delegated to) the liquidator, sit in the
131
+ * same spoke, and be in `PositionMode::Normal`.
132
+ */
133
+ export type StellarSeizeModeInput = 'Transfer' | {
134
+ Credit: number | string;
135
+ };
136
+ /**
137
+ * Encode `SeizeMode`. Soroban serializes a `#[contracttype]` enum as
138
+ * `scvVec([scvSymbol(Variant), ...payload])` — the void variant carries only
139
+ * the symbol, `Credit` appends its `u64`. Same shape as `OracleReadMode`
140
+ * (`Spot` / `Twap(u32)`) in `admin.ts`.
141
+ */
142
+ export declare const seizeMode: (mode: StellarSeizeModeInput) => xdr.ScVal;
121
143
  /**
122
144
  * Encode a Soroban `struct` — at the XDR level, structs are maps with
123
145
  * `Symbol` keys in **lexicographic order** of field names.
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xoxno/sdk-js",
3
- "version": "1.0.205",
3
+ "version": "1.0.207",
4
4
  "description": "The SDK to interact with the XOXNO Protocol!",
5
5
  "type": "module",
6
6
  "exports": {
@@ -114,7 +114,7 @@
114
114
  "dependencies": {
115
115
  "@multiversx/sdk-core": "^15.3.2",
116
116
  "@multiversx/sdk-network-providers": "^2.9.3",
117
- "@xoxno/types": "1.0.484"
117
+ "@xoxno/types": "1.0.485"
118
118
  },
119
119
  "peerDependencies": {
120
120
  "@stellar/stellar-sdk": ">=15.0.0 <17.0.0"