@xoxno/sdk-js 1.0.201 → 1.0.202

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:()=>ct,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>Ur,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>qr,XOXNO_LENDING_STELLAR_TICKER:()=>Gr,buildSameTokenRepaySwapSteps:()=>so,buildStellarAcceptOwnershipTx:()=>Me,buildStellarAddRewardsTx:()=>lt,buildStellarApproveBlendPoolTx:()=>je,buildStellarApproveTokenTx:()=>Je,buildStellarBatchSwapTx:()=>Kr,buildStellarBorrowBatchTx:()=>G,buildStellarBorrowTx:()=>q,buildStellarCctpForwardTx:()=>lo,buildStellarClaimRevenueTx:()=>it,buildStellarCreateLiquidityPoolTx:()=>nt,buildStellarExecuteCancellerResetTx:()=>pr,buildStellarExecuteStrategyTx:()=>Jr,buildStellarFlashLoanTx:()=>F,buildStellarGovernanceAddSpokeImmediateTx:()=>br,buildStellarGovernanceCreateHubImmediateTx:()=>Sr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>nr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>ir,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>lr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>ur,buildStellarGovernanceExecuteTx:()=>ar,buildStellarGovernanceExecuteUpdateDelayTx:()=>sr,buildStellarGovernancePauseTx:()=>hr,buildStellarGovernanceRevokeRoleImmediateTx:()=>gr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>fr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>mr,buildStellarGrantRoleTx:()=>qe,buildStellarLendingIdentifier:()=>Dr,buildStellarLiquidateTx:()=>z,buildStellarMigrateFromBlendTx:()=>X,buildStellarMigrateTx:()=>Ue,buildStellarMultiplyTx:()=>H,buildStellarPauseTx:()=>Ce,buildStellarProposeAddAssetToSpokeTx:()=>Nt,buildStellarProposeAddSpokeTx:()=>Ot,buildStellarProposeApproveBlendPoolTx:()=>Wt,buildStellarProposeApproveTokenTx:()=>qt,buildStellarProposeCancellerResetTx:()=>dr,buildStellarProposeConfigureAssetOracleTx:()=>Jt,buildStellarProposeConfigureMarketOracleTx:()=>Kt,buildStellarProposeCreateHubTx:()=>Pt,buildStellarProposeCreateLiquidityPoolTx:()=>Vt,buildStellarProposeDeployPoolTx:()=>Ft,buildStellarProposeEditAssetInSpokeTx:()=>Lt,buildStellarProposeEditOracleToleranceTx:()=>Zt,buildStellarProposeGovernanceUpgradeTx:()=>Yt,buildStellarProposeGrantGovernanceRoleTx:()=>tr,buildStellarProposeMigrateControllerTx:()=>jt,buildStellarProposeRemoveAssetFromSpokeTx:()=>$t,buildStellarProposeRemoveSpokeTx:()=>Bt,buildStellarProposeRevokeBlendPoolTx:()=>Mt,buildStellarProposeRevokeGovernanceRoleTx:()=>rr,buildStellarProposeRevokeTokenTx:()=>Dt,buildStellarProposeSetAccumulatorTx:()=>Et,buildStellarProposeSetAggregatorTx:()=>At,buildStellarProposeSetMinBorrowCollatTx:()=>Gt,buildStellarProposeSetPositionLimitsTx:()=>It,buildStellarProposeSetPositionManagerTx:()=>Ct,buildStellarProposeSetPriceAggregatorTx:()=>Rt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>Ut,buildStellarProposeSetSwapAggregatorTx:()=>kt,buildStellarProposeTransferCtrlOwnershipTx:()=>Qt,buildStellarProposeTransferGovOwnTx:()=>or,buildStellarProposeUnpauseTx:()=>_r,buildStellarProposeUpdateDelayTx:()=>er,buildStellarProposeUpgradeControllerTx:()=>Ht,buildStellarProposeUpgradePoolParamsTx:()=>zt,buildStellarProposeUpgradePoolTx:()=>Xt,buildStellarRenewAccountTx:()=>at,buildStellarRepayBatchTx:()=>M,buildStellarRepayDebtWithCollateralTx:()=>J,buildStellarRepayTx:()=>V,buildStellarRevokeBlendPoolTx:()=>Qe,buildStellarRevokeRoleTx:()=>De,buildStellarRevokeTokenTx:()=>Ke,buildStellarSetAccumulatorTx:()=>Xe,buildStellarSetAggregatorTx:()=>Fe,buildStellarSetMarketOracleConfigTx:()=>Ye,buildStellarSetOracleSanityBoundsTx:()=>rt,buildStellarSetOracleToleranceTx:()=>et,buildStellarSetOracleTx:()=>Ze,buildStellarSetPositionLimitsTx:()=>He,buildStellarSetPriceAggregatorTx:()=>ze,buildStellarSetSpokeAssetFlagsTx:()=>tt,buildStellarSetSwapAggregatorTx:()=>Ve,buildStellarSupplyBatchTx:()=>U,buildStellarSupplyTx:()=>C,buildStellarSwapCollateralTx:()=>Q,buildStellarSwapDebtTx:()=>j,buildStellarTransferOwnershipTx:()=>We,buildStellarUnpauseTx:()=>Ge,buildStellarUpdateAccountThresholdTx:()=>ut,buildStellarUpdateIndexesTx:()=>ot,buildStellarUpgradeControllerTx:()=>$e,buildStellarUpgradeLiquidityPoolParamsTx:()=>st,buildStellarWithdrawBatchTx:()=>D,buildStellarWithdrawTx:()=>W,buildTx:()=>$,decodeStellarLendingEvent:()=>Cr,encodeAssetOracle:()=>Ne,encodeInterestRateModel:()=>ye,encodeMarketOracleConfigInput:()=>Le,encodeMarketParamsRaw:()=>xe,encodePositionLimits:()=>ve,encodePriceKey:()=>ke,encodeStrategyPayloadToRouteXdr:()=>Qr,extractEventOrder:()=>Wr,getStellarAccountPositions:()=>Se,getStellarAggregatorQuote:()=>Xr,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>le,getStellarAssetGraph:()=>ge,getStellarAssetMarkets:()=>ce,getStellarAssetPage:()=>ue,getStellarAssets:()=>re,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>be,getStellarHub:()=>de,getStellarHubGraph:()=>he,getStellarHubs:()=>oe,getStellarLendingContext:()=>ee,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>te,getStellarQuoteTokens:()=>Hr,getStellarReserve:()=>se,getStellarReserveGraph:()=>we,getStellarReserveHolders:()=>ie,getStellarReserves:()=>ne,getStellarSpoke:()=>pe,getStellarSpokeGraph:()=>_e,getStellarSpokes:()=>ae,getStellarUserActivity:()=>fe,getStellarUserPositions:()=>me,mapQuoteResponseToAggregatorSwap:()=>eo,mapQuoteResponseToStrategyPayload:()=>Zr,mapQuoteResponseToStrategySwap:()=>Yr,mapSorobanError:()=>co,mapStellarPositionActivityType:()=>Vr,prepareStellarBuiltTx:()=>ao,prepareStellarTxXdr:()=>oo,stellarLendingDispatchKey:()=>yr,stellarLendingRead:()=>Te,syntheticEventOrder:()=>Mr,tagStellarInvokedContractError:()=>ro,toBase64Xdr:()=>wr,toStellarPositionMode:()=>no});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=e=>new d.Address(e).toScVal(),f=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(),g=e=>d.xdr.ScVal.scvBool(e),h=e=>d.xdr.ScVal.scvString(e),_=e=>d.xdr.ScVal.scvSymbol(e),w=()=>d.xdr.ScVal.scvVoid(),T=e=>d.xdr.ScVal.scvVec(e),y=(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)},x=(e,t)=>null==e?w():t(e),v=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([m(t),f(r)]);var t,r}))),k=(e,t)=>E({asset:m(t),hub_id:S(e)}),R=(e,t,r)=>d.xdr.ScVal.scvVec([k(e,t),f(r)]),A=e=>d.xdr.ScVal.scvVec(e.map((e=>R(e.hubId,e.asset,e.amount)))),E=e=>{const t=Object.keys(e).sort().map((t=>new d.xdr.ScMapEntry({key:_(t),val:e[t]})));return d.xdr.ScVal.scvMap(t)},I=e=>{const t=e.paths.map((e=>{const t=e.hops.map((e=>{return E({amount_out:f(e.amountOut),pool:m(e.pool),token_in:m(e.tokenIn),token_out:m(e.tokenOut),venue:(t=e.venue,d.xdr.ScVal.scvVec([_(t)]))});var t}));return E({hops:d.xdr.ScVal.scvVec(t),split_ppm:S(e.splitPpm)})}));return E({paths:d.xdr.ScVal.scvVec(t),referral_id:b(e.referralId??0),token_in:m(e.tokenIn),token_out:m(e.tokenOut),total_min_out:f(e.totalMinOut)})},P=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)},O=()=>d.xdr.ScVal.scvBytes(Buffer.alloc(0)),B=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},N=e=>{if("string"==typeof e)return P(B(e));if(e instanceof Uint8Array)return 0===e.length?O():P(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?P(B(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?P(B(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?P(B(e.bytes)):0===e.bytes.length?O():P(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");let r=0;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`);r+=o.splitPpm;for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.amountOut||"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 amountOut, pool, tokenIn, tokenOut, and a valid Soroban venue`)}if(1e6!==r)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` must sum to 1_000_000, got ${r}`);return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(I(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},L=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 $(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 U(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return $(e,"supply",[m(e.caller),b(r),S(o),A([...t.assets])])}function C(e,t){return U(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function G(e,t){return $(e,"borrow",[m(e.caller),b(t.accountNonce),A([...t.borrows]),x(t.to,m)])}function q(e,t){return G(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function D(e,t){return $(e,"withdraw",[m(e.caller),b(t.accountNonce),A([...t.withdrawals]),x(t.to,m)])}function W(e,t){return D(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function M(e,t){return $(e,"repay",[m(e.caller),b(t.accountNonce),A([...t.payments])])}function V(e,t){return M(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function z(e,t){return $(e,"liquidate",[m(e.caller),b(t.accountNonce),A([...t.debtPayments])])}function F(e,t){return $(e,"flash_loan",[m(e.caller),k(t.hubId,t.asset),f(t.amount),m(t.receiver),L(t.data)])}function X(e,t){return $(e,"migrate_from_blend",[m(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),m(t.blendPool),T(t.collateralTokens.map(m)),T(t.supplyTokens.map(m)),v(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function H(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return $(e,"multiply",[m(e.caller),b(r),S(o),k(t.collateral.hubId,t.collateral.asset),f(t.debtToFlashLoan),k(t.debt.hubId,t.debt.asset),S(t.mode),N(t.steps),x(t.initialPayment,(e=>R(e.hubId,e.asset,e.amount))),x(t.convertSwap,N)])}function j(e,t){return $(e,"swap_debt",[m(e.caller),b(t.accountNonce),k(t.existingDebt.hubId,t.existingDebt.asset),f(t.newDebtAmount),k(t.newDebt.hubId,t.newDebt.asset),N(t.steps)])}function Q(e,t){return $(e,"swap_collateral",[m(e.caller),b(t.accountNonce),k(t.current.hubId,t.current.asset),f(t.fromAmount),k(t.newCollateral.hubId,t.newCollateral.asset),N(t.steps)])}function J(e,t){return $(e,"repay_debt_with_collateral",[m(e.caller),b(t.accountNonce),k(t.collateral.hubId,t.collateral.asset),f(t.collateralAmount),k(t.debt.hubId,t.debt.asset),N(t.steps),g(t.closePosition)])}const K="/stellar-lending",Z=25,Y=encodeURIComponent,ee=(e,t)=>e.fetchWithTimeout(`${K}/context`,t),te=(e,t)=>e.fetchWithTimeout(`${K}/live-state`,t),re=(e,t)=>e.fetchWithTimeout(`${K}/assets`,t),oe=(e,t)=>e.fetchWithTimeout(`${K}/hubs`,t),ae=(e,t)=>e.fetchWithTimeout(`${K}/spokes`,t),ne=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${K}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},se=(e,t,r,o,a)=>e.fetchWithTimeout(`${K}/reserves/${t}/${r}/${Y(o)}`,a),ie=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${K}/reserves/${t}/${r}/${Y(o)}/holders`,{...n,params:{side:a}}),le=(e,t,r)=>e.fetchWithTimeout(`${K}/assets/${Y(t)}`,r),ue=(e,t,r,o)=>e.fetchWithTimeout(`${K}/assets/${Y(t)}/page`,{...o,params:{...r}}),ce=(e,t,r,o)=>e.fetchWithTimeout(`${K}/assets/${Y(t)}/markets`,{...o,params:{side:r}}),de=(e,t,r)=>e.fetchWithTimeout(`${K}/hubs/${t}`,r),pe=(e,t,r)=>e.fetchWithTimeout(`${K}/spokes/${t}`,r),me=(e,t,r)=>e.fetchWithTimeout(`${K}/users/${Y(t)}/positions`,r),fe=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${K}/users/${Y(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},Se=(e,t,r)=>e.fetchWithTimeout(`${K}/accounts/${Y(t)}/positions`,r),be=(e,t={},r)=>{const{top:o=Z,continuationToken:a}=t;return e.fetchWithTimeout(`${K}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},ge=(e,t,r,o)=>e.fetchWithTimeout(`${K}/assets/${Y(t)}/graph`,{...o,params:{...r}}),he=(e,t,r,o)=>e.fetchWithTimeout(`${K}/hubs/${t}/graph`,{...o,params:{...r}}),_e=(e,t,r,o)=>e.fetchWithTimeout(`${K}/spokes/${t}/graph`,{...o,params:{...r}}),we=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${K}/reserves/${t}/${r}/${Y(o)}/graph`,{...n,params:{...a}}),Te=e=>({context:t=>ee(e,t),liveState:t=>te(e,t),assets:t=>re(e,t),hubs:t=>oe(e,t),spokes:t=>ae(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?ne(e,t,r):ne(e,{},t);var o},reserve:(t,r,o,a)=>se(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ie(e,t,r,o,a,n),asset:(t,r)=>le(e,t,r),assetMarkets:(t,r,o)=>ce(e,t,r,o),hub:(t,r)=>de(e,t,r),spoke:(t,r)=>pe(e,t,r),userPositions:(t,r)=>me(e,t,r),userActivity:(t,r,o)=>fe(e,t,r,o),accountPositions:(t,r)=>Se(e,t,r),governanceProposals:(t,r)=>be(e,t,r),assetGraph:(t,r,o)=>ge(e,t,r,o),hubGraph:(t,r,o)=>he(e,t,r,o),spokeGraph:(t,r,o)=>_e(e,t,r,o),reserveGraph:(t,r,o,a,n)=>we(e,t,r,o,a,n)}),ye=e=>E({base_borrow_rate:f(e.baseBorrowRateRay),max_borrow_rate:f(e.maxBorrowRateRay),max_utilization:f(e.maxUtilizationRay),mid_utilization:f(e.midUtilizationRay),optimal_utilization:f(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:f(e.slope1Ray),slope2:f(e.slope2Ray),slope3:f(e.slope3Ray)}),xe=e=>E({asset_decimals:S(e.assetDecimals),asset_id:m(e.assetId),base_borrow_rate:f(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:g(e.isFlashloanable),max_borrow_rate:f(e.maxBorrowRateRay),max_utilization:f(e.maxUtilizationRay),mid_utilization:f(e.midUtilizationRay),optimal_utilization:f(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:f(e.slope1Ray),slope2:f(e.slope2Ray),slope3:f(e.slope3Ray)}),ve=e=>E({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),ke=e=>{if("Token"in e&&e.Token)return T([_("Token"),m(e.Token)]);if("Ref"in e&&e.Ref)return T([_("Ref"),_(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Re=e=>{if("Stellar"in e)return T([_("Stellar"),m(e.Stellar)]);if("Symbol"in e)return T([_("Symbol"),_(e.Symbol)]);if("String"in e)return T([_("String"),h(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ae=e=>{if("Spot"===e)return T([_("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return T([_("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ee=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return T([_(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ie=e=>{if("Market"===e||"Fundamental"===e)return T([_(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Pe=e=>{if("Reflector"in e){const t=e.Reflector;return T([_("Reflector"),E({asset:Re(t.asset),contract:m(t.contract),read_mode:Ae(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return T([_("MultiFeed"),E({contract:m(t.contract),feed_id:h(t.feedId),kind:Ee(t.kind),nature:Ie(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Oe=e=>{const t=e;return E({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:Pe(t.provider)})},Be=e=>{if("RequireDisjoint"===e)return T([_("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return T([_("AllowShared"),T(t.map((e=>E({contract:m(e.contract),kind:Ee(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},Ne=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 E({asset_decimals:S(Number(t.assetDecimals)),independence:Be(t.independence),max_price_stale_seconds:b(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:f(String(t.maxSanityPriceWad)),min_sanity_price_wad:f(String(t.minSanityPriceWad)),sources:T(r.map((e=>(e=>{if("Feed"in e)return T([_("Feed"),Oe(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return T([_("Scaled"),E({factor:Oe(t.factor),max_factor_wad:f(t.maxFactorWad),min_factor_wad:f(t.minFactorWad),quote:ke(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return T([_("LpShare"),E({key_a:ke(t.keyA),key_b:ke(t.keyB),kind:T([_(t.kind||"ConstantProduct")]),pool:m(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:E({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Le=Ne;function $e(e,t){return $(e,"upgrade",[y(t.wasmHash)])}function Ue(e,t){return $(e,"migrate",[S(t.newVersion)])}function Ce(e){return $(e,"pause",[])}function Ge(e){return $(e,"unpause",[])}function qe(e,t){return $(e,"grant_role",[m(t.account),_(t.role)])}function De(e,t){return $(e,"revoke_role",[m(t.account),_(t.role)])}function We(e,t){return $(e,"transfer_ownership",[m(t.newOwner),S(t.liveUntilLedger)])}function Me(e){return $(e,"accept_ownership",[])}function Ve(e,t){return $(e,"set_swap_aggregator",[m(t.aggregator)])}function ze(e,t){return $(e,"set_price_aggregator",[m(t.aggregator)])}const Fe=Ve;function Xe(e,t){return $(e,"set_accumulator",[m(t.accumulator)])}function He(e,t){return $(e,"set_position_limits",[ve(t)])}function je(e,t){return $(e,"approve_blend_pool",[m(t.pool)])}function Qe(e,t){return $(e,"revoke_blend_pool",[m(t.pool)])}const Je=je,Ke=Qe;function Ze(e,t){return $(e,"set_oracle",[ke(t.key),Ne(t.oracle)])}const Ye=Ze;function et(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return $(e,"set_tolerance",[ke(t.key),E({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function tt(e,t){return $(e,"set_spoke_asset_flags",[S(t.spokeId),k(t.hubId,t.asset),g(t.paused),g(t.frozen)])}function rt(e,t){return $(e,"set_oracle_sanity_bounds",[m(t.asset),f(t.minPriceWad),f(t.maxPriceWad)])}function ot(e,t){return $(e,"update_indexes",[m(e.caller),T(t.assets.map((e=>k(e.hubId,e.asset))))])}function at(e,t){return $(e,"renew_account",[m(e.caller),b(t.accountNonce)])}function nt(e,t){return $(e,"create_liquidity_pool",[S(t.hubId),m(t.asset),xe(t.params)])}function st(e,t){return $(e,"upgrade_liquidity_pool_params",[k(t.hubId,t.asset),ye(t.params)])}function it(e,t){return $(e,"claim_revenue",[m(e.caller),T(t.assets.map((e=>k(e.hubId,e.asset))))])}function lt(e,t){return $(e,"add_rewards",[m(e.caller),A(t.rewards)])}function ut(e,t){return $(e,"update_account_threshold",[m(e.caller),g(t.hasRisks),T(t.accountNonces.map((e=>b(e))))])}const ct="00".repeat(32),dt=e=>{if("string"==typeof e)return y(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)},pt=(e,...t)=>T([_(e),...t]),mt=e=>E({asset:m(e.asset),hub_id:S(e.hubId),params:xe(e.params)}),ft=e=>E({hub_asset:k(e.hubId,e.asset),params:ye(e.params)}),St=e=>E({new_owner:m(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),bt=e=>E({key:ke(e.key),oracle:Ne(e.oracle)}),gt=e=>E({asset:m(e.asset),bonus:S(e.bonus),borrow_cap:f(e.borrowCap),can_borrow:g(e.canBorrow),can_collateral:g(e.canCollateral),frozen:g(e.frozen),hub_id:S(e.hubId),paused:g(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),oracle_override:T([_("None")]),spoke_id:S(e.spokeId),supply_cap:f(e.supplyCap),threshold:S(e.threshold)}),ht=e=>E({hub_asset:k(e.hubId,e.asset),spoke_id:S(e.spokeId)}),_t=e=>E({hf_for_max_bonus_wad:f(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:f(e.targetHfWad)}),wt=e=>E({key:ke(e.key),tolerance:S(e.tolerance)}),Tt=e=>E({account:m(e.account),role:_(e.role)});function yt(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 xt=(e,t,r)=>yt(e,"propose",[m(e.caller),t,dt(r)]),vt=(e,t,r)=>yt(e,"execute_self",[w(),t,dt(r)]);function kt(e,t,r){return xt(e,pt("SetSwapAggregator",m(t.aggregator)),r)}function Rt(e,t,r){return xt(e,pt("SetPriceAggregator",m(t.aggregator)),r)}const At=kt;function Et(e,t,r){return xt(e,pt("SetAccumulator",m(t.accumulator)),r)}function It(e,t,r){return xt(e,pt("SetPositionLimits",ve(t)),r)}function Pt(e,t){return xt(e,pt("CreateHub"),t)}function Ot(e,t){return xt(e,pt("AddSpoke"),t)}function Bt(e,t,r){return xt(e,pt("RemoveSpoke",S(t.spokeId)),r)}function Nt(e,t,r){return xt(e,pt("AddAssetToSpoke",gt(t)),r)}function Lt(e,t,r){return xt(e,pt("EditAssetInSpoke",gt(t)),r)}function $t(e,t,r){return xt(e,pt("RemoveAssetFromSpoke",ht(t)),r)}function Ut(e,t,r){return xt(e,pt("SetSpokeLiquidationCurve",_t(t)),r)}function Ct(e,t,r){return xt(e,pt("SetPositionManager",m(t.manager),g(t.isActive)),r)}function Gt(e,t,r){return xt(e,pt("SetMinBorrowCollateralUsd",f(t.floorWad)),r)}function qt(e,t,r){return xt(e,pt("ApproveToken",m(t.token)),r)}function Dt(e,t,r){return xt(e,pt("RevokeToken",m(t.token)),r)}function Wt(e,t,r){return xt(e,pt("ApproveBlendPool",m(t.pool)),r)}function Mt(e,t,r){return xt(e,pt("RevokeBlendPool",m(t.pool)),r)}function Vt(e,t,r){return xt(e,pt("CreateLiquidityPool",mt(t)),r)}function zt(e,t,r){return xt(e,pt("UpgradeLiquidityPoolParams",ft(t)),r)}function Ft(e,t,r){return xt(e,pt("DeployPool",y(t.wasmHash)),r)}function Xt(e,t,r){return xt(e,pt("UpgradePool",y(t.wasmHash)),r)}function Ht(e,t,r){return xt(e,pt("UpgradeController",y(t.wasmHash)),r)}function jt(e,t,r){return xt(e,pt("MigrateController",S(t.newVersion)),r)}function Qt(e,t,r){return xt(e,pt("TransferCtrlOwnership",St(t)),r)}function Jt(e,t,r){return xt(e,pt("ConfigureAssetOracle",bt(t)),r)}const Kt=Jt;function Zt(e,t,r){return xt(e,pt("EditOracleTolerance",wt(t)),r)}function Yt(e,t,r){return xt(e,pt("UpgradeGov",y(t.wasmHash)),r)}function er(e,t,r){return xt(e,pt("UpdateGovDelay",S(t.newDelay)),r)}function tr(e,t,r){return xt(e,pt("GrantGovRole",Tt(t)),r)}function rr(e,t,r){return xt(e,pt("RevokeGovRole",Tt(t)),r)}function or(e,t,r){return xt(e,pt("TransferGovOwnership",St(t)),r)}function ar(e,t){const r=T(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=dt(t.predecessor??ct);return yt(e,"execute",[w(),m(t.target),_(t.functionName),r,o,dt(t.salt)])}function nr(e,t,r){return vt(e,pt("UpgradeGov",y(t.wasmHash)),r)}function sr(e,t,r){return vt(e,pt("UpdateGovDelay",S(t.newDelay)),r)}function ir(e,t,r){return vt(e,pt("GrantGovRole",Tt(t)),r)}function lr(e,t,r){return vt(e,pt("RevokeGovRole",Tt(t)),r)}function ur(e,t,r){return vt(e,pt("TransferGovOwnership",St(t)),r)}const cr=e=>T(e.map(m));function dr(e,t,r){return yt(e,"propose_canceller_reset",[cr(t.newCancellers),dt(r)])}function pr(e,t,r){return yt(e,"execute_canceller_reset",[x(t.executor,m),cr(t.newCancellers),dt(r)])}function mr(e,t){return yt(e,"set_spoke_asset_flags",[m(e.caller),S(t.spokeId),k(t.hubId,t.asset),g(t.paused),g(t.frozen)])}function fr(e,t){return yt(e,"set_oracle_sanity_bounds",[m(e.caller),m(t.asset),f(t.minPriceWad),f(t.maxPriceWad)])}function Sr(e){return yt(e,"create_hub",[m(e.caller)])}function br(e){return yt(e,"add_spoke",[m(e.caller)])}function gr(e,t){return yt(e,"revoke_role_immediate",[m(t.account),_(t.role)])}function hr(e){return yt(e,"pause",[m(e.caller)])}function _r(e,t){return xt(e,pt("Unpause"),t)}const wr=e=>e.toXDR("base64"),Tr=e=>d.xdr.ScVal.fromXDR(e,"base64"),yr=e=>e.map((e=>String((0,d.scValToNative)(Tr(e))))).join(":"),xr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),vr=e=>Number(e),kr=e=>String(e),Rr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ar=["None","Multiply","Long","Short"],Er=["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"],Ir=e=>Array.isArray(e)?e:[],Pr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Er[vr(o)]??xr(o)),positionType:t,hubId:vr(e[1]),asset:kr(e[2]),scaledAmountRay:xr(e[3]),indexRay:xr(e[4]),amount:xr(e[5]),liquidationThresholdBps:r?void 0:vr(e[6]),liquidationBonusBps:r?void 0:vr(e[7]),loanToValueBps:r?void 0:vr(e[8]),liquidationFeesBps:r?void 0:vr(e[9])};var o},Or=e=>{return{owner:kr(e[0]),spokeId:vr(e[1]),mode:(t=e[2],Ar[vr(t)]??"None")};var t},Br=e=>Array.isArray(e)?e[1]:void 0,Nr=e=>{const t=(r=e,Array.isArray(r)?kr(r[0]):kr(r));var r;if("Token"===t)return{Token:kr(Br(e))};if("Ref"===t)return{Ref:kr(Br(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:kr(t.Token)};if(void 0!==t.Ref)return{Ref:kr(t.Ref)}}return{Token:kr(e)}},Lr=e=>{const t=e.tolerance??{};return{assetDecimals:vr(e.asset_decimals),maxPriceStaleSeconds:vr(e.max_price_stale_seconds),sources:Ir(e.sources).map((e=>e)),tolerance:{upperRatio:vr(t.upper_ratio_bps),lowerRatio:vr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:xr(e.min_sanity_price_wad),maxSanityPriceWad:xr(e.max_sanity_price_wad)}},$r={"market:create":e=>({topic:"market:create",data:{hubId:vr(e.hub_id),baseAsset:kr(e.base_asset),maxBorrowRate:xr(e.max_borrow_rate),baseBorrowRate:xr(e.base_borrow_rate),slope1:xr(e.slope1),slope2:xr(e.slope2),slope3:xr(e.slope3),midUtilization:xr(e.mid_utilization),optimalUtilization:xr(e.optimal_utilization),maxUtilization:xr(e.max_utilization),reserveFactor:vr(e.reserve_factor),marketAddress:kr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:kr(e.asset),maxBorrowRateRay:xr(e.max_borrow_rate),baseBorrowRateRay:xr(e.base_borrow_rate),slope1Ray:xr(e.slope1),slope2Ray:xr(e.slope2),slope3Ray:xr(e.slope3),midUtilizationRay:xr(e.mid_utilization),optimalUtilizationRay:xr(e.optimal_utilization),maxUtilizationRay:xr(e.max_utilization),reserveFactorBps:vr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ir(e).map((e=>{return t=Ir(e),{hubId:vr(t[0]),asset:kr(t[1]),timestamp:vr(t[2]),supplyIndexRay:xr(t[3]),borrowIndexRay:xr(t[4]),cash:xr(t[5]),suppliedRay:xr(t[6]),borrowedRay:xr(t[7]),revenueRay:xr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ir(e).map((e=>{const t=e;return{hubId:vr(t.hub_id),asset:kr(t.asset),params:(r=t.params,{maxBorrowRateRay:xr(r.max_borrow_rate),baseBorrowRateRay:xr(r.base_borrow_rate),slope1Ray:xr(r.slope1),slope2Ray:xr(r.slope2),slope3Ray:xr(r.slope3),midUtilizationRay:xr(r.mid_utilization),optimalUtilizationRay:xr(r.optimal_utilization),maxUtilizationRay:xr(r.max_utilization),reserveFactorBps:vr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:vr(r.flashloan_fee),assetId:kr(r.asset_id),assetDecimals:vr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ir(e);return{topic:"position:batch_update",data:{accountId:xr(t[0]),accountAttributes:Or(Ir(t[1])),updates:[...Ir(t[2]).map((e=>Pr(Ir(e),"Deposit"))),...Ir(t[3]).map((e=>Pr(Ir(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:vr(e.hub_id),asset:kr(e.asset),receiver:kr(e.receiver),caller:kr(e.caller),amount:xr(e.amount),fee:xr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Nr(e.key),oracle:Lr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:kr(e.asset),oracle:Lr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:kr(e.liquidator),accountId:xr(e.account_id),repaidUsdWad:xr(e.repaid_usd_wad),bonusBps:xr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:xr(e.account_id),totalBorrowUsdWad:xr(e.total_borrow_usd_wad),totalCollateralUsdWad:xr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:kr(e.token),amount:xr(e.amount),usdValueWad:xr(e.usd_value_wad),accountId:xr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:vr(e.hub_id),asset:kr(e.asset),amount:xr(e.amount),fee:xr(e.fee),amountSent:xr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:kr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Rr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:kr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:kr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:kr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:kr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Rr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:vr(e.max_supply_positions),maxBorrowPositions:vr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:xr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:kr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:vr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:xr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:xr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:vr(t.liquidation_bonus_factor_bps)}}}},Ur=Object.freeze(Object.keys($r));function Cr(e,t){const r=yr(e),o=$r[r];return o?o((0,d.scValToNative)(Tr(t))):null}const Gr="XLENDXLM-a7c9f3",qr=1e4;function Dr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Gr}-${r}`}function Wr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Mr(e,t=0){return e*qr+t}function Vr(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()},Fr=e=>e.baseUrl??s[e.network];async function Xr(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(Fr(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 Hr(e){const t=zr(Fr(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 jr=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Qr=e=>I(e).toXDR("base64");function Jr(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=N(jr(t,e.referralId));return{xdr:new d.TransactionBuilder(a,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call("execute_strategy",m(e.caller),f(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function Kr(e,t){return Jr(e,t)}function Zr(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(to),splitPpm:e.splitPpm}))):[{hops:e.hops.map(to),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function Yr(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:Zr(e,t)}const eo=Zr,to=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function ro(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function oo(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw ro(r.invokedContractId,e);throw e}}async function ao(e,t,r){return oo(e,t.xdr,r)}function no(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 io=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 lo(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(io(e.message)),d.xdr.ScVal.scvBytes(io(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 uo={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 co(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=uo[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:()=>mt,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>qr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>Wr,XOXNO_LENDING_STELLAR_TICKER:()=>Mr,buildSameTokenRepaySwapSteps:()=>uo,buildStellarAcceptOwnershipTx:()=>Fe,buildStellarAddRewardsTx:()=>dt,buildStellarApproveBlendPoolTx:()=>Ke,buildStellarApproveTokenTx:()=>Ye,buildStellarBatchSwapTx:()=>eo,buildStellarBorrowBatchTx:()=>M,buildStellarBorrowTx:()=>W,buildStellarCctpForwardTx:()=>po,buildStellarClaimRevenueTx:()=>ct,buildStellarCreateLiquidityPoolTx:()=>lt,buildStellarExecuteCancellerResetTx:()=>hr,buildStellarExecuteStrategyTx:()=>Yr,buildStellarFlashLoanTx:()=>j,buildStellarGovernanceAddSpokeImmediateTx:()=>_r,buildStellarGovernanceCreateHubImmediateTx:()=>br,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>lr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>cr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>dr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>pr,buildStellarGovernanceExecuteTx:()=>ir,buildStellarGovernanceExecuteUpdateDelayTx:()=>ur,buildStellarGovernancePauseTx:()=>yr,buildStellarGovernanceRevokeRoleImmediateTx:()=>wr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Sr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>gr,buildStellarGrantRoleTx:()=>We,buildStellarLendingIdentifier:()=>Vr,buildStellarLiquidateTx:()=>H,buildStellarMigrateFromBlendTx:()=>Q,buildStellarMigrateTx:()=>qe,buildStellarMultiplyTx:()=>J,buildStellarPauseTx:()=>De,buildStellarProposeAddAssetToSpokeTx:()=>Ut,buildStellarProposeAddSpokeTx:()=>Lt,buildStellarProposeApproveBlendPoolTx:()=>zt,buildStellarProposeApproveTokenTx:()=>Wt,buildStellarProposeCancellerResetTx:()=>fr,buildStellarProposeConfigureAssetOracleTx:()=>Yt,buildStellarProposeConfigureMarketOracleTx:()=>er,buildStellarProposeCreateHubTx:()=>Nt,buildStellarProposeCreateLiquidityPoolTx:()=>Xt,buildStellarProposeDeployPoolTx:()=>jt,buildStellarProposeEditAssetInSpokeTx:()=>Ct,buildStellarProposeEditOracleToleranceTx:()=>tr,buildStellarProposeGovernanceUpgradeTx:()=>rr,buildStellarProposeGrantGovernanceRoleTx:()=>ar,buildStellarProposeMigrateControllerTx:()=>Kt,buildStellarProposeRemoveAssetFromSpokeTx:()=>Gt,buildStellarProposeRemoveSpokeTx:()=>$t,buildStellarProposeRevokeBlendPoolTx:()=>Ft,buildStellarProposeRevokeGovernanceRoleTx:()=>nr,buildStellarProposeRevokeTokenTx:()=>Vt,buildStellarProposeSetAccumulatorTx:()=>Ot,buildStellarProposeSetAggregatorTx:()=>It,buildStellarProposeSetMinBorrowCollatTx:()=>Mt,buildStellarProposeSetPositionLimitsTx:()=>Bt,buildStellarProposeSetPositionManagerTx:()=>Dt,buildStellarProposeSetPriceAggregatorTx:()=>Pt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>qt,buildStellarProposeSetSwapAggregatorTx:()=>Et,buildStellarProposeTransferCtrlOwnershipTx:()=>Zt,buildStellarProposeTransferGovOwnTx:()=>sr,buildStellarProposeUnpauseTx:()=>Tr,buildStellarProposeUpdateDelayTx:()=>or,buildStellarProposeUpgradeControllerTx:()=>Jt,buildStellarProposeUpgradePoolParamsTx:()=>Ht,buildStellarProposeUpgradePoolTx:()=>Qt,buildStellarRenewAccountTx:()=>it,buildStellarRepayBatchTx:()=>F,buildStellarRepayDebtWithCollateralTx:()=>Y,buildStellarRepayTx:()=>X,buildStellarRevokeBlendPoolTx:()=>Ze,buildStellarRevokeRoleTx:()=>Ve,buildStellarRevokeTokenTx:()=>et,buildStellarSetAccumulatorTx:()=>Qe,buildStellarSetAggregatorTx:()=>je,buildStellarSetMarketOracleConfigTx:()=>rt,buildStellarSetOracleSanityBoundsTx:()=>nt,buildStellarSetOracleToleranceTx:()=>ot,buildStellarSetOracleTx:()=>tt,buildStellarSetPositionLimitsTx:()=>Je,buildStellarSetPriceAggregatorTx:()=>He,buildStellarSetSpokeAssetFlagsTx:()=>at,buildStellarSetSwapAggregatorTx:()=>Xe,buildStellarSupplyBatchTx:()=>q,buildStellarSupplyTx:()=>D,buildStellarSwapCollateralTx:()=>Z,buildStellarSwapDebtTx:()=>K,buildStellarTransferOwnershipTx:()=>ze,buildStellarUnpauseTx:()=>Me,buildStellarUpdateAccountThresholdTx:()=>pt,buildStellarUpdateIndexesTx:()=>st,buildStellarUpgradeControllerTx:()=>Ge,buildStellarUpgradeLiquidityPoolParamsTx:()=>ut,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>z,buildTx:()=>G,decodeStellarLendingEvent:()=>Dr,encodeAssetOracle:()=>Ue,encodeInterestRateModel:()=>ke,encodeMarketOracleConfigInput:()=>Ce,encodeMarketParamsRaw:()=>Re,encodePositionLimits:()=>Ae,encodePriceKey:()=>Ee,encodeStrategyPayloadToRouteXdr:()=>Zr,extractEventOrder:()=>zr,getStellarAccountPositions:()=>be,getStellarAggregatorQuote:()=>Qr,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>de,getStellarAssetGraph:()=>we,getStellarAssetMarkets:()=>me,getStellarAssetPage:()=>pe,getStellarAssets:()=>ne,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>_e,getStellarHub:()=>fe,getStellarHubGraph:()=>ye,getStellarHubs:()=>se,getStellarLendingContext:()=>oe,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>ae,getStellarQuoteTokens:()=>Jr,getStellarReserve:()=>ue,getStellarReserveGraph:()=>xe,getStellarReserveHolders:()=>ce,getStellarReserves:()=>le,getStellarSpoke:()=>he,getStellarSpokeGraph:()=>Te,getStellarSpokes:()=>ie,getStellarUserActivity:()=>Se,getStellarUserPositions:()=>ge,mapQuoteResponseToAggregatorSwap:()=>oo,mapQuoteResponseToStrategyPayload:()=>to,mapQuoteResponseToStrategySwap:()=>ro,mapSorobanError:()=>fo,mapStellarPositionActivityType:()=>Xr,prepareStellarBuiltTx:()=>io,prepareStellarTxXdr:()=>so,stellarLendingDispatchKey:()=>kr,stellarLendingRead:()=>ve,syntheticEventOrder:()=>Fr,tagStellarInvokedContractError:()=>no,toBase64Xdr:()=>xr,toStellarPositionMode:()=>lo});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)}),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=>{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 O{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 B=e=>{const t=new O(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},U=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(B(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},C=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=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 q(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return G(e,"supply",[h(e.caller),b(r),S(o),P([...t.assets])])}function D(e,t){return q(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function M(e,t){return G(e,"borrow",[h(e.caller),b(t.accountNonce),P([...t.borrows]),k(t.to,h)])}function W(e,t){return M(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),P([...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),P([...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),P([...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),C(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),U(t.steps),k(t.initialPayment,(e=>E(e.hubId,e.asset,e.amount))),k(t.convertSwap,U)])}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),U(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),U(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),U(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=>({context:t=>oe(e,t),liveState:t=>ae(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)}),ke=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)}),Re=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)}),Ae=e=>I({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),Ee=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)}`)},Pe=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)}`)},Ie=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)}`)},Oe=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Be=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ne=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),I({asset:Pe(t.asset),contract:h(t.contract),read_mode:Ie(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:Oe(t.kind),nature:Be(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Le=e=>{const t=e;return I({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:Ne(t.provider)})},$e=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:Oe(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},Ue=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:$e(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"),Le(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),I({factor:Le(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:Ee(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),I({key_a:Ee(t.keyA),key_b:Ee(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)})})},Ce=Ue;function Ge(e,t){return G(e,"upgrade",[v(t.wasmHash)])}function qe(e,t){return G(e,"migrate",[S(t.newVersion)])}function De(e){return G(e,"pause",[])}function Me(e){return G(e,"unpause",[])}function We(e,t){return G(e,"grant_role",[h(t.account),y(t.role)])}function Ve(e,t){return G(e,"revoke_role",[h(t.account),y(t.role)])}function ze(e,t){return G(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Fe(e){return G(e,"accept_ownership",[])}function Xe(e,t){return G(e,"set_swap_aggregator",[h(t.aggregator)])}function He(e,t){return G(e,"set_price_aggregator",[h(t.aggregator)])}const je=Xe;function Qe(e,t){return G(e,"set_accumulator",[h(t.accumulator)])}function Je(e,t){return G(e,"set_position_limits",[Ae(t)])}function Ke(e,t){return G(e,"approve_blend_pool",[h(t.pool)])}function Ze(e,t){return G(e,"revoke_blend_pool",[h(t.pool)])}const Ye=Ke,et=Ze;function tt(e,t){return G(e,"set_oracle",[Ee(t.key),Ue(t.oracle)])}const rt=tt;function ot(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",[Ee(t.key),I({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function at(e,t){return G(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function nt(e,t){return G(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function st(e,t){return G(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function it(e,t){return G(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function lt(e,t){return G(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Re(t.params)])}function ut(e,t){return G(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),ke(t.params)])}function ct(e,t){return G(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function dt(e,t){return G(e,"add_rewards",[h(e.caller),P(t.rewards)])}function pt(e,t){return G(e,"update_account_threshold",[h(e.caller),_(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const mt="00".repeat(32),ft=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)},ht=(e,...t)=>x([y(e),...t]),gt=e=>I({asset:h(e.asset),hub_id:S(e.hubId),params:Re(e.params)}),St=e=>I({hub_asset:A(e.hubId,e.asset),params:ke(e.params)}),bt=e=>I({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),_t=e=>I({key:Ee(e.key),oracle:Ue(e.oracle)}),wt=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)}),yt=e=>I({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),Tt=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)}),xt=e=>I({key:Ee(e.key),tolerance:S(e.tolerance)}),vt=e=>I({account:h(e.account),role:y(e.role)});function kt(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 Rt=(e,t,r)=>kt(e,"propose",[h(e.caller),t,ft(r)]),At=(e,t,r)=>kt(e,"execute_self",[T(),t,ft(r)]);function Et(e,t,r){return Rt(e,ht("SetSwapAggregator",h(t.aggregator)),r)}function Pt(e,t,r){return Rt(e,ht("SetPriceAggregator",h(t.aggregator)),r)}const It=Et;function Ot(e,t,r){return Rt(e,ht("SetAccumulator",h(t.accumulator)),r)}function Bt(e,t,r){return Rt(e,ht("SetPositionLimits",Ae(t)),r)}function Nt(e,t){return Rt(e,ht("CreateHub"),t)}function Lt(e,t){return Rt(e,ht("AddSpoke"),t)}function $t(e,t,r){return Rt(e,ht("RemoveSpoke",S(t.spokeId)),r)}function Ut(e,t,r){return Rt(e,ht("AddAssetToSpoke",wt(t)),r)}function Ct(e,t,r){return Rt(e,ht("EditAssetInSpoke",wt(t)),r)}function Gt(e,t,r){return Rt(e,ht("RemoveAssetFromSpoke",yt(t)),r)}function qt(e,t,r){return Rt(e,ht("SetSpokeLiquidationCurve",Tt(t)),r)}function Dt(e,t,r){return Rt(e,ht("SetPositionManager",h(t.manager),_(t.isActive)),r)}function Mt(e,t,r){return Rt(e,ht("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Wt(e,t,r){return Rt(e,ht("ApproveToken",h(t.token)),r)}function Vt(e,t,r){return Rt(e,ht("RevokeToken",h(t.token)),r)}function zt(e,t,r){return Rt(e,ht("ApproveBlendPool",h(t.pool)),r)}function Ft(e,t,r){return Rt(e,ht("RevokeBlendPool",h(t.pool)),r)}function Xt(e,t,r){return Rt(e,ht("CreateLiquidityPool",gt(t)),r)}function Ht(e,t,r){return Rt(e,ht("UpgradeLiquidityPoolParams",St(t)),r)}function jt(e,t,r){return Rt(e,ht("DeployPool",v(t.wasmHash)),r)}function Qt(e,t,r){return Rt(e,ht("UpgradePool",v(t.wasmHash)),r)}function Jt(e,t,r){return Rt(e,ht("UpgradeController",v(t.wasmHash)),r)}function Kt(e,t,r){return Rt(e,ht("MigrateController",S(t.newVersion)),r)}function Zt(e,t,r){return Rt(e,ht("TransferCtrlOwnership",bt(t)),r)}function Yt(e,t,r){return Rt(e,ht("ConfigureAssetOracle",_t(t)),r)}const er=Yt;function tr(e,t,r){return Rt(e,ht("EditOracleTolerance",xt(t)),r)}function rr(e,t,r){return Rt(e,ht("UpgradeGov",v(t.wasmHash)),r)}function or(e,t,r){return Rt(e,ht("UpdateGovDelay",S(t.newDelay)),r)}function ar(e,t,r){return Rt(e,ht("GrantGovRole",vt(t)),r)}function nr(e,t,r){return Rt(e,ht("RevokeGovRole",vt(t)),r)}function sr(e,t,r){return Rt(e,ht("TransferGovOwnership",bt(t)),r)}function ir(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=ft(t.predecessor??mt);return kt(e,"execute",[T(),h(t.target),y(t.functionName),r,o,ft(t.salt)])}function lr(e,t,r){return At(e,ht("UpgradeGov",v(t.wasmHash)),r)}function ur(e,t,r){return At(e,ht("UpdateGovDelay",S(t.newDelay)),r)}function cr(e,t,r){return At(e,ht("GrantGovRole",vt(t)),r)}function dr(e,t,r){return At(e,ht("RevokeGovRole",vt(t)),r)}function pr(e,t,r){return At(e,ht("TransferGovOwnership",bt(t)),r)}const mr=e=>x(e.map(h));function fr(e,t,r){return kt(e,"propose_canceller_reset",[mr(t.newCancellers),ft(r)])}function hr(e,t,r){return kt(e,"execute_canceller_reset",[k(t.executor,h),mr(t.newCancellers),ft(r)])}function gr(e,t){return kt(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function Sr(e,t){return kt(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function br(e){return kt(e,"create_hub",[h(e.caller)])}function _r(e){return kt(e,"add_spoke",[h(e.caller)])}function wr(e,t){return kt(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function yr(e){return kt(e,"pause",[h(e.caller)])}function Tr(e,t){return Rt(e,ht("Unpause"),t)}const xr=e=>e.toXDR("base64"),vr=e=>d.xdr.ScVal.fromXDR(e,"base64"),kr=e=>e.map((e=>String((0,d.scValToNative)(vr(e))))).join(":"),Rr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Ar=e=>Number(e),Er=e=>String(e),Pr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ir=["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"],Br=e=>Array.isArray(e)?e:[],Nr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Or[Ar(o)]??Rr(o)),positionType:t,hubId:Ar(e[1]),asset:Er(e[2]),scaledAmountRay:Rr(e[3]),indexRay:Rr(e[4]),amount:Rr(e[5]),liquidationThresholdBps:r?void 0:Ar(e[6]),liquidationBonusBps:r?void 0:Ar(e[7]),loanToValueBps:r?void 0:Ar(e[8]),liquidationFeesBps:r?void 0:Ar(e[9])};var o},Lr=e=>{return{owner:Er(e[0]),spokeId:Ar(e[1]),mode:(t=e[2],Ir[Ar(t)]??"None")};var t},$r=e=>Array.isArray(e)?e[1]:void 0,Ur=e=>{const t=(r=e,Array.isArray(r)?Er(r[0]):Er(r));var r;if("Token"===t)return{Token:Er($r(e))};if("Ref"===t)return{Ref:Er($r(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Er(t.Token)};if(void 0!==t.Ref)return{Ref:Er(t.Ref)}}return{Token:Er(e)}},Cr=e=>{const t=e.tolerance??{};return{assetDecimals:Ar(e.asset_decimals),maxPriceStaleSeconds:Ar(e.max_price_stale_seconds),sources:Br(e.sources).map((e=>e)),tolerance:{upperRatio:Ar(t.upper_ratio_bps),lowerRatio:Ar(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Rr(e.min_sanity_price_wad),maxSanityPriceWad:Rr(e.max_sanity_price_wad)}},Gr={"market:create":e=>({topic:"market:create",data:{hubId:Ar(e.hub_id),baseAsset:Er(e.base_asset),maxBorrowRate:Rr(e.max_borrow_rate),baseBorrowRate:Rr(e.base_borrow_rate),slope1:Rr(e.slope1),slope2:Rr(e.slope2),slope3:Rr(e.slope3),midUtilization:Rr(e.mid_utilization),optimalUtilization:Rr(e.optimal_utilization),maxUtilization:Rr(e.max_utilization),reserveFactor:Ar(e.reserve_factor),marketAddress:Er(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Er(e.asset),maxBorrowRateRay:Rr(e.max_borrow_rate),baseBorrowRateRay:Rr(e.base_borrow_rate),slope1Ray:Rr(e.slope1),slope2Ray:Rr(e.slope2),slope3Ray:Rr(e.slope3),midUtilizationRay:Rr(e.mid_utilization),optimalUtilizationRay:Rr(e.optimal_utilization),maxUtilizationRay:Rr(e.max_utilization),reserveFactorBps:Ar(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Br(e).map((e=>{return t=Br(e),{hubId:Ar(t[0]),asset:Er(t[1]),timestamp:Ar(t[2]),supplyIndexRay:Rr(t[3]),borrowIndexRay:Rr(t[4]),cash:Rr(t[5]),suppliedRay:Rr(t[6]),borrowedRay:Rr(t[7]),revenueRay:Rr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Br(e).map((e=>{const t=e;return{hubId:Ar(t.hub_id),asset:Er(t.asset),params:(r=t.params,{maxBorrowRateRay:Rr(r.max_borrow_rate),baseBorrowRateRay:Rr(r.base_borrow_rate),slope1Ray:Rr(r.slope1),slope2Ray:Rr(r.slope2),slope3Ray:Rr(r.slope3),midUtilizationRay:Rr(r.mid_utilization),optimalUtilizationRay:Rr(r.optimal_utilization),maxUtilizationRay:Rr(r.max_utilization),reserveFactorBps:Ar(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Ar(r.flashloan_fee),assetId:Er(r.asset_id),assetDecimals:Ar(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Br(e);return{topic:"position:batch_update",data:{accountId:Rr(t[0]),accountAttributes:Lr(Br(t[1])),updates:[...Br(t[2]).map((e=>Nr(Br(e),"Deposit"))),...Br(t[3]).map((e=>Nr(Br(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Ar(e.hub_id),asset:Er(e.asset),receiver:Er(e.receiver),caller:Er(e.caller),amount:Rr(e.amount),fee:Rr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Ur(e.key),oracle:Cr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Er(e.asset),oracle:Cr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Er(e.liquidator),accountId:Rr(e.account_id),repaidUsdWad:Rr(e.repaid_usd_wad),bonusBps:Rr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Rr(e.account_id),totalBorrowUsdWad:Rr(e.total_borrow_usd_wad),totalCollateralUsdWad:Rr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Er(e.token),amount:Rr(e.amount),usdValueWad:Rr(e.usd_value_wad),accountId:Rr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Ar(e.hub_id),asset:Er(e.asset),amount:Rr(e.amount),fee:Rr(e.fee),amountSent:Rr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Er(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:Pr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Er(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Er(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Er(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Er(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Pr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Ar(e.max_supply_positions),maxBorrowPositions:Ar(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Rr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Er(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Ar(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Rr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Rr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Ar(t.liquidation_bonus_factor_bps)}}}},qr=Object.freeze(Object.keys(Gr));function Dr(e,t){const r=kr(e),o=Gr[r];return o?o((0,d.scValToNative)(vr(t))):null}const Mr="XLENDXLM-a7c9f3",Wr=1e4;function Vr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Mr}-${r}`}function zr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Fr(e,t=0){return e*Wr+t}function Xr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Hr=(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()},jr=e=>e.baseUrl??s[e.network];async function Qr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Hr(jr(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 Jr(e){const t=Hr(jr(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 Kr=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Zr=e=>B(e).toXDR("base64");function Yr(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=U(Kr(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 eo(e,t){return Yr(e,t)}function to(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(ao),splitPpm:e.splitPpm}))):[{hops:e.hops.map(ao),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function ro(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:to(e,t)}const oo=to,ao=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function no(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function so(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw no(r.invokedContractId,e);throw e}}async function io(e,t,r){return so(e,t.xdr,r)}function lo(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 uo(e,t){return new Uint8Array(0)}const co=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 po(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(co(e.message)),d.xdr.ScVal.scvBytes(co(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 mo={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 fo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=mo[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??""},c={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},u={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=c[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 _(e){const t=u[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const g=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],b=e=>new t(e).toScVal(),w=e=>new a(e).toI128(),y=e=>i.ScVal.scvU32(e),v=e=>new a("string"==typeof e?e:e.toString()).toU64(),S=e=>i.ScVal.scvBool(e),k=e=>i.ScVal.scvString(e),R=e=>i.ScVal.scvSymbol(e),T=()=>i.ScVal.scvVoid(),x=e=>i.ScVal.scvVec(e),I=(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)},A=(e,t)=>null==e?T():t(e),E=(e,t)=>$({asset:b(t),hub_id:y(e)}),B=(e,t,r)=>i.ScVal.scvVec([E(e,t),w(r)]),N=e=>i.ScVal.scvVec(e.map((e=>B(e.hubId,e.asset,e.amount)))),$=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:R(t),val:e[t]})));return i.ScVal.scvMap(t)},O=e=>{const t=e.paths.map((e=>{const t=e.hops.map((e=>{return $({amount_out:w(e.amountOut),pool:b(e.pool),token_in:b(e.tokenIn),token_out:b(e.tokenOut),venue:(t=e.venue,i.ScVal.scvVec([R(t)]))});var t}));return $({hops:i.ScVal.scvVec(t),split_ppm:y(e.splitPpm)})}));return $({paths:i.ScVal.scvVec(t),referral_id:v(e.referralId??0),token_in:b(e.tokenIn),token_out:b(e.tokenOut),total_min_out:w(e.totalMinOut)})},P=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)},U=()=>i.ScVal.scvBytes(Buffer.alloc(0)),L=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},q=e=>{if("string"==typeof e)return P(L(e));if(e instanceof Uint8Array)return 0===e.length?U():P(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?P(L(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?P(L(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?P(L(e.bytes)):0===e.bytes.length?U():P(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");let r=0;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`);r+=o.splitPpm;for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.amountOut||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!g.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have amountOut, pool, tokenIn, tokenOut, and a valid Soroban venue`)}if(1e6!==r)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` must sum to 1_000_000, got ${r}`);return t})(e),i.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)")},W=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 z(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),c=new e(t.caller,t.sourceSequence);return{xdr:new n(c,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return z(e,"supply",[b(e.caller),v(r),y(o),N([...t.assets])])}function V(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function C(e,t){return z(e,"borrow",[b(e.caller),v(t.accountNonce),N([...t.borrows]),A(t.to,b)])}function F(e,t){return C(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function M(e,t){return z(e,"withdraw",[b(e.caller),v(t.accountNonce),N([...t.withdrawals]),A(t.to,b)])}function G(e,t){return M(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return z(e,"repay",[b(e.caller),v(t.accountNonce),N([...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 z(e,"liquidate",[b(e.caller),v(t.accountNonce),N([...t.debtPayments])])}function J(e,t){return z(e,"flash_loan",[b(e.caller),E(t.hubId,t.asset),w(t.amount),b(t.receiver),W(t.data)])}function Q(e,t){return z(e,"migrate_from_blend",[b(e.caller),v(t.accountId),y(t.spokeId),y(t.hubId),b(t.blendPool),x(t.collateralTokens.map(b)),x(t.supplyTokens.map(b)),(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([b(t),w(r)]);var t,r}))))]);var r}function K(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return z(e,"multiply",[b(e.caller),v(r),y(o),E(t.collateral.hubId,t.collateral.asset),w(t.debtToFlashLoan),E(t.debt.hubId,t.debt.asset),y(t.mode),q(t.steps),A(t.initialPayment,(e=>B(e.hubId,e.asset,e.amount))),A(t.convertSwap,q)])}function Z(e,t){return z(e,"swap_debt",[b(e.caller),v(t.accountNonce),E(t.existingDebt.hubId,t.existingDebt.asset),w(t.newDebtAmount),E(t.newDebt.hubId,t.newDebt.asset),q(t.steps)])}function Y(e,t){return z(e,"swap_collateral",[b(e.caller),v(t.accountNonce),E(t.current.hubId,t.current.asset),w(t.fromAmount),E(t.newCollateral.hubId,t.newCollateral.asset),q(t.steps)])}function ee(e,t){return z(e,"repay_debt_with_collateral",[b(e.caller),v(t.accountNonce),E(t.collateral.hubId,t.collateral.asset),w(t.collateralAmount),E(t.debt.hubId,t.debt.asset),q(t.steps),S(t.closePosition)])}const te="/stellar-lending",re=25,oe=encodeURIComponent,ae=(e,t)=>e.fetchWithTimeout(`${te}/context`,t),ne=(e,t)=>e.fetchWithTimeout(`${te}/live-state`,t),se=(e,t)=>e.fetchWithTimeout(`${te}/assets`,t),ie=(e,t)=>e.fetchWithTimeout(`${te}/hubs`,t),le=(e,t)=>e.fetchWithTimeout(`${te}/spokes`,t),ce=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${te}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},ue=(e,t,r,o,a)=>e.fetchWithTimeout(`${te}/reserves/${t}/${r}/${oe(o)}`,a),pe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${r}/${oe(o)}/holders`,{...n,params:{side:a}}),de=(e,t,r)=>e.fetchWithTimeout(`${te}/assets/${oe(t)}`,r),me=(e,t,r,o)=>e.fetchWithTimeout(`${te}/assets/${oe(t)}/page`,{...o,params:{...r}}),fe=(e,t,r,o)=>e.fetchWithTimeout(`${te}/assets/${oe(t)}/markets`,{...o,params:{side:r}}),he=(e,t,r)=>e.fetchWithTimeout(`${te}/hubs/${t}`,r),_e=(e,t,r)=>e.fetchWithTimeout(`${te}/spokes/${t}`,r),ge=(e,t,r)=>e.fetchWithTimeout(`${te}/users/${oe(t)}/positions`,r),be=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${te}/users/${oe(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},we=(e,t,r)=>e.fetchWithTimeout(`${te}/accounts/${oe(t)}/positions`,r),ye=(e,t={},r)=>{const{top:o=re,continuationToken:a}=t;return e.fetchWithTimeout(`${te}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},ve=(e,t,r,o)=>e.fetchWithTimeout(`${te}/assets/${oe(t)}/graph`,{...o,params:{...r}}),Se=(e,t,r,o)=>e.fetchWithTimeout(`${te}/hubs/${t}/graph`,{...o,params:{...r}}),ke=(e,t,r,o)=>e.fetchWithTimeout(`${te}/spokes/${t}/graph`,{...o,params:{...r}}),Re=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${r}/${oe(o)}/graph`,{...n,params:{...a}}),Te=e=>({context:t=>ae(e,t),liveState:t=>ne(e,t),assets:t=>se(e,t),hubs:t=>ie(e,t),spokes:t=>le(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)=>ue(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>pe(e,t,r,o,a,n),asset:(t,r)=>de(e,t,r),assetMarkets:(t,r,o)=>fe(e,t,r,o),hub:(t,r)=>he(e,t,r),spoke:(t,r)=>_e(e,t,r),userPositions:(t,r)=>ge(e,t,r),userActivity:(t,r,o)=>be(e,t,r,o),accountPositions:(t,r)=>we(e,t,r),governanceProposals:(t,r)=>ye(e,t,r),assetGraph:(t,r,o)=>ve(e,t,r,o),hubGraph:(t,r,o)=>Se(e,t,r,o),spokeGraph:(t,r,o)=>ke(e,t,r,o),reserveGraph:(t,r,o,a,n)=>Re(e,t,r,o,a,n)}),xe=e=>$({base_borrow_rate:w(e.baseBorrowRateRay),max_borrow_rate:w(e.maxBorrowRateRay),max_utilization:w(e.maxUtilizationRay),mid_utilization:w(e.midUtilizationRay),optimal_utilization:w(e.optimalUtilizationRay),reserve_factor:y(e.reserveFactorBps),slope1:w(e.slope1Ray),slope2:w(e.slope2Ray),slope3:w(e.slope3Ray)}),Ie=e=>$({asset_decimals:y(e.assetDecimals),asset_id:b(e.assetId),base_borrow_rate:w(e.baseBorrowRateRay),flashloan_fee:y(e.flashloanFeeBps),is_flashloanable:S(e.isFlashloanable),max_borrow_rate:w(e.maxBorrowRateRay),max_utilization:w(e.maxUtilizationRay),mid_utilization:w(e.midUtilizationRay),optimal_utilization:w(e.optimalUtilizationRay),reserve_factor:y(e.reserveFactorBps),slope1:w(e.slope1Ray),slope2:w(e.slope2Ray),slope3:w(e.slope3Ray)}),Ae=e=>$({max_borrow_positions:y(e.maxBorrowPositions),max_supply_positions:y(e.maxSupplyPositions)}),Ee=e=>{if("Token"in e&&e.Token)return x([R("Token"),b(e.Token)]);if("Ref"in e&&e.Ref)return x([R("Ref"),R(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Be=e=>{if("Stellar"in e)return x([R("Stellar"),b(e.Stellar)]);if("Symbol"in e)return x([R("Symbol"),R(e.Symbol)]);if("String"in e)return x([R("String"),k(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ne=e=>{if("Spot"===e)return x([R("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([R("Twap"),y(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},$e=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([R(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Oe=e=>{if("Market"===e||"Fundamental"===e)return x([R(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Pe=e=>{if("Reflector"in e){const t=e.Reflector;return x([R("Reflector"),$({asset:Be(t.asset),contract:b(t.contract),read_mode:Ne(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([R("MultiFeed"),$({contract:b(t.contract),feed_id:k(t.feedId),kind:$e(t.kind),nature:Oe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ue=e=>{const t=e;return $({decimals:y(t.decimals),max_stale_seconds:v(t.maxStaleSeconds),provider:Pe(t.provider)})},Le=e=>{if("RequireDisjoint"===e)return x([R("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return x([R("AllowShared"),x(t.map((e=>$({contract:b(e.contract),kind:$e(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},qe=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 $({asset_decimals:y(Number(t.assetDecimals)),independence:Le(t.independence),max_price_stale_seconds:v(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:w(String(t.maxSanityPriceWad)),min_sanity_price_wad:w(String(t.minSanityPriceWad)),sources:x(r.map((e=>(e=>{if("Feed"in e)return x([R("Feed"),Ue(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([R("Scaled"),$({factor:Ue(t.factor),max_factor_wad:w(t.maxFactorWad),min_factor_wad:w(t.minFactorWad),quote:Ee(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([R("LpShare"),$({key_a:Ee(t.keyA),key_b:Ee(t.keyB),kind:x([R(t.kind||"ConstantProduct")]),pool:b(t.pool),reserve_a_decimals:y(t.reserveADecimals),reserve_b_decimals:y(t.reserveBDecimals),share_decimals:y(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:$({lower_ratio_bps:y(a),upper_ratio_bps:y(o)})})},We=qe;function ze(e,t){return z(e,"upgrade",[I(t.wasmHash)])}function De(e,t){return z(e,"migrate",[y(t.newVersion)])}function Ve(e){return z(e,"pause",[])}function Ce(e){return z(e,"unpause",[])}function Fe(e,t){return z(e,"grant_role",[b(t.account),R(t.role)])}function Me(e,t){return z(e,"revoke_role",[b(t.account),R(t.role)])}function Ge(e,t){return z(e,"transfer_ownership",[b(t.newOwner),y(t.liveUntilLedger)])}function Xe(e){return z(e,"accept_ownership",[])}function He(e,t){return z(e,"set_swap_aggregator",[b(t.aggregator)])}function je(e,t){return z(e,"set_price_aggregator",[b(t.aggregator)])}const Je=He;function Qe(e,t){return z(e,"set_accumulator",[b(t.accumulator)])}function Ke(e,t){return z(e,"set_position_limits",[Ae(t)])}function Ze(e,t){return z(e,"approve_blend_pool",[b(t.pool)])}function Ye(e,t){return z(e,"revoke_blend_pool",[b(t.pool)])}const et=Ze,tt=Ye;function rt(e,t){return z(e,"set_oracle",[Ee(t.key),qe(t.oracle)])}const ot=rt;function at(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return z(e,"set_tolerance",[Ee(t.key),$({lower_ratio_bps:y(a),upper_ratio_bps:y(o)})])}function nt(e,t){return z(e,"set_spoke_asset_flags",[y(t.spokeId),E(t.hubId,t.asset),S(t.paused),S(t.frozen)])}function st(e,t){return z(e,"set_oracle_sanity_bounds",[b(t.asset),w(t.minPriceWad),w(t.maxPriceWad)])}function it(e,t){return z(e,"update_indexes",[b(e.caller),x(t.assets.map((e=>E(e.hubId,e.asset))))])}function lt(e,t){return z(e,"renew_account",[b(e.caller),v(t.accountNonce)])}function ct(e,t){return z(e,"create_liquidity_pool",[y(t.hubId),b(t.asset),Ie(t.params)])}function ut(e,t){return z(e,"upgrade_liquidity_pool_params",[E(t.hubId,t.asset),xe(t.params)])}function pt(e,t){return z(e,"claim_revenue",[b(e.caller),x(t.assets.map((e=>E(e.hubId,e.asset))))])}function dt(e,t){return z(e,"add_rewards",[b(e.caller),N(t.rewards)])}function mt(e,t){return z(e,"update_account_threshold",[b(e.caller),S(t.hasRisks),x(t.accountNonces.map((e=>v(e))))])}const ft="00".repeat(32),ht=e=>{if("string"==typeof e)return I(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)},_t=(e,...t)=>x([R(e),...t]),gt=e=>$({new_owner:b(e.newOwner),live_until_ledger:y(e.liveUntilLedger)}),bt=e=>$({asset:b(e.asset),bonus:y(e.bonus),borrow_cap:w(e.borrowCap),can_borrow:S(e.canBorrow),can_collateral:S(e.canCollateral),frozen:S(e.frozen),hub_id:y(e.hubId),paused:S(e.paused),liquidation_fees:y(e.liquidationFees),ltv:y(e.ltv),oracle_override:x([R("None")]),spoke_id:y(e.spokeId),supply_cap:w(e.supplyCap),threshold:y(e.threshold)}),wt=e=>$({account:b(e.account),role:R(e.role)});function yt(t,a,s){const i=t.governanceAddress??_(t.network),l=new o(i),c=new e(t.caller,t.sourceSequence);return{xdr:new n(c,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const vt=(e,t,r)=>yt(e,"propose",[b(e.caller),t,ht(r)]),St=(e,t,r)=>yt(e,"execute_self",[T(),t,ht(r)]);function kt(e,t,r){return vt(e,_t("SetSwapAggregator",b(t.aggregator)),r)}function Rt(e,t,r){return vt(e,_t("SetPriceAggregator",b(t.aggregator)),r)}const Tt=kt;function xt(e,t,r){return vt(e,_t("SetAccumulator",b(t.accumulator)),r)}function It(e,t,r){return vt(e,_t("SetPositionLimits",Ae(t)),r)}function At(e,t){return vt(e,_t("CreateHub"),t)}function Et(e,t){return vt(e,_t("AddSpoke"),t)}function Bt(e,t,r){return vt(e,_t("RemoveSpoke",y(t.spokeId)),r)}function Nt(e,t,r){return vt(e,_t("AddAssetToSpoke",bt(t)),r)}function $t(e,t,r){return vt(e,_t("EditAssetInSpoke",bt(t)),r)}function Ot(e,t,r){return vt(e,_t("RemoveAssetFromSpoke",$({hub_asset:E((o=t).hubId,o.asset),spoke_id:y(o.spokeId)})),r);var o}function Pt(e,t,r){return vt(e,_t("SetSpokeLiquidationCurve",$({hf_for_max_bonus_wad:w((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:y(o.liquidationBonusFactorBps),spoke_id:y(o.spokeId),target_hf_wad:w(o.targetHfWad)})),r);var o}function Ut(e,t,r){return vt(e,_t("SetPositionManager",b(t.manager),S(t.isActive)),r)}function Lt(e,t,r){return vt(e,_t("SetMinBorrowCollateralUsd",w(t.floorWad)),r)}function qt(e,t,r){return vt(e,_t("ApproveToken",b(t.token)),r)}function Wt(e,t,r){return vt(e,_t("RevokeToken",b(t.token)),r)}function zt(e,t,r){return vt(e,_t("ApproveBlendPool",b(t.pool)),r)}function Dt(e,t,r){return vt(e,_t("RevokeBlendPool",b(t.pool)),r)}function Vt(e,t,r){return vt(e,_t("CreateLiquidityPool",$({asset:b((o=t).asset),hub_id:y(o.hubId),params:Ie(o.params)})),r);var o}function Ct(e,t,r){return vt(e,_t("UpgradeLiquidityPoolParams",$({hub_asset:E((o=t).hubId,o.asset),params:xe(o.params)})),r);var o}function Ft(e,t,r){return vt(e,_t("DeployPool",I(t.wasmHash)),r)}function Mt(e,t,r){return vt(e,_t("UpgradePool",I(t.wasmHash)),r)}function Gt(e,t,r){return vt(e,_t("UpgradeController",I(t.wasmHash)),r)}function Xt(e,t,r){return vt(e,_t("MigrateController",y(t.newVersion)),r)}function Ht(e,t,r){return vt(e,_t("TransferCtrlOwnership",gt(t)),r)}function jt(e,t,r){return vt(e,_t("ConfigureAssetOracle",$({key:Ee((o=t).key),oracle:qe(o.oracle)})),r);var o}const Jt=jt;function Qt(e,t,r){return vt(e,_t("EditOracleTolerance",$({key:Ee((o=t).key),tolerance:y(o.tolerance)})),r);var o}function Kt(e,t,r){return vt(e,_t("UpgradeGov",I(t.wasmHash)),r)}function Zt(e,t,r){return vt(e,_t("UpdateGovDelay",y(t.newDelay)),r)}function Yt(e,t,r){return vt(e,_t("GrantGovRole",wt(t)),r)}function er(e,t,r){return vt(e,_t("RevokeGovRole",wt(t)),r)}function tr(e,t,r){return vt(e,_t("TransferGovOwnership",gt(t)),r)}function rr(e,t){const r=x(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=ht(t.predecessor??ft);return yt(e,"execute",[T(),b(t.target),R(t.functionName),r,o,ht(t.salt)])}function or(e,t,r){return St(e,_t("UpgradeGov",I(t.wasmHash)),r)}function ar(e,t,r){return St(e,_t("UpdateGovDelay",y(t.newDelay)),r)}function nr(e,t,r){return St(e,_t("GrantGovRole",wt(t)),r)}function sr(e,t,r){return St(e,_t("RevokeGovRole",wt(t)),r)}function ir(e,t,r){return St(e,_t("TransferGovOwnership",gt(t)),r)}const lr=e=>x(e.map(b));function cr(e,t,r){return yt(e,"propose_canceller_reset",[lr(t.newCancellers),ht(r)])}function ur(e,t,r){return yt(e,"execute_canceller_reset",[A(t.executor,b),lr(t.newCancellers),ht(r)])}function pr(e,t){return yt(e,"set_spoke_asset_flags",[b(e.caller),y(t.spokeId),E(t.hubId,t.asset),S(t.paused),S(t.frozen)])}function dr(e,t){return yt(e,"set_oracle_sanity_bounds",[b(e.caller),b(t.asset),w(t.minPriceWad),w(t.maxPriceWad)])}function mr(e){return yt(e,"create_hub",[b(e.caller)])}function fr(e){return yt(e,"add_spoke",[b(e.caller)])}function hr(e,t){return yt(e,"revoke_role_immediate",[b(t.account),R(t.role)])}function _r(e){return yt(e,"pause",[b(e.caller)])}function gr(e,t){return vt(e,_t("Unpause"),t)}const br=e=>e.toXDR("base64"),wr=e=>i.ScVal.fromXDR(e,"base64"),yr=e=>e.map((e=>String(s(wr(e))))).join(":"),vr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Sr=e=>Number(e),kr=e=>String(e),Rr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Tr=["None","Multiply","Long","Short"],xr=["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"],Ir=e=>Array.isArray(e)?e:[],Ar=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],xr[Sr(o)]??vr(o)),positionType:t,hubId:Sr(e[1]),asset:kr(e[2]),scaledAmountRay:vr(e[3]),indexRay:vr(e[4]),amount:vr(e[5]),liquidationThresholdBps:r?void 0:Sr(e[6]),liquidationBonusBps:r?void 0:Sr(e[7]),loanToValueBps:r?void 0:Sr(e[8]),liquidationFeesBps:r?void 0:Sr(e[9])};var o},Er=e=>{return{owner:kr(e[0]),spokeId:Sr(e[1]),mode:(t=e[2],Tr[Sr(t)]??"None")};var t},Br=e=>Array.isArray(e)?e[1]:void 0,Nr=e=>{const t=(r=e,Array.isArray(r)?kr(r[0]):kr(r));var r;if("Token"===t)return{Token:kr(Br(e))};if("Ref"===t)return{Ref:kr(Br(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:kr(t.Token)};if(void 0!==t.Ref)return{Ref:kr(t.Ref)}}return{Token:kr(e)}},$r=e=>{const t=e.tolerance??{};return{assetDecimals:Sr(e.asset_decimals),maxPriceStaleSeconds:Sr(e.max_price_stale_seconds),sources:Ir(e.sources).map((e=>e)),tolerance:{upperRatio:Sr(t.upper_ratio_bps),lowerRatio:Sr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:vr(e.min_sanity_price_wad),maxSanityPriceWad:vr(e.max_sanity_price_wad)}},Or={"market:create":e=>({topic:"market:create",data:{hubId:Sr(e.hub_id),baseAsset:kr(e.base_asset),maxBorrowRate:vr(e.max_borrow_rate),baseBorrowRate:vr(e.base_borrow_rate),slope1:vr(e.slope1),slope2:vr(e.slope2),slope3:vr(e.slope3),midUtilization:vr(e.mid_utilization),optimalUtilization:vr(e.optimal_utilization),maxUtilization:vr(e.max_utilization),reserveFactor:Sr(e.reserve_factor),marketAddress:kr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:kr(e.asset),maxBorrowRateRay:vr(e.max_borrow_rate),baseBorrowRateRay:vr(e.base_borrow_rate),slope1Ray:vr(e.slope1),slope2Ray:vr(e.slope2),slope3Ray:vr(e.slope3),midUtilizationRay:vr(e.mid_utilization),optimalUtilizationRay:vr(e.optimal_utilization),maxUtilizationRay:vr(e.max_utilization),reserveFactorBps:Sr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ir(e).map((e=>{return t=Ir(e),{hubId:Sr(t[0]),asset:kr(t[1]),timestamp:Sr(t[2]),supplyIndexRay:vr(t[3]),borrowIndexRay:vr(t[4]),cash:vr(t[5]),suppliedRay:vr(t[6]),borrowedRay:vr(t[7]),revenueRay:vr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ir(e).map((e=>{const t=e;return{hubId:Sr(t.hub_id),asset:kr(t.asset),params:(r=t.params,{maxBorrowRateRay:vr(r.max_borrow_rate),baseBorrowRateRay:vr(r.base_borrow_rate),slope1Ray:vr(r.slope1),slope2Ray:vr(r.slope2),slope3Ray:vr(r.slope3),midUtilizationRay:vr(r.mid_utilization),optimalUtilizationRay:vr(r.optimal_utilization),maxUtilizationRay:vr(r.max_utilization),reserveFactorBps:Sr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Sr(r.flashloan_fee),assetId:kr(r.asset_id),assetDecimals:Sr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ir(e);return{topic:"position:batch_update",data:{accountId:vr(t[0]),accountAttributes:Er(Ir(t[1])),updates:[...Ir(t[2]).map((e=>Ar(Ir(e),"Deposit"))),...Ir(t[3]).map((e=>Ar(Ir(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Sr(e.hub_id),asset:kr(e.asset),receiver:kr(e.receiver),caller:kr(e.caller),amount:vr(e.amount),fee:vr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Nr(e.key),oracle:$r(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:kr(e.asset),oracle:$r(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:kr(e.liquidator),accountId:vr(e.account_id),repaidUsdWad:vr(e.repaid_usd_wad),bonusBps:vr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:vr(e.account_id),totalBorrowUsdWad:vr(e.total_borrow_usd_wad),totalCollateralUsdWad:vr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:kr(e.token),amount:vr(e.amount),usdValueWad:vr(e.usd_value_wad),accountId:vr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Sr(e.hub_id),asset:kr(e.asset),amount:vr(e.amount),fee:vr(e.fee),amountSent:vr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:kr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Rr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:kr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:kr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:kr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:kr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Rr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Sr(e.max_supply_positions),maxBorrowPositions:Sr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:vr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:kr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Sr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:vr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:vr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Sr(t.liquidation_bonus_factor_bps)}}}},Pr=Object.freeze(Object.keys(Or));function Ur(e,t){const r=yr(e),o=Or[r];return o?o(s(wr(t))):null}const Lr="XLENDXLM-a7c9f3",qr=1e4;function Wr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Lr}-${r}`}function zr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Dr(e,t=0){return 1e4*e+t}function Vr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Cr=(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()},Fr=e=>e.baseUrl??d[e.network];async function Mr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Cr(Fr(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 Gr(e){const t=Cr(Fr(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 Xr=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Hr=e=>O(e).toXDR("base64");function jr(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),c=q(Xr(a,t.referralId));return{xdr:new n(l,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",b(t.caller),w(t.totalIn),c)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function Jr(e,t){return jr(e,t)}function Qr(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(Yr),splitPpm:e.splitPpm}))):[{hops:e.hops.map(Yr),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function Kr(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:Qr(e,t)}const Zr=Qr,Yr=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function eo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function to(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw eo(r.invokedContractId,e);throw e}}async function ro(e,t,r){return to(e,t.xdr,r)}function oo(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 ao(e,t){return new Uint8Array(0)}const no=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(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(no(t.message)),i.ScVal.scvBytes(no(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const io={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 lo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=io[r];return o?{code:r,...o}:null}export{c as STELLAR_AGGREGATOR_ROUTER,u as STELLAR_GOVERNANCE,ft as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Pr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,qr as SYNTHETIC_EVENT_ORDER_STRIDE,Lr as XOXNO_LENDING_STELLAR_TICKER,ao as buildSameTokenRepaySwapSteps,Xe as buildStellarAcceptOwnershipTx,dt as buildStellarAddRewardsTx,Ze as buildStellarApproveBlendPoolTx,et as buildStellarApproveTokenTx,Jr as buildStellarBatchSwapTx,C as buildStellarBorrowBatchTx,F as buildStellarBorrowTx,so as buildStellarCctpForwardTx,pt as buildStellarClaimRevenueTx,ct as buildStellarCreateLiquidityPoolTx,ur as buildStellarExecuteCancellerResetTx,jr as buildStellarExecuteStrategyTx,J as buildStellarFlashLoanTx,fr as buildStellarGovernanceAddSpokeImmediateTx,mr as buildStellarGovernanceCreateHubImmediateTx,or as buildStellarGovernanceExecuteGovernanceUpgradeTx,nr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,sr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,ir as buildStellarGovernanceExecuteTransferGovOwnTx,rr as buildStellarGovernanceExecuteTx,ar as buildStellarGovernanceExecuteUpdateDelayTx,_r as buildStellarGovernancePauseTx,hr as buildStellarGovernanceRevokeRoleImmediateTx,dr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,pr as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Fe as buildStellarGrantRoleTx,Wr as buildStellarLendingIdentifier,j as buildStellarLiquidateTx,Q as buildStellarMigrateFromBlendTx,De as buildStellarMigrateTx,K as buildStellarMultiplyTx,Ve as buildStellarPauseTx,Nt as buildStellarProposeAddAssetToSpokeTx,Et as buildStellarProposeAddSpokeTx,zt as buildStellarProposeApproveBlendPoolTx,qt as buildStellarProposeApproveTokenTx,cr as buildStellarProposeCancellerResetTx,jt as buildStellarProposeConfigureAssetOracleTx,Jt as buildStellarProposeConfigureMarketOracleTx,At as buildStellarProposeCreateHubTx,Vt as buildStellarProposeCreateLiquidityPoolTx,Ft as buildStellarProposeDeployPoolTx,$t as buildStellarProposeEditAssetInSpokeTx,Qt as buildStellarProposeEditOracleToleranceTx,Kt as buildStellarProposeGovernanceUpgradeTx,Yt as buildStellarProposeGrantGovernanceRoleTx,Xt as buildStellarProposeMigrateControllerTx,Ot as buildStellarProposeRemoveAssetFromSpokeTx,Bt as buildStellarProposeRemoveSpokeTx,Dt as buildStellarProposeRevokeBlendPoolTx,er as buildStellarProposeRevokeGovernanceRoleTx,Wt as buildStellarProposeRevokeTokenTx,xt as buildStellarProposeSetAccumulatorTx,Tt as buildStellarProposeSetAggregatorTx,Lt as buildStellarProposeSetMinBorrowCollatTx,It as buildStellarProposeSetPositionLimitsTx,Ut as buildStellarProposeSetPositionManagerTx,Rt as buildStellarProposeSetPriceAggregatorTx,Pt as buildStellarProposeSetSpokeLiquidationCurveTx,kt as buildStellarProposeSetSwapAggregatorTx,Ht as buildStellarProposeTransferCtrlOwnershipTx,tr as buildStellarProposeTransferGovOwnTx,gr as buildStellarProposeUnpauseTx,Zt as buildStellarProposeUpdateDelayTx,Gt as buildStellarProposeUpgradeControllerTx,Ct as buildStellarProposeUpgradePoolParamsTx,Mt as buildStellarProposeUpgradePoolTx,lt as buildStellarRenewAccountTx,X as buildStellarRepayBatchTx,ee as buildStellarRepayDebtWithCollateralTx,H as buildStellarRepayTx,Ye as buildStellarRevokeBlendPoolTx,Me as buildStellarRevokeRoleTx,tt as buildStellarRevokeTokenTx,Qe as buildStellarSetAccumulatorTx,Je as buildStellarSetAggregatorTx,ot as buildStellarSetMarketOracleConfigTx,st as buildStellarSetOracleSanityBoundsTx,at as buildStellarSetOracleToleranceTx,rt as buildStellarSetOracleTx,Ke as buildStellarSetPositionLimitsTx,je as buildStellarSetPriceAggregatorTx,nt as buildStellarSetSpokeAssetFlagsTx,He as buildStellarSetSwapAggregatorTx,D as buildStellarSupplyBatchTx,V as buildStellarSupplyTx,Y as buildStellarSwapCollateralTx,Z as buildStellarSwapDebtTx,Ge as buildStellarTransferOwnershipTx,Ce as buildStellarUnpauseTx,mt as buildStellarUpdateAccountThresholdTx,it as buildStellarUpdateIndexesTx,ze as buildStellarUpgradeControllerTx,ut as buildStellarUpgradeLiquidityPoolParamsTx,M as buildStellarWithdrawBatchTx,G as buildStellarWithdrawTx,z as buildTx,Ur as decodeStellarLendingEvent,qe as encodeAssetOracle,xe as encodeInterestRateModel,We as encodeMarketOracleConfigInput,Ie as encodeMarketParamsRaw,Ae as encodePositionLimits,Ee as encodePriceKey,Hr as encodeStrategyPayloadToRouteXdr,zr as extractEventOrder,we as getStellarAccountPositions,Mr as getStellarAggregatorQuote,h as getStellarAggregatorRouter,de as getStellarAsset,ve as getStellarAssetGraph,fe as getStellarAssetMarkets,me as getStellarAssetPage,se as getStellarAssets,_ as getStellarGovernance,ye as getStellarGovernanceProposals,he as getStellarHub,Se as getStellarHubGraph,ie as getStellarHubs,ae as getStellarLendingContext,f as getStellarLendingController,ne as getStellarLendingLiveState,Gr as getStellarQuoteTokens,ue as getStellarReserve,Re as getStellarReserveGraph,pe as getStellarReserveHolders,ce as getStellarReserves,_e as getStellarSpoke,ke as getStellarSpokeGraph,le as getStellarSpokes,be as getStellarUserActivity,ge as getStellarUserPositions,Zr as mapQuoteResponseToAggregatorSwap,Qr as mapQuoteResponseToStrategyPayload,Kr as mapQuoteResponseToStrategySwap,lo as mapSorobanError,Vr as mapStellarPositionActivityType,ro as prepareStellarBuiltTx,to as prepareStellarTxXdr,yr as stellarLendingDispatchKey,Te as stellarLendingRead,Dr as syntheticEventOrder,eo as tagStellarInvokedContractError,br as toBase64Xdr,oo 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),I=e=>i.ScVal.scvString(e),T=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)},B=(e,t)=>null==e?x():t(e),$=(e,t)=>O({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([$(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:T(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))})},q=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)),z=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return 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},D=e=>{if("string"==typeof e)return q(z(e));if(e instanceof Uint8Array)return 0===e.length?W():q(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?q(z(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?q(z(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?q(z(e.bytes)):0===e.bytes.length?W():q(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]),B(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]),B(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),$(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),$(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),$(t.debt.hubId,t.debt.asset),v(t.mode),D(t.steps),B(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),B(t.convertSwap,D)])}function te(e,t){return C(e,"swap_debt",[y(e.caller),k(t.accountNonce),$(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),$(t.newDebt.hubId,t.newDebt.asset),D(t.steps)])}function re(e,t){return C(e,"swap_collateral",[y(e.caller),k(t.accountNonce),$(t.current.hubId,t.current.asset),S(t.fromAmount),$(t.newCollateral.hubId,t.newCollateral.asset),D(t.steps)])}function oe(e,t){return C(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),$(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),$(t.debt.hubId,t.debt.asset),D(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}}),Ie=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/hubs/${t}/graph`,{...o,params:{...r}}),Te=(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=>({context:t=>ie(e,t),liveState:t=>le(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)=>Ie(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)}),Ee=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)}),Be=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)}),$e=e=>O({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),Ne=e=>{if("Token"in e&&e.Token)return A([T("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([T("Ref"),T(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Pe=e=>{if("Stellar"in e)return A([T("Stellar"),y(e.Stellar)]);if("Symbol"in e)return A([T("Symbol"),T(e.Symbol)]);if("String"in e)return A([T("String"),I(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Oe=e=>{if("Spot"===e)return A([T("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return A([T("Twap"),v(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ue=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([T(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Le=e=>{if("Market"===e||"Fundamental"===e)return A([T(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},qe=e=>{if("Reflector"in e){const t=e.Reflector;return A([T("Reflector"),O({asset:Pe(t.asset),contract:y(t.contract),read_mode:Oe(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([T("MultiFeed"),O({contract:y(t.contract),feed_id:I(t.feedId),kind:Ue(t.kind),nature:Le(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},We=e=>{const t=e;return O({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:qe(t.provider)})},ze=e=>{if("RequireDisjoint"===e)return A([T("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([T("AllowShared"),A(t.map((e=>O({contract:y(e.contract),kind:Ue(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},De=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:ze(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([T("Feed"),We(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([T("Scaled"),O({factor:We(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:Ne(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([T("LpShare"),O({key_a:Ne(t.keyA),key_b:Ne(t.keyB),kind:A([T(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)})})},Ve=De;function Ce(e,t){return C(e,"upgrade",[E(t.wasmHash)])}function Me(e,t){return C(e,"migrate",[v(t.newVersion)])}function Fe(e){return C(e,"pause",[])}function Ge(e){return C(e,"unpause",[])}function Xe(e,t){return C(e,"grant_role",[y(t.account),T(t.role)])}function He(e,t){return C(e,"revoke_role",[y(t.account),T(t.role)])}function je(e,t){return C(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function Je(e){return C(e,"accept_ownership",[])}function Qe(e,t){return C(e,"set_swap_aggregator",[y(t.aggregator)])}function Ke(e,t){return C(e,"set_price_aggregator",[y(t.aggregator)])}const Ze=Qe;function Ye(e,t){return C(e,"set_accumulator",[y(t.accumulator)])}function et(e,t){return C(e,"set_position_limits",[$e(t)])}function tt(e,t){return C(e,"approve_blend_pool",[y(t.pool)])}function rt(e,t){return C(e,"revoke_blend_pool",[y(t.pool)])}const ot=tt,at=rt;function nt(e,t){return C(e,"set_oracle",[Ne(t.key),De(t.oracle)])}const st=nt;function it(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",[Ne(t.key),O({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function lt(e,t){return C(e,"set_spoke_asset_flags",[v(t.spokeId),$(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function ut(e,t){return C(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function ct(e,t){return C(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>$(e.hubId,e.asset))))])}function pt(e,t){return C(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function dt(e,t){return C(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),Be(t.params)])}function mt(e,t){return C(e,"upgrade_liquidity_pool_params",[$(t.hubId,t.asset),Ee(t.params)])}function ft(e,t){return C(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>$(e.hubId,e.asset))))])}function ht(e,t){return C(e,"add_rewards",[y(e.caller),P(t.rewards)])}function gt(e,t){return C(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const wt="00".repeat(32),_t=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)},bt=(e,...t)=>A([T(e),...t]),yt=e=>O({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),St=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([T("None")]),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),vt=e=>O({account:y(e.account),role:T(e.role)});function kt(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 Rt=(e,t,r)=>kt(e,"propose",[y(e.caller),t,_t(r)]),It=(e,t,r)=>kt(e,"execute_self",[x(),t,_t(r)]);function Tt(e,t,r){return Rt(e,bt("SetSwapAggregator",y(t.aggregator)),r)}function xt(e,t,r){return Rt(e,bt("SetPriceAggregator",y(t.aggregator)),r)}const At=Tt;function Et(e,t,r){return Rt(e,bt("SetAccumulator",y(t.accumulator)),r)}function Bt(e,t,r){return Rt(e,bt("SetPositionLimits",$e(t)),r)}function $t(e,t){return Rt(e,bt("CreateHub"),t)}function Nt(e,t){return Rt(e,bt("AddSpoke"),t)}function Pt(e,t,r){return Rt(e,bt("RemoveSpoke",v(t.spokeId)),r)}function Ot(e,t,r){return Rt(e,bt("AddAssetToSpoke",St(t)),r)}function Ut(e,t,r){return Rt(e,bt("EditAssetInSpoke",St(t)),r)}function Lt(e,t,r){return Rt(e,bt("RemoveAssetFromSpoke",O({hub_asset:$((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function qt(e,t,r){return Rt(e,bt("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 Wt(e,t,r){return Rt(e,bt("SetPositionManager",y(t.manager),R(t.isActive)),r)}function zt(e,t,r){return Rt(e,bt("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Dt(e,t,r){return Rt(e,bt("ApproveToken",y(t.token)),r)}function Vt(e,t,r){return Rt(e,bt("RevokeToken",y(t.token)),r)}function Ct(e,t,r){return Rt(e,bt("ApproveBlendPool",y(t.pool)),r)}function Mt(e,t,r){return Rt(e,bt("RevokeBlendPool",y(t.pool)),r)}function Ft(e,t,r){return Rt(e,bt("CreateLiquidityPool",O({asset:y((o=t).asset),hub_id:v(o.hubId),params:Be(o.params)})),r);var o}function Gt(e,t,r){return Rt(e,bt("UpgradeLiquidityPoolParams",O({hub_asset:$((o=t).hubId,o.asset),params:Ee(o.params)})),r);var o}function Xt(e,t,r){return Rt(e,bt("DeployPool",E(t.wasmHash)),r)}function Ht(e,t,r){return Rt(e,bt("UpgradePool",E(t.wasmHash)),r)}function jt(e,t,r){return Rt(e,bt("UpgradeController",E(t.wasmHash)),r)}function Jt(e,t,r){return Rt(e,bt("MigrateController",v(t.newVersion)),r)}function Qt(e,t,r){return Rt(e,bt("TransferCtrlOwnership",yt(t)),r)}function Kt(e,t,r){return Rt(e,bt("ConfigureAssetOracle",O({key:Ne((o=t).key),oracle:De(o.oracle)})),r);var o}const Zt=Kt;function Yt(e,t,r){return Rt(e,bt("EditOracleTolerance",O({key:Ne((o=t).key),tolerance:v(o.tolerance)})),r);var o}function er(e,t,r){return Rt(e,bt("UpgradeGov",E(t.wasmHash)),r)}function tr(e,t,r){return Rt(e,bt("UpdateGovDelay",v(t.newDelay)),r)}function rr(e,t,r){return Rt(e,bt("GrantGovRole",vt(t)),r)}function or(e,t,r){return Rt(e,bt("RevokeGovRole",vt(t)),r)}function ar(e,t,r){return Rt(e,bt("TransferGovOwnership",yt(t)),r)}function nr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=_t(t.predecessor??wt);return kt(e,"execute",[x(),y(t.target),T(t.functionName),r,o,_t(t.salt)])}function sr(e,t,r){return It(e,bt("UpgradeGov",E(t.wasmHash)),r)}function ir(e,t,r){return It(e,bt("UpdateGovDelay",v(t.newDelay)),r)}function lr(e,t,r){return It(e,bt("GrantGovRole",vt(t)),r)}function ur(e,t,r){return It(e,bt("RevokeGovRole",vt(t)),r)}function cr(e,t,r){return It(e,bt("TransferGovOwnership",yt(t)),r)}const pr=e=>A(e.map(y));function dr(e,t,r){return kt(e,"propose_canceller_reset",[pr(t.newCancellers),_t(r)])}function mr(e,t,r){return kt(e,"execute_canceller_reset",[B(t.executor,y),pr(t.newCancellers),_t(r)])}function fr(e,t){return kt(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),$(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function hr(e,t){return kt(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function gr(e){return kt(e,"create_hub",[y(e.caller)])}function wr(e){return kt(e,"add_spoke",[y(e.caller)])}function _r(e,t){return kt(e,"revoke_role_immediate",[y(t.account),T(t.role)])}function br(e){return kt(e,"pause",[y(e.caller)])}function yr(e,t){return Rt(e,bt("Unpause"),t)}const Sr=e=>e.toXDR("base64"),vr=e=>i.ScVal.fromXDR(e,"base64"),kr=e=>e.map((e=>String(s(vr(e))))).join(":"),Rr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Ir=e=>Number(e),Tr=e=>String(e),xr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ar=["None","Multiply","Long","Short"],Er=["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"],Br=e=>Array.isArray(e)?e:[],$r=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Er[Ir(o)]??Rr(o)),positionType:t,hubId:Ir(e[1]),asset:Tr(e[2]),scaledAmountRay:Rr(e[3]),indexRay:Rr(e[4]),amount:Rr(e[5]),liquidationThresholdBps:r?void 0:Ir(e[6]),liquidationBonusBps:r?void 0:Ir(e[7]),loanToValueBps:r?void 0:Ir(e[8]),liquidationFeesBps:r?void 0:Ir(e[9])};var o},Nr=e=>{return{owner:Tr(e[0]),spokeId:Ir(e[1]),mode:(t=e[2],Ar[Ir(t)]??"None")};var t},Pr=e=>Array.isArray(e)?e[1]:void 0,Or=e=>{const t=(r=e,Array.isArray(r)?Tr(r[0]):Tr(r));var r;if("Token"===t)return{Token:Tr(Pr(e))};if("Ref"===t)return{Ref:Tr(Pr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Tr(t.Token)};if(void 0!==t.Ref)return{Ref:Tr(t.Ref)}}return{Token:Tr(e)}},Ur=e=>{const t=e.tolerance??{};return{assetDecimals:Ir(e.asset_decimals),maxPriceStaleSeconds:Ir(e.max_price_stale_seconds),sources:Br(e.sources).map((e=>e)),tolerance:{upperRatio:Ir(t.upper_ratio_bps),lowerRatio:Ir(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Rr(e.min_sanity_price_wad),maxSanityPriceWad:Rr(e.max_sanity_price_wad)}},Lr={"market:create":e=>({topic:"market:create",data:{hubId:Ir(e.hub_id),baseAsset:Tr(e.base_asset),maxBorrowRate:Rr(e.max_borrow_rate),baseBorrowRate:Rr(e.base_borrow_rate),slope1:Rr(e.slope1),slope2:Rr(e.slope2),slope3:Rr(e.slope3),midUtilization:Rr(e.mid_utilization),optimalUtilization:Rr(e.optimal_utilization),maxUtilization:Rr(e.max_utilization),reserveFactor:Ir(e.reserve_factor),marketAddress:Tr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Tr(e.asset),maxBorrowRateRay:Rr(e.max_borrow_rate),baseBorrowRateRay:Rr(e.base_borrow_rate),slope1Ray:Rr(e.slope1),slope2Ray:Rr(e.slope2),slope3Ray:Rr(e.slope3),midUtilizationRay:Rr(e.mid_utilization),optimalUtilizationRay:Rr(e.optimal_utilization),maxUtilizationRay:Rr(e.max_utilization),reserveFactorBps:Ir(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Br(e).map((e=>{return t=Br(e),{hubId:Ir(t[0]),asset:Tr(t[1]),timestamp:Ir(t[2]),supplyIndexRay:Rr(t[3]),borrowIndexRay:Rr(t[4]),cash:Rr(t[5]),suppliedRay:Rr(t[6]),borrowedRay:Rr(t[7]),revenueRay:Rr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Br(e).map((e=>{const t=e;return{hubId:Ir(t.hub_id),asset:Tr(t.asset),params:(r=t.params,{maxBorrowRateRay:Rr(r.max_borrow_rate),baseBorrowRateRay:Rr(r.base_borrow_rate),slope1Ray:Rr(r.slope1),slope2Ray:Rr(r.slope2),slope3Ray:Rr(r.slope3),midUtilizationRay:Rr(r.mid_utilization),optimalUtilizationRay:Rr(r.optimal_utilization),maxUtilizationRay:Rr(r.max_utilization),reserveFactorBps:Ir(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Ir(r.flashloan_fee),assetId:Tr(r.asset_id),assetDecimals:Ir(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Br(e);return{topic:"position:batch_update",data:{accountId:Rr(t[0]),accountAttributes:Nr(Br(t[1])),updates:[...Br(t[2]).map((e=>$r(Br(e),"Deposit"))),...Br(t[3]).map((e=>$r(Br(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Ir(e.hub_id),asset:Tr(e.asset),receiver:Tr(e.receiver),caller:Tr(e.caller),amount:Rr(e.amount),fee:Rr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Or(e.key),oracle:Ur(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Tr(e.asset),oracle:Ur(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Tr(e.liquidator),accountId:Rr(e.account_id),repaidUsdWad:Rr(e.repaid_usd_wad),bonusBps:Rr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Rr(e.account_id),totalBorrowUsdWad:Rr(e.total_borrow_usd_wad),totalCollateralUsdWad:Rr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Tr(e.token),amount:Rr(e.amount),usdValueWad:Rr(e.usd_value_wad),accountId:Rr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Ir(e.hub_id),asset:Tr(e.asset),amount:Rr(e.amount),fee:Rr(e.fee),amountSent:Rr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Tr(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:xr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Tr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Tr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Tr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Tr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:xr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Ir(e.max_supply_positions),maxBorrowPositions:Ir(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Rr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Tr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Ir(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Rr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Rr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Ir(t.liquidation_bonus_factor_bps)}}}},qr=Object.freeze(Object.keys(Lr));function Wr(e,t){const r=kr(e),o=Lr[r];return o?o(s(vr(t))):null}const zr="XLENDXLM-a7c9f3",Dr=1e4;function Vr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${zr}-${r}`}function Cr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Mr(e,t=0){return 1e4*e+t}function Fr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Gr=(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()},Xr=e=>e.baseUrl??d[e.network];async function Hr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Gr(Xr(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 jr(e){const t=Gr(Xr(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 Jr=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Qr=e=>L(e).toXDR("base64");function Kr(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=D(Jr(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 Zr(e,t){return Kr(e,t)}function Yr(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(ro),splitPpm:e.splitPpm}))):[{hops:e.hops.map(ro),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function eo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:Yr(e,t)}const to=Yr,ro=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function oo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function ao(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw oo(r.invokedContractId,e);throw e}}async function no(e,t,r){return ao(e,t.xdr,r)}function so(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 io(e,t){return new Uint8Array(0)}const lo=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 uo(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(lo(t.message)),i.ScVal.scvBytes(lo(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const co={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 po(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=co[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,wt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,qr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Dr as SYNTHETIC_EVENT_ORDER_STRIDE,zr as XOXNO_LENDING_STELLAR_TICKER,io as buildSameTokenRepaySwapSteps,Je as buildStellarAcceptOwnershipTx,ht as buildStellarAddRewardsTx,tt as buildStellarApproveBlendPoolTx,ot as buildStellarApproveTokenTx,Zr as buildStellarBatchSwapTx,G as buildStellarBorrowBatchTx,X as buildStellarBorrowTx,uo as buildStellarCctpForwardTx,ft as buildStellarClaimRevenueTx,dt as buildStellarCreateLiquidityPoolTx,mr as buildStellarExecuteCancellerResetTx,Kr as buildStellarExecuteStrategyTx,Z as buildStellarFlashLoanTx,wr as buildStellarGovernanceAddSpokeImmediateTx,gr as buildStellarGovernanceCreateHubImmediateTx,sr as buildStellarGovernanceExecuteGovernanceUpgradeTx,lr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,ur as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,cr as buildStellarGovernanceExecuteTransferGovOwnTx,nr as buildStellarGovernanceExecuteTx,ir as buildStellarGovernanceExecuteUpdateDelayTx,br as buildStellarGovernancePauseTx,_r as buildStellarGovernanceRevokeRoleImmediateTx,hr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,fr as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Xe as buildStellarGrantRoleTx,Vr as buildStellarLendingIdentifier,K as buildStellarLiquidateTx,Y as buildStellarMigrateFromBlendTx,Me as buildStellarMigrateTx,ee as buildStellarMultiplyTx,Fe as buildStellarPauseTx,Ot as buildStellarProposeAddAssetToSpokeTx,Nt as buildStellarProposeAddSpokeTx,Ct as buildStellarProposeApproveBlendPoolTx,Dt as buildStellarProposeApproveTokenTx,dr as buildStellarProposeCancellerResetTx,Kt as buildStellarProposeConfigureAssetOracleTx,Zt as buildStellarProposeConfigureMarketOracleTx,$t as buildStellarProposeCreateHubTx,Ft as buildStellarProposeCreateLiquidityPoolTx,Xt as buildStellarProposeDeployPoolTx,Ut as buildStellarProposeEditAssetInSpokeTx,Yt as buildStellarProposeEditOracleToleranceTx,er as buildStellarProposeGovernanceUpgradeTx,rr as buildStellarProposeGrantGovernanceRoleTx,Jt as buildStellarProposeMigrateControllerTx,Lt as buildStellarProposeRemoveAssetFromSpokeTx,Pt as buildStellarProposeRemoveSpokeTx,Mt as buildStellarProposeRevokeBlendPoolTx,or as buildStellarProposeRevokeGovernanceRoleTx,Vt as buildStellarProposeRevokeTokenTx,Et as buildStellarProposeSetAccumulatorTx,At as buildStellarProposeSetAggregatorTx,zt as buildStellarProposeSetMinBorrowCollatTx,Bt as buildStellarProposeSetPositionLimitsTx,Wt as buildStellarProposeSetPositionManagerTx,xt as buildStellarProposeSetPriceAggregatorTx,qt as buildStellarProposeSetSpokeLiquidationCurveTx,Tt as buildStellarProposeSetSwapAggregatorTx,Qt as buildStellarProposeTransferCtrlOwnershipTx,ar as buildStellarProposeTransferGovOwnTx,yr as buildStellarProposeUnpauseTx,tr as buildStellarProposeUpdateDelayTx,jt as buildStellarProposeUpgradeControllerTx,Gt as buildStellarProposeUpgradePoolParamsTx,Ht as buildStellarProposeUpgradePoolTx,pt as buildStellarRenewAccountTx,J as buildStellarRepayBatchTx,oe as buildStellarRepayDebtWithCollateralTx,Q as buildStellarRepayTx,rt as buildStellarRevokeBlendPoolTx,He as buildStellarRevokeRoleTx,at as buildStellarRevokeTokenTx,Ye as buildStellarSetAccumulatorTx,Ze as buildStellarSetAggregatorTx,st as buildStellarSetMarketOracleConfigTx,ut as buildStellarSetOracleSanityBoundsTx,it as buildStellarSetOracleToleranceTx,nt as buildStellarSetOracleTx,et as buildStellarSetPositionLimitsTx,Ke as buildStellarSetPriceAggregatorTx,lt as buildStellarSetSpokeAssetFlagsTx,Qe as buildStellarSetSwapAggregatorTx,M as buildStellarSupplyBatchTx,F as buildStellarSupplyTx,re as buildStellarSwapCollateralTx,te as buildStellarSwapDebtTx,je as buildStellarTransferOwnershipTx,Ge as buildStellarUnpauseTx,gt as buildStellarUpdateAccountThresholdTx,ct as buildStellarUpdateIndexesTx,Ce as buildStellarUpgradeControllerTx,mt as buildStellarUpgradeLiquidityPoolParamsTx,H as buildStellarWithdrawBatchTx,j as buildStellarWithdrawTx,C as buildTx,Wr as decodeStellarLendingEvent,De as encodeAssetOracle,Ee as encodeInterestRateModel,Ve as encodeMarketOracleConfigInput,Be as encodeMarketParamsRaw,$e as encodePositionLimits,Ne as encodePriceKey,Qr as encodeStrategyPayloadToRouteXdr,Cr as extractEventOrder,ve as getStellarAccountPositions,Hr as getStellarAggregatorQuote,h as getStellarAggregatorRouter,he as getStellarAsset,Re as getStellarAssetGraph,we as getStellarAssetMarkets,ge as getStellarAssetPage,ue as getStellarAssets,g as getStellarGovernance,ke as getStellarGovernanceProposals,_e as getStellarHub,Ie as getStellarHubGraph,ce as getStellarHubs,ie as getStellarLendingContext,f as getStellarLendingController,le as getStellarLendingLiveState,jr as getStellarQuoteTokens,me as getStellarReserve,xe as getStellarReserveGraph,fe as getStellarReserveHolders,de as getStellarReserves,be as getStellarSpoke,Te as getStellarSpokeGraph,pe as getStellarSpokes,Se as getStellarUserActivity,ye as getStellarUserPositions,to as mapQuoteResponseToAggregatorSwap,Yr as mapQuoteResponseToStrategyPayload,eo as mapQuoteResponseToStrategySwap,po as mapSorobanError,Fr as mapStellarPositionActivityType,no as prepareStellarBuiltTx,ao as prepareStellarTxXdr,kr as stellarLendingDispatchKey,Ae as stellarLendingRead,Mr as syntheticEventOrder,oo as tagStellarInvokedContractError,Sr as toBase64Xdr,so as toStellarPositionMode};
@@ -8,12 +8,22 @@
8
8
  import { xdr } from '@stellar/stellar-sdk';
9
9
  /**
10
10
  * On-chain swap venues, validated at runtime for a caller-supplied venue.
11
- * Mirrors the Soroban-only aggregator router's `SwapVenue` enum.
11
+ * Mirrors the Soroban-only aggregator router's opcode table.
12
12
  */
13
13
  export declare const STELLAR_SWAP_VENUES: readonly ["Soroswap", "Aquarius", "Phoenix", "Sushi", "CometDex"];
14
14
  export type StellarSwapVenue = (typeof STELLAR_SWAP_VENUES)[number];
15
+ /**
16
+ * Instruction opcode per venue. Part of the on-chain ABI — see
17
+ * `contracts/swap-aggregator/src/program.rs`.
18
+ */
19
+ export declare const STELLAR_SWAP_VENUE_OPCODE: Record<StellarSwapVenue, number>;
20
+ /** Wire version of the packed program. Must match the contract's `VERSION`. */
21
+ export declare const STELLAR_PROGRAM_VERSION = 1;
22
+ /** Split weights are parts per million. */
23
+ export declare const PPM_DENOMINATOR = 1000000;
15
24
  export interface StellarStrategySwapHopInput {
16
- amountOut: string;
25
+ /** Quote-side estimate; not carried on the wire. */
26
+ amountOut?: string;
17
27
  pool: string;
18
28
  tokenIn: string;
19
29
  tokenOut: string;
@@ -21,10 +31,25 @@ export interface StellarStrategySwapHopInput {
21
31
  }
22
32
  export interface StellarStrategySwapPathInput {
23
33
  hops: StellarStrategySwapHopInput[];
34
+ /** Absolute share of this path's starting-token balance, in ppm. */
24
35
  splitPpm: number;
25
36
  }
26
37
  export interface StellarStrategyPayloadInput {
38
+ /** Aquarius pool whose LP shares (`tokenIn`) are burned before routing. */
39
+ burnPool?: string;
40
+ /** Per-constituent floors for the burn, in the pool's own token order. */
41
+ burnMinAmounts?: string[];
42
+ /** Aquarius pool that mints `tokenOut` from the routed constituents. */
43
+ mintPool?: string;
44
+ /** Minimum LP shares the mint must deliver. */
45
+ mintMinShares?: string;
46
+ /** Constituents of `mintPool`, in pool order. Required with `preSwapAmount`. */
47
+ mintPoolTokens?: string[];
27
48
  paths: StellarStrategySwapPathInput[];
49
+ /** Caller-solved amount that balances a lopsided mint before the deposit. */
50
+ preSwapAmount?: string;
51
+ /** Pre-swap direction: pool token A into B when true, B into A when false. */
52
+ preSwapFromA?: boolean;
28
53
  referralId?: number | string;
29
54
  tokenIn: string;
30
55
  tokenOut: string;
@@ -99,13 +124,8 @@ export declare const tupleHubAssetAmountVec: (entries: Array<{
99
124
  */
100
125
  export declare const scStruct: (fields: Record<string, xdr.ScVal>) => xdr.ScVal;
101
126
  /**
102
- * Encode a Soroban `enum SwapVenue` (tag-only / unit variant). At the XDR level
103
- * a unit variant is `scvVec([symbol_name])`.
104
- */
105
- export declare const encodeSwapVenue: (venue: StellarSwapVenue) => xdr.ScVal;
106
- /**
107
- * Encode the aggregator router's decoded `StrategyPayload` struct. The caller
108
- * usually receives this as quote `routeXdr`; this helper is for tests and for
127
+ * Encode the aggregator router's `StrategyPayload`. The caller usually receives
128
+ * this already encoded as quote `routeXdr`; this helper is for tests and for
109
129
  * callers that construct routes locally.
110
130
  */
111
131
  export declare const encodeStrategyPayload: (payload: StellarStrategyPayloadInput) => xdr.ScVal;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xoxno/sdk-js",
3
- "version": "1.0.201",
3
+ "version": "1.0.202",
4
4
  "description": "The SDK to interact with the XOXNO Protocol!",
5
5
  "type": "module",
6
6
  "exports": {