@xoxno/sdk-js 1.0.201 → 1.0.203
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/stellar/__tests__/strategy-program.test.d.ts +9 -0
- package/dist/cjs/sdk/stellar/lending-read-types.d.ts +63 -0
- package/dist/cjs/sdk/stellar/lending-read.d.ts +26 -1
- package/dist/cjs/sdk/stellar/scval-encode.d.ts +29 -9
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/sdk/stellar/__tests__/strategy-program.test.d.ts +9 -0
- package/dist/sdk/stellar/index.cjs +1 -1
- package/dist/sdk/stellar/index.esm.js +1 -1
- package/dist/sdk/stellar/lending-read-types.d.ts +63 -0
- package/dist/sdk/stellar/lending-read.d.ts +26 -1
- package/dist/sdk/stellar/scval-encode.d.ts +29 -9
- package/package.json +1 -1
|
@@ -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:()=>bt,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>zr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>Hr,XOXNO_LENDING_STELLAR_TICKER:()=>Xr,buildSameTokenRepaySwapSteps:()=>ho,buildStellarAcceptOwnershipTx:()=>Je,buildStellarAddRewardsTx:()=>gt,buildStellarApproveBlendPoolTx:()=>rt,buildStellarApproveTokenTx:()=>at,buildStellarBatchSwapTx:()=>no,buildStellarBorrowBatchTx:()=>W,buildStellarBorrowTx:()=>M,buildStellarCctpForwardTx:()=>So,buildStellarClaimRevenueTx:()=>ht,buildStellarCreateLiquidityPoolTx:()=>mt,buildStellarExecuteCancellerResetTx:()=>wr,buildStellarExecuteStrategyTx:()=>ao,buildStellarFlashLoanTx:()=>j,buildStellarGovernanceAddSpokeImmediateTx:()=>vr,buildStellarGovernanceCreateHubImmediateTx:()=>xr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>mr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>hr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>gr,buildStellarGovernanceExecuteTransferGovOwnTx:()=>Sr,buildStellarGovernanceExecuteTx:()=>pr,buildStellarGovernanceExecuteUpdateDelayTx:()=>fr,buildStellarGovernancePauseTx:()=>Rr,buildStellarGovernanceRevokeRoleImmediateTx:()=>kr,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>Tr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>yr,buildStellarGrantRoleTx:()=>He,buildStellarLendingIdentifier:()=>jr,buildStellarLiquidateTx:()=>H,buildStellarMigrateFromBlendTx:()=>Q,buildStellarMigrateTx:()=>ze,buildStellarMultiplyTx:()=>J,buildStellarPauseTx:()=>Fe,buildStellarProposeAddAssetToSpokeTx:()=>Wt,buildStellarProposeAddSpokeTx:()=>Dt,buildStellarProposeApproveBlendPoolTx:()=>Qt,buildStellarProposeApproveTokenTx:()=>Ht,buildStellarProposeCancellerResetTx:()=>_r,buildStellarProposeConfigureAssetOracleTx:()=>ar,buildStellarProposeConfigureMarketOracleTx:()=>nr,buildStellarProposeCreateHubTx:()=>Gt,buildStellarProposeCreateLiquidityPoolTx:()=>Kt,buildStellarProposeDeployPoolTx:()=>Yt,buildStellarProposeEditAssetInSpokeTx:()=>Mt,buildStellarProposeEditOracleToleranceTx:()=>sr,buildStellarProposeGovernanceUpgradeTx:()=>ir,buildStellarProposeGrantGovernanceRoleTx:()=>ur,buildStellarProposeMigrateControllerTx:()=>rr,buildStellarProposeRemoveAssetFromSpokeTx:()=>Vt,buildStellarProposeRemoveSpokeTx:()=>qt,buildStellarProposeRevokeBlendPoolTx:()=>Jt,buildStellarProposeRevokeGovernanceRoleTx:()=>cr,buildStellarProposeRevokeTokenTx:()=>jt,buildStellarProposeSetAccumulatorTx:()=>Ct,buildStellarProposeSetAggregatorTx:()=>$t,buildStellarProposeSetMinBorrowCollatTx:()=>Xt,buildStellarProposeSetPositionLimitsTx:()=>Ut,buildStellarProposeSetPositionManagerTx:()=>Ft,buildStellarProposeSetPriceAggregatorTx:()=>Lt,buildStellarProposeSetSpokeLiquidationCurveTx:()=>zt,buildStellarProposeSetSwapAggregatorTx:()=>Nt,buildStellarProposeTransferCtrlOwnershipTx:()=>or,buildStellarProposeTransferGovOwnTx:()=>dr,buildStellarProposeUnpauseTx:()=>Ar,buildStellarProposeUpdateDelayTx:()=>lr,buildStellarProposeUpgradeControllerTx:()=>tr,buildStellarProposeUpgradePoolParamsTx:()=>Zt,buildStellarProposeUpgradePoolTx:()=>er,buildStellarRenewAccountTx:()=>pt,buildStellarRepayBatchTx:()=>F,buildStellarRepayDebtWithCollateralTx:()=>Y,buildStellarRepayTx:()=>X,buildStellarRevokeBlendPoolTx:()=>ot,buildStellarRevokeRoleTx:()=>je,buildStellarRevokeTokenTx:()=>nt,buildStellarSetAccumulatorTx:()=>et,buildStellarSetAggregatorTx:()=>Ye,buildStellarSetMarketOracleConfigTx:()=>it,buildStellarSetOracleSanityBoundsTx:()=>ct,buildStellarSetOracleToleranceTx:()=>lt,buildStellarSetOracleTx:()=>st,buildStellarSetPositionLimitsTx:()=>tt,buildStellarSetPriceAggregatorTx:()=>Ze,buildStellarSetSpokeAssetFlagsTx:()=>ut,buildStellarSetSwapAggregatorTx:()=>Ke,buildStellarSupplyBatchTx:()=>D,buildStellarSupplyTx:()=>q,buildStellarSwapCollateralTx:()=>Z,buildStellarSwapDebtTx:()=>K,buildStellarTransferOwnershipTx:()=>Qe,buildStellarUnpauseTx:()=>Xe,buildStellarUpdateAccountThresholdTx:()=>St,buildStellarUpdateIndexesTx:()=>dt,buildStellarUpgradeControllerTx:()=>Ve,buildStellarUpgradeLiquidityPoolParamsTx:()=>ft,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>z,buildTx:()=>G,decodeStellarLendingEvent:()=>Fr,encodeAssetOracle:()=>We,encodeInterestRateModel:()=>Ie,encodeMarketOracleConfigInput:()=>Me,encodeMarketParamsRaw:()=>Be,encodePositionLimits:()=>Oe,encodePriceKey:()=>Ne,encodeStrategyPayloadToRouteXdr:()=>oo,extractEventOrder:()=>Qr,getStellarAccountDelegates:()=>Ae,getStellarAccountPositions:()=>be,getStellarAggregatorQuote:()=>eo,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>de,getStellarAssetGraph:()=>we,getStellarAssetMarkets:()=>me,getStellarAssetPage:()=>pe,getStellarAssets:()=>ne,getStellarBlendPools:()=>Pe,getStellarContractConfig:()=>ke,getStellarContractRoles:()=>Re,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>_e,getStellarHub:()=>fe,getStellarHubGraph:()=>ye,getStellarHubs:()=>se,getStellarLendingContext:()=>oe,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>ae,getStellarProtocolConfig:()=>ve,getStellarQuoteTokens:()=>to,getStellarReserve:()=>ue,getStellarReserveGraph:()=>xe,getStellarReserveHolders:()=>ce,getStellarReserves:()=>le,getStellarSpoke:()=>he,getStellarSpokeGraph:()=>Te,getStellarSpokes:()=>ie,getStellarUserActivity:()=>Se,getStellarUserPositions:()=>ge,mapQuoteResponseToAggregatorSwap:()=>lo,mapQuoteResponseToStrategyPayload:()=>so,mapQuoteResponseToStrategySwap:()=>io,mapSorobanError:()=>_o,mapStellarPositionActivityType:()=>Kr,prepareStellarBuiltTx:()=>mo,prepareStellarTxXdr:()=>po,stellarLendingDispatchKey:()=>Ir,stellarLendingRead:()=>Ee,syntheticEventOrder:()=>Jr,tagStellarInvokedContractError:()=>co,toBase64Xdr:()=>Pr,toStellarPositionMode:()=>fo});const r={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},o={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},a={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},n={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},s={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},i={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function l(e){const t=r[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function u(e){const t=o[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function c(e){const t=a[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const d=require("@stellar/stellar-sdk"),p=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],m={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},f=1e6,h=e=>new d.Address(e).toScVal(),g=e=>new d.ScInt(e).toI128(),S=e=>d.xdr.ScVal.scvU32(e),b=e=>new d.ScInt("string"==typeof e?e:e.toString()).toU64(),_=e=>d.xdr.ScVal.scvBool(e),w=e=>d.xdr.ScVal.scvString(e),y=e=>d.xdr.ScVal.scvSymbol(e),T=()=>d.xdr.ScVal.scvVoid(),x=e=>d.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return d.xdr.ScVal.scvBytes(o)},k=(e,t)=>null==e?T():t(e),R=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([h(t),g(r)]);var t,r}))),A=(e,t)=>I({asset:h(t),hub_id:S(e)}),P=(e,t,r)=>d.xdr.ScVal.scvVec([A(e,t),g(r)]),E=e=>d.xdr.ScVal.scvVec(e.map((e=>P(e.hubId,e.asset,e.amount)))),I=e=>{const t=Object.keys(e).sort().map((t=>new d.xdr.ScMapEntry({key:y(t),val:e[t]})));return d.xdr.ScVal.scvMap(t)};class B{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>f)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(m[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>f)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===f;let i=f;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*f/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const O=e=>{const t=new B(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(m.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return I({amounts:d.xdr.ScVal.scvVec(t.amountList.map((e=>g(e)))),assets:d.xdr.ScVal.scvVec(t.assetList.map((e=>h(e)))),ops:d.xdr.ScVal.scvBytes(t.toBytes(r,o,a))})},N=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return d.xdr.ScVal.scvBytes(t)},L=()=>d.xdr.ScVal.scvBytes(Buffer.alloc(0)),$=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},C=e=>{if("string"==typeof e)return N($(e));if(e instanceof Uint8Array)return 0===e.length?L():N(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?N($(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?N($(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?N($(e.bytes)):0===e.bytes.length?L():N(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!p.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(O(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},U=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return d.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return d.xdr.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function G(e,t,r){const o=e.controllerAddress??l(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return G(e,"supply",[h(e.caller),b(r),S(o),E([...t.assets])])}function q(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function W(e,t){return G(e,"borrow",[h(e.caller),b(t.accountNonce),E([...t.borrows]),k(t.to,h)])}function M(e,t){return W(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function V(e,t){return G(e,"withdraw",[h(e.caller),b(t.accountNonce),E([...t.withdrawals]),k(t.to,h)])}function z(e,t){return V(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function F(e,t){return G(e,"repay",[h(e.caller),b(t.accountNonce),E([...t.payments])])}function X(e,t){return F(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function H(e,t){return G(e,"liquidate",[h(e.caller),b(t.accountNonce),E([...t.debtPayments])])}function j(e,t){return G(e,"flash_loan",[h(e.caller),A(t.hubId,t.asset),g(t.amount),h(t.receiver),U(t.data)])}function Q(e,t){return G(e,"migrate_from_blend",[h(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),h(t.blendPool),x(t.collateralTokens.map(h)),x(t.supplyTokens.map(h)),R(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function J(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return G(e,"multiply",[h(e.caller),b(r),S(o),A(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),A(t.debt.hubId,t.debt.asset),S(t.mode),C(t.steps),k(t.initialPayment,(e=>P(e.hubId,e.asset,e.amount))),k(t.convertSwap,C)])}function K(e,t){return G(e,"swap_debt",[h(e.caller),b(t.accountNonce),A(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),A(t.newDebt.hubId,t.newDebt.asset),C(t.steps)])}function Z(e,t){return G(e,"swap_collateral",[h(e.caller),b(t.accountNonce),A(t.current.hubId,t.current.asset),g(t.fromAmount),A(t.newCollateral.hubId,t.newCollateral.asset),C(t.steps)])}function Y(e,t){return G(e,"repay_debt_with_collateral",[h(e.caller),b(t.accountNonce),A(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),A(t.debt.hubId,t.debt.asset),C(t.steps),_(t.closePosition)])}const ee="/stellar-lending",te=25,re=encodeURIComponent,oe=(e,t)=>e.fetchWithTimeout(`${ee}/context`,t),ae=(e,t)=>e.fetchWithTimeout(`${ee}/live-state`,t),ne=(e,t)=>e.fetchWithTimeout(`${ee}/assets`,t),se=(e,t)=>e.fetchWithTimeout(`${ee}/hubs`,t),ie=(e,t)=>e.fetchWithTimeout(`${ee}/spokes`,t),le=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${ee}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},ue=(e,t,r,o,a)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}`,a),ce=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}/holders`,{...n,params:{side:a}}),de=(e,t,r)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}`,r),pe=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/page`,{...o,params:{...r}}),me=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/markets`,{...o,params:{side:r}}),fe=(e,t,r)=>e.fetchWithTimeout(`${ee}/hubs/${t}`,r),he=(e,t,r)=>e.fetchWithTimeout(`${ee}/spokes/${t}`,r),ge=(e,t,r)=>e.fetchWithTimeout(`${ee}/users/${re(t)}/positions`,r),Se=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${ee}/users/${re(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},be=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${re(t)}/positions`,r),_e=(e,t={},r)=>{const{top:o=te,continuationToken:a}=t;return e.fetchWithTimeout(`${ee}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},we=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/assets/${re(t)}/graph`,{...o,params:{...r}}),ye=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/hubs/${t}/graph`,{...o,params:{...r}}),Te=(e,t,r,o)=>e.fetchWithTimeout(`${ee}/spokes/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ee}/reserves/${t}/${r}/${re(o)}/graph`,{...n,params:{...a}}),ve=(e,t)=>e.fetchWithTimeout(`${ee}/protocol-config`,t),ke=(e,t,r)=>e.fetchWithTimeout(`${ee}/protocol-config/${re(t)}`,r),Re=(e,t,r)=>e.fetchWithTimeout(t?`${ee}/roles?contractAddress=${re(t)}`:`${ee}/roles`,r),Ae=(e,t,r)=>e.fetchWithTimeout(`${ee}/accounts/${re(String(t))}/delegates`,r),Pe=(e,t)=>e.fetchWithTimeout(`${ee}/blend-pools`,t),Ee=e=>({context:t=>oe(e,t),liveState:t=>ae(e,t),protocolConfig:t=>ve(e,t),contractConfig:(t,r)=>ke(e,t,r),contractRoles:(t,r)=>Re(e,t,r),accountDelegates:(t,r)=>Ae(e,t,r),blendPools:t=>Pe(e,t),assets:t=>ne(e,t),hubs:t=>se(e,t),spokes:t=>ie(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?le(e,t,r):le(e,{},t);var o},reserve:(t,r,o,a)=>ue(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ce(e,t,r,o,a,n),asset:(t,r)=>de(e,t,r),assetMarkets:(t,r,o)=>me(e,t,r,o),hub:(t,r)=>fe(e,t,r),spoke:(t,r)=>he(e,t,r),userPositions:(t,r)=>ge(e,t,r),userActivity:(t,r,o)=>Se(e,t,r,o),accountPositions:(t,r)=>be(e,t,r),governanceProposals:(t,r)=>_e(e,t,r),assetGraph:(t,r,o)=>we(e,t,r,o),hubGraph:(t,r,o)=>ye(e,t,r,o),spokeGraph:(t,r,o)=>Te(e,t,r,o),reserveGraph:(t,r,o,a,n)=>xe(e,t,r,o,a,n)}),Ie=e=>I({base_borrow_rate:g(e.baseBorrowRateRay),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Be=e=>I({asset_decimals:S(e.assetDecimals),asset_id:h(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:_(e.isFlashloanable),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Oe=e=>I({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),Ne=e=>{if("Token"in e&&e.Token)return x([y("Token"),h(e.Token)]);if("Ref"in e&&e.Ref)return x([y("Ref"),y(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Le=e=>{if("Stellar"in e)return x([y("Stellar"),h(e.Stellar)]);if("Symbol"in e)return x([y("Symbol"),y(e.Symbol)]);if("String"in e)return x([y("String"),w(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},$e=e=>{if("Spot"===e)return x([y("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([y("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ce=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ue=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ge=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),I({asset:Le(t.asset),contract:h(t.contract),read_mode:$e(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([y("MultiFeed"),I({contract:h(t.contract),feed_id:w(t.feedId),kind:Ce(t.kind),nature:Ue(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},De=e=>{const t=e;return I({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:Ge(t.provider)})},qe=e=>{if("RequireDisjoint"===e)return x([y("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return x([y("AllowShared"),x(t.map((e=>I({contract:h(e.contract),kind:Ce(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},We=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return I({asset_decimals:S(Number(t.assetDecimals)),independence:qe(t.independence),max_price_stale_seconds:b(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:g(String(t.maxSanityPriceWad)),min_sanity_price_wad:g(String(t.minSanityPriceWad)),sources:x(r.map((e=>(e=>{if("Feed"in e)return x([y("Feed"),De(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),I({factor:De(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:Ne(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),I({key_a:Ne(t.keyA),key_b:Ne(t.keyB),kind:x([y(t.kind||"ConstantProduct")]),pool:h(t.pool),reserve_a_decimals:S(t.reserveADecimals),reserve_b_decimals:S(t.reserveBDecimals),share_decimals:S(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:I({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Me=We;function Ve(e,t){return G(e,"upgrade",[v(t.wasmHash)])}function ze(e,t){return G(e,"migrate",[S(t.newVersion)])}function Fe(e){return G(e,"pause",[])}function Xe(e){return G(e,"unpause",[])}function He(e,t){return G(e,"grant_role",[h(t.account),y(t.role)])}function je(e,t){return G(e,"revoke_role",[h(t.account),y(t.role)])}function Qe(e,t){return G(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Je(e){return G(e,"accept_ownership",[])}function Ke(e,t){return G(e,"set_swap_aggregator",[h(t.aggregator)])}function Ze(e,t){return G(e,"set_price_aggregator",[h(t.aggregator)])}const Ye=Ke;function et(e,t){return G(e,"set_accumulator",[h(t.accumulator)])}function tt(e,t){return G(e,"set_position_limits",[Oe(t)])}function rt(e,t){return G(e,"approve_blend_pool",[h(t.pool)])}function ot(e,t){return G(e,"revoke_blend_pool",[h(t.pool)])}const at=rt,nt=ot;function st(e,t){return G(e,"set_oracle",[Ne(t.key),We(t.oracle)])}const it=st;function lt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return G(e,"set_tolerance",[Ne(t.key),I({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function ut(e,t){return G(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function ct(e,t){return G(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function dt(e,t){return G(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function pt(e,t){return G(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function mt(e,t){return G(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Be(t.params)])}function ft(e,t){return G(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),Ie(t.params)])}function ht(e,t){return G(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function gt(e,t){return G(e,"add_rewards",[h(e.caller),E(t.rewards)])}function St(e,t){return G(e,"update_account_threshold",[h(e.caller),_(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const bt="00".repeat(32),_t=e=>{if("string"==typeof e)return v(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return d.xdr.ScVal.scvBytes(t)},wt=(e,...t)=>x([y(e),...t]),yt=e=>I({asset:h(e.asset),hub_id:S(e.hubId),params:Be(e.params)}),Tt=e=>I({hub_asset:A(e.hubId,e.asset),params:Ie(e.params)}),xt=e=>I({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),vt=e=>I({key:Ne(e.key),oracle:We(e.oracle)}),kt=e=>I({asset:h(e.asset),bonus:S(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:_(e.canBorrow),can_collateral:_(e.canCollateral),frozen:_(e.frozen),hub_id:S(e.hubId),paused:_(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),oracle_override:x([y("None")]),spoke_id:S(e.spokeId),supply_cap:g(e.supplyCap),threshold:S(e.threshold)}),Rt=e=>I({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),At=e=>I({hf_for_max_bonus_wad:g(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:g(e.targetHfWad)}),Pt=e=>I({key:Ne(e.key),tolerance:S(e.tolerance)}),Et=e=>I({account:h(e.account),role:y(e.role)});function It(e,t,r){const o=e.governanceAddress??c(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Bt=(e,t,r)=>It(e,"propose",[h(e.caller),t,_t(r)]),Ot=(e,t,r)=>It(e,"execute_self",[T(),t,_t(r)]);function Nt(e,t,r){return Bt(e,wt("SetSwapAggregator",h(t.aggregator)),r)}function Lt(e,t,r){return Bt(e,wt("SetPriceAggregator",h(t.aggregator)),r)}const $t=Nt;function Ct(e,t,r){return Bt(e,wt("SetAccumulator",h(t.accumulator)),r)}function Ut(e,t,r){return Bt(e,wt("SetPositionLimits",Oe(t)),r)}function Gt(e,t){return Bt(e,wt("CreateHub"),t)}function Dt(e,t){return Bt(e,wt("AddSpoke"),t)}function qt(e,t,r){return Bt(e,wt("RemoveSpoke",S(t.spokeId)),r)}function Wt(e,t,r){return Bt(e,wt("AddAssetToSpoke",kt(t)),r)}function Mt(e,t,r){return Bt(e,wt("EditAssetInSpoke",kt(t)),r)}function Vt(e,t,r){return Bt(e,wt("RemoveAssetFromSpoke",Rt(t)),r)}function zt(e,t,r){return Bt(e,wt("SetSpokeLiquidationCurve",At(t)),r)}function Ft(e,t,r){return Bt(e,wt("SetPositionManager",h(t.manager),_(t.isActive)),r)}function Xt(e,t,r){return Bt(e,wt("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Ht(e,t,r){return Bt(e,wt("ApproveToken",h(t.token)),r)}function jt(e,t,r){return Bt(e,wt("RevokeToken",h(t.token)),r)}function Qt(e,t,r){return Bt(e,wt("ApproveBlendPool",h(t.pool)),r)}function Jt(e,t,r){return Bt(e,wt("RevokeBlendPool",h(t.pool)),r)}function Kt(e,t,r){return Bt(e,wt("CreateLiquidityPool",yt(t)),r)}function Zt(e,t,r){return Bt(e,wt("UpgradeLiquidityPoolParams",Tt(t)),r)}function Yt(e,t,r){return Bt(e,wt("DeployPool",v(t.wasmHash)),r)}function er(e,t,r){return Bt(e,wt("UpgradePool",v(t.wasmHash)),r)}function tr(e,t,r){return Bt(e,wt("UpgradeController",v(t.wasmHash)),r)}function rr(e,t,r){return Bt(e,wt("MigrateController",S(t.newVersion)),r)}function or(e,t,r){return Bt(e,wt("TransferCtrlOwnership",xt(t)),r)}function ar(e,t,r){return Bt(e,wt("ConfigureAssetOracle",vt(t)),r)}const nr=ar;function sr(e,t,r){return Bt(e,wt("EditOracleTolerance",Pt(t)),r)}function ir(e,t,r){return Bt(e,wt("UpgradeGov",v(t.wasmHash)),r)}function lr(e,t,r){return Bt(e,wt("UpdateGovDelay",S(t.newDelay)),r)}function ur(e,t,r){return Bt(e,wt("GrantGovRole",Et(t)),r)}function cr(e,t,r){return Bt(e,wt("RevokeGovRole",Et(t)),r)}function dr(e,t,r){return Bt(e,wt("TransferGovOwnership",xt(t)),r)}function pr(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=_t(t.predecessor??bt);return It(e,"execute",[T(),h(t.target),y(t.functionName),r,o,_t(t.salt)])}function mr(e,t,r){return Ot(e,wt("UpgradeGov",v(t.wasmHash)),r)}function fr(e,t,r){return Ot(e,wt("UpdateGovDelay",S(t.newDelay)),r)}function hr(e,t,r){return Ot(e,wt("GrantGovRole",Et(t)),r)}function gr(e,t,r){return Ot(e,wt("RevokeGovRole",Et(t)),r)}function Sr(e,t,r){return Ot(e,wt("TransferGovOwnership",xt(t)),r)}const br=e=>x(e.map(h));function _r(e,t,r){return It(e,"propose_canceller_reset",[br(t.newCancellers),_t(r)])}function wr(e,t,r){return It(e,"execute_canceller_reset",[k(t.executor,h),br(t.newCancellers),_t(r)])}function yr(e,t){return It(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),_(t.paused),_(t.frozen)])}function Tr(e,t){return It(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function xr(e){return It(e,"create_hub",[h(e.caller)])}function vr(e){return It(e,"add_spoke",[h(e.caller)])}function kr(e,t){return It(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function Rr(e){return It(e,"pause",[h(e.caller)])}function Ar(e,t){return Bt(e,wt("Unpause"),t)}const Pr=e=>e.toXDR("base64"),Er=e=>d.xdr.ScVal.fromXDR(e,"base64"),Ir=e=>e.map((e=>String((0,d.scValToNative)(Er(e))))).join(":"),Br=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Or=e=>Number(e),Nr=e=>String(e),Lr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),$r=["None","Multiply","Long","Short"],Cr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net"],Ur=e=>Array.isArray(e)?e:[],Gr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Cr[Or(o)]??Br(o)),positionType:t,hubId:Or(e[1]),asset:Nr(e[2]),scaledAmountRay:Br(e[3]),indexRay:Br(e[4]),amount:Br(e[5]),liquidationThresholdBps:r?void 0:Or(e[6]),liquidationBonusBps:r?void 0:Or(e[7]),loanToValueBps:r?void 0:Or(e[8]),liquidationFeesBps:r?void 0:Or(e[9])};var o},Dr=e=>{return{owner:Nr(e[0]),spokeId:Or(e[1]),mode:(t=e[2],$r[Or(t)]??"None")};var t},qr=e=>Array.isArray(e)?e[1]:void 0,Wr=e=>{const t=(r=e,Array.isArray(r)?Nr(r[0]):Nr(r));var r;if("Token"===t)return{Token:Nr(qr(e))};if("Ref"===t)return{Ref:Nr(qr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Nr(t.Token)};if(void 0!==t.Ref)return{Ref:Nr(t.Ref)}}return{Token:Nr(e)}},Mr=e=>{const t=e.tolerance??{};return{assetDecimals:Or(e.asset_decimals),maxPriceStaleSeconds:Or(e.max_price_stale_seconds),sources:Ur(e.sources).map((e=>e)),tolerance:{upperRatio:Or(t.upper_ratio_bps),lowerRatio:Or(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Br(e.min_sanity_price_wad),maxSanityPriceWad:Br(e.max_sanity_price_wad)}},Vr={"market:create":e=>({topic:"market:create",data:{hubId:Or(e.hub_id),baseAsset:Nr(e.base_asset),maxBorrowRate:Br(e.max_borrow_rate),baseBorrowRate:Br(e.base_borrow_rate),slope1:Br(e.slope1),slope2:Br(e.slope2),slope3:Br(e.slope3),midUtilization:Br(e.mid_utilization),optimalUtilization:Br(e.optimal_utilization),maxUtilization:Br(e.max_utilization),reserveFactor:Or(e.reserve_factor),marketAddress:Nr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Nr(e.asset),maxBorrowRateRay:Br(e.max_borrow_rate),baseBorrowRateRay:Br(e.base_borrow_rate),slope1Ray:Br(e.slope1),slope2Ray:Br(e.slope2),slope3Ray:Br(e.slope3),midUtilizationRay:Br(e.mid_utilization),optimalUtilizationRay:Br(e.optimal_utilization),maxUtilizationRay:Br(e.max_utilization),reserveFactorBps:Or(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ur(e).map((e=>{return t=Ur(e),{hubId:Or(t[0]),asset:Nr(t[1]),timestamp:Or(t[2]),supplyIndexRay:Br(t[3]),borrowIndexRay:Br(t[4]),cash:Br(t[5]),suppliedRay:Br(t[6]),borrowedRay:Br(t[7]),revenueRay:Br(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ur(e).map((e=>{const t=e;return{hubId:Or(t.hub_id),asset:Nr(t.asset),params:(r=t.params,{maxBorrowRateRay:Br(r.max_borrow_rate),baseBorrowRateRay:Br(r.base_borrow_rate),slope1Ray:Br(r.slope1),slope2Ray:Br(r.slope2),slope3Ray:Br(r.slope3),midUtilizationRay:Br(r.mid_utilization),optimalUtilizationRay:Br(r.optimal_utilization),maxUtilizationRay:Br(r.max_utilization),reserveFactorBps:Or(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Or(r.flashloan_fee),assetId:Nr(r.asset_id),assetDecimals:Or(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ur(e);return{topic:"position:batch_update",data:{accountId:Br(t[0]),accountAttributes:Dr(Ur(t[1])),updates:[...Ur(t[2]).map((e=>Gr(Ur(e),"Deposit"))),...Ur(t[3]).map((e=>Gr(Ur(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Or(e.hub_id),asset:Nr(e.asset),receiver:Nr(e.receiver),caller:Nr(e.caller),amount:Br(e.amount),fee:Br(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Wr(e.key),oracle:Mr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Nr(e.asset),oracle:Mr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Nr(e.liquidator),accountId:Br(e.account_id),repaidUsdWad:Br(e.repaid_usd_wad),bonusBps:Br(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Br(e.account_id),totalBorrowUsdWad:Br(e.total_borrow_usd_wad),totalCollateralUsdWad:Br(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Nr(e.token),amount:Br(e.amount),usdValueWad:Br(e.usd_value_wad),accountId:Br(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Or(e.hub_id),asset:Nr(e.asset),amount:Br(e.amount),fee:Br(e.fee),amountSent:Br(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Nr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Lr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Nr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Nr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Nr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Nr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Lr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Or(e.max_supply_positions),maxBorrowPositions:Or(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Br(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Nr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Or(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Br(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Br(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Or(t.liquidation_bonus_factor_bps)}}}},zr=Object.freeze(Object.keys(Vr));function Fr(e,t){const r=Ir(e),o=Vr[r];return o?o((0,d.scValToNative)(Er(t))):null}const Xr="XLENDXLM-a7c9f3",Hr=1e4;function jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Xr}-${r}`}function Qr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Jr(e,t=0){return e*Hr+t}function Kr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Zr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Yr=e=>e.baseUrl??s[e.network];async function eo(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Zr(Yr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function to(e){const t=Zr(Yr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ro=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,oo=e=>O(e).toXDR("base64");function ao(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=C(ro(t,e.referralId));return{xdr:new d.TransactionBuilder(a,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call("execute_strategy",h(e.caller),g(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function no(e,t){return ao(e,t)}function so(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(uo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(uo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function io(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:so(e,t)}const lo=so,uo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function co(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function po(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw co(r.invokedContractId,e);throw e}}async function mo(e,t,r){return po(e,t.xdr,r)}function fo(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function ho(e,t){return new Uint8Array(0)}const go=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function So(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(go(e.message)),d.xdr.ScVal.scvBytes(go(e.attestation)));return{xdr:new d.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const bo={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function _o(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=bo[r];return o?{code:r,...o}:null}module.exports=t})();
|
|
@@ -1 +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),T=e=>i.ScVal.scvString(e),I=e=>i.ScVal.scvSymbol(e),x=()=>i.ScVal.scvVoid(),A=e=>i.ScVal.scvVec(e),E=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.ScVal.scvBytes(o)},$=(e,t)=>null==e?x():t(e),B=(e,t)=>O({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([B(e,t),S(r)]),P=e=>i.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),O=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:I(t),val:e[t]})));return i.ScVal.scvMap(t)};class U{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>b)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(_[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>b)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===b;let i=b;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*b/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const L=e=>{const t=new U(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(_.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return O({amounts:i.ScVal.scvVec(t.amountList.map((e=>S(e)))),assets:i.ScVal.scvVec(t.assetList.map((e=>y(e)))),ops:i.ScVal.scvBytes(t.toBytes(r,o,a))})},W=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},q=()=>i.ScVal.scvBytes(Buffer.alloc(0)),D=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},z=e=>{if("string"==typeof e)return W(D(e));if(e instanceof Uint8Array)return 0===e.length?q():W(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?W(D(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?W(D(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?W(D(e.bytes)):0===e.bytes.length?q():W(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!w.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),i.ScVal.scvBytes(Buffer.from(L(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},V=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return i.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function C(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function M(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return C(e,"supply",[y(e.caller),k(r),v(o),P([...t.assets])])}function F(e,t){return M(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function G(e,t){return C(e,"borrow",[y(e.caller),k(t.accountNonce),P([...t.borrows]),$(t.to,y)])}function X(e,t){return G(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function H(e,t){return C(e,"withdraw",[y(e.caller),k(t.accountNonce),P([...t.withdrawals]),$(t.to,y)])}function j(e,t){return H(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function J(e,t){return C(e,"repay",[y(e.caller),k(t.accountNonce),P([...t.payments])])}function Q(e,t){return J(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function K(e,t){return C(e,"liquidate",[y(e.caller),k(t.accountNonce),P([...t.debtPayments])])}function Z(e,t){return C(e,"flash_loan",[y(e.caller),B(t.hubId,t.asset),S(t.amount),y(t.receiver),V(t.data)])}function Y(e,t){return C(e,"migrate_from_blend",[y(e.caller),k(t.accountId),v(t.spokeId),v(t.hubId),y(t.blendPool),A(t.collateralTokens.map(y)),A(t.supplyTokens.map(y)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,i.ScVal.scvVec([y(t),S(r)]);var t,r}))))]);var r}function ee(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return C(e,"multiply",[y(e.caller),k(r),v(o),B(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),B(t.debt.hubId,t.debt.asset),v(t.mode),z(t.steps),$(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),$(t.convertSwap,z)])}function te(e,t){return C(e,"swap_debt",[y(e.caller),k(t.accountNonce),B(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),B(t.newDebt.hubId,t.newDebt.asset),z(t.steps)])}function re(e,t){return C(e,"swap_collateral",[y(e.caller),k(t.accountNonce),B(t.current.hubId,t.current.asset),S(t.fromAmount),B(t.newCollateral.hubId,t.newCollateral.asset),z(t.steps)])}function oe(e,t){return C(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),B(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),B(t.debt.hubId,t.debt.asset),z(t.steps),R(t.closePosition)])}const ae="/stellar-lending",ne=25,se=encodeURIComponent,ie=(e,t)=>e.fetchWithTimeout(`${ae}/context`,t),le=(e,t)=>e.fetchWithTimeout(`${ae}/live-state`,t),ue=(e,t)=>e.fetchWithTimeout(`${ae}/assets`,t),ce=(e,t)=>e.fetchWithTimeout(`${ae}/hubs`,t),pe=(e,t)=>e.fetchWithTimeout(`${ae}/spokes`,t),de=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${ae}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},me=(e,t,r,o,a)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}`,a),fe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}/holders`,{...n,params:{side:a}}),he=(e,t,r)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}`,r),ge=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/page`,{...o,params:{...r}}),we=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/markets`,{...o,params:{side:r}}),_e=(e,t,r)=>e.fetchWithTimeout(`${ae}/hubs/${t}`,r),be=(e,t,r)=>e.fetchWithTimeout(`${ae}/spokes/${t}`,r),ye=(e,t,r)=>e.fetchWithTimeout(`${ae}/users/${se(t)}/positions`,r),Se=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${ae}/users/${se(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},ve=(e,t,r)=>e.fetchWithTimeout(`${ae}/accounts/${se(t)}/positions`,r),ke=(e,t={},r)=>{const{top:o=ne,continuationToken:a}=t;return e.fetchWithTimeout(`${ae}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Re=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/assets/${se(t)}/graph`,{...o,params:{...r}}),Te=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/hubs/${t}/graph`,{...o,params:{...r}}),Ie=(e,t,r,o)=>e.fetchWithTimeout(`${ae}/spokes/${t}/graph`,{...o,params:{...r}}),xe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${ae}/reserves/${t}/${r}/${se(o)}/graph`,{...n,params:{...a}}),Ae=(e,t)=>e.fetchWithTimeout(`${ae}/protocol-config`,t),Ee=(e,t,r)=>e.fetchWithTimeout(`${ae}/protocol-config/${se(t)}`,r),$e=(e,t,r)=>e.fetchWithTimeout(t?`${ae}/roles?contractAddress=${se(t)}`:`${ae}/roles`,r),Be=(e,t,r)=>e.fetchWithTimeout(`${ae}/accounts/${se(String(t))}/delegates`,r),Ne=(e,t)=>e.fetchWithTimeout(`${ae}/blend-pools`,t),Pe=e=>({context:t=>ie(e,t),liveState:t=>le(e,t),protocolConfig:t=>Ae(e,t),contractConfig:(t,r)=>Ee(e,t,r),contractRoles:(t,r)=>$e(e,t,r),accountDelegates:(t,r)=>Be(e,t,r),blendPools:t=>Ne(e,t),assets:t=>ue(e,t),hubs:t=>ce(e,t),spokes:t=>pe(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?de(e,t,r):de(e,{},t);var o},reserve:(t,r,o,a)=>me(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>fe(e,t,r,o,a,n),asset:(t,r)=>he(e,t,r),assetMarkets:(t,r,o)=>we(e,t,r,o),hub:(t,r)=>_e(e,t,r),spoke:(t,r)=>be(e,t,r),userPositions:(t,r)=>ye(e,t,r),userActivity:(t,r,o)=>Se(e,t,r,o),accountPositions:(t,r)=>ve(e,t,r),governanceProposals:(t,r)=>ke(e,t,r),assetGraph:(t,r,o)=>Re(e,t,r,o),hubGraph:(t,r,o)=>Te(e,t,r,o),spokeGraph:(t,r,o)=>Ie(e,t,r,o),reserveGraph:(t,r,o,a,n)=>xe(e,t,r,o,a,n)}),Oe=e=>O({base_borrow_rate:S(e.baseBorrowRateRay),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),Ue=e=>O({asset_decimals:v(e.assetDecimals),asset_id:y(e.assetId),base_borrow_rate:S(e.baseBorrowRateRay),flashloan_fee:v(e.flashloanFeeBps),is_flashloanable:R(e.isFlashloanable),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),Le=e=>O({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),We=e=>{if("Token"in e&&e.Token)return A([I("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([I("Ref"),I(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},qe=e=>{if("Stellar"in e)return A([I("Stellar"),y(e.Stellar)]);if("Symbol"in e)return A([I("Symbol"),I(e.Symbol)]);if("String"in e)return A([I("String"),T(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},De=e=>{if("Spot"===e)return A([I("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return A([I("Twap"),v(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},ze=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Ve=e=>{if("Market"===e||"Fundamental"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Ce=e=>{if("Reflector"in e){const t=e.Reflector;return A([I("Reflector"),O({asset:qe(t.asset),contract:y(t.contract),read_mode:De(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([I("MultiFeed"),O({contract:y(t.contract),feed_id:T(t.feedId),kind:ze(t.kind),nature:Ve(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Me=e=>{const t=e;return O({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:Ce(t.provider)})},Fe=e=>{if("RequireDisjoint"===e)return A([I("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([I("AllowShared"),A(t.map((e=>O({contract:y(e.contract),kind:ze(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},Ge=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return O({asset_decimals:v(Number(t.assetDecimals)),independence:Fe(t.independence),max_price_stale_seconds:k(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:S(String(t.maxSanityPriceWad)),min_sanity_price_wad:S(String(t.minSanityPriceWad)),sources:A(r.map((e=>(e=>{if("Feed"in e)return A([I("Feed"),Me(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([I("Scaled"),O({factor:Me(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:We(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([I("LpShare"),O({key_a:We(t.keyA),key_b:We(t.keyB),kind:A([I(t.kind||"ConstantProduct")]),pool:y(t.pool),reserve_a_decimals:v(t.reserveADecimals),reserve_b_decimals:v(t.reserveBDecimals),share_decimals:v(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:O({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})})},Xe=Ge;function He(e,t){return C(e,"upgrade",[E(t.wasmHash)])}function je(e,t){return C(e,"migrate",[v(t.newVersion)])}function Je(e){return C(e,"pause",[])}function Qe(e){return C(e,"unpause",[])}function Ke(e,t){return C(e,"grant_role",[y(t.account),I(t.role)])}function Ze(e,t){return C(e,"revoke_role",[y(t.account),I(t.role)])}function Ye(e,t){return C(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function et(e){return C(e,"accept_ownership",[])}function tt(e,t){return C(e,"set_swap_aggregator",[y(t.aggregator)])}function rt(e,t){return C(e,"set_price_aggregator",[y(t.aggregator)])}const ot=tt;function at(e,t){return C(e,"set_accumulator",[y(t.accumulator)])}function nt(e,t){return C(e,"set_position_limits",[Le(t)])}function st(e,t){return C(e,"approve_blend_pool",[y(t.pool)])}function it(e,t){return C(e,"revoke_blend_pool",[y(t.pool)])}const lt=st,ut=it;function ct(e,t){return C(e,"set_oracle",[We(t.key),Ge(t.oracle)])}const pt=ct;function dt(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return C(e,"set_tolerance",[We(t.key),O({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function mt(e,t){return C(e,"set_spoke_asset_flags",[v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function ft(e,t){return C(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function ht(e,t){return C(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function gt(e,t){return C(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function wt(e,t){return C(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),Ue(t.params)])}function _t(e,t){return C(e,"upgrade_liquidity_pool_params",[B(t.hubId,t.asset),Oe(t.params)])}function bt(e,t){return C(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function yt(e,t){return C(e,"add_rewards",[y(e.caller),P(t.rewards)])}function St(e,t){return C(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const vt="00".repeat(32),kt=e=>{if("string"==typeof e)return E(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return i.ScVal.scvBytes(t)},Rt=(e,...t)=>A([I(e),...t]),Tt=e=>O({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),It=e=>O({asset:y(e.asset),bonus:v(e.bonus),borrow_cap:S(e.borrowCap),can_borrow:R(e.canBorrow),can_collateral:R(e.canCollateral),frozen:R(e.frozen),hub_id:v(e.hubId),paused:R(e.paused),liquidation_fees:v(e.liquidationFees),ltv:v(e.ltv),oracle_override:A([I("None")]),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),xt=e=>O({account:y(e.account),role:I(e.role)});function At(t,a,s){const i=t.governanceAddress??g(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const Et=(e,t,r)=>At(e,"propose",[y(e.caller),t,kt(r)]),$t=(e,t,r)=>At(e,"execute_self",[x(),t,kt(r)]);function Bt(e,t,r){return Et(e,Rt("SetSwapAggregator",y(t.aggregator)),r)}function Nt(e,t,r){return Et(e,Rt("SetPriceAggregator",y(t.aggregator)),r)}const Pt=Bt;function Ot(e,t,r){return Et(e,Rt("SetAccumulator",y(t.accumulator)),r)}function Ut(e,t,r){return Et(e,Rt("SetPositionLimits",Le(t)),r)}function Lt(e,t){return Et(e,Rt("CreateHub"),t)}function Wt(e,t){return Et(e,Rt("AddSpoke"),t)}function qt(e,t,r){return Et(e,Rt("RemoveSpoke",v(t.spokeId)),r)}function Dt(e,t,r){return Et(e,Rt("AddAssetToSpoke",It(t)),r)}function zt(e,t,r){return Et(e,Rt("EditAssetInSpoke",It(t)),r)}function Vt(e,t,r){return Et(e,Rt("RemoveAssetFromSpoke",O({hub_asset:B((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function Ct(e,t,r){return Et(e,Rt("SetSpokeLiquidationCurve",O({hf_for_max_bonus_wad:S((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:v(o.liquidationBonusFactorBps),spoke_id:v(o.spokeId),target_hf_wad:S(o.targetHfWad)})),r);var o}function Mt(e,t,r){return Et(e,Rt("SetPositionManager",y(t.manager),R(t.isActive)),r)}function Ft(e,t,r){return Et(e,Rt("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Gt(e,t,r){return Et(e,Rt("ApproveToken",y(t.token)),r)}function Xt(e,t,r){return Et(e,Rt("RevokeToken",y(t.token)),r)}function Ht(e,t,r){return Et(e,Rt("ApproveBlendPool",y(t.pool)),r)}function jt(e,t,r){return Et(e,Rt("RevokeBlendPool",y(t.pool)),r)}function Jt(e,t,r){return Et(e,Rt("CreateLiquidityPool",O({asset:y((o=t).asset),hub_id:v(o.hubId),params:Ue(o.params)})),r);var o}function Qt(e,t,r){return Et(e,Rt("UpgradeLiquidityPoolParams",O({hub_asset:B((o=t).hubId,o.asset),params:Oe(o.params)})),r);var o}function Kt(e,t,r){return Et(e,Rt("DeployPool",E(t.wasmHash)),r)}function Zt(e,t,r){return Et(e,Rt("UpgradePool",E(t.wasmHash)),r)}function Yt(e,t,r){return Et(e,Rt("UpgradeController",E(t.wasmHash)),r)}function er(e,t,r){return Et(e,Rt("MigrateController",v(t.newVersion)),r)}function tr(e,t,r){return Et(e,Rt("TransferCtrlOwnership",Tt(t)),r)}function rr(e,t,r){return Et(e,Rt("ConfigureAssetOracle",O({key:We((o=t).key),oracle:Ge(o.oracle)})),r);var o}const or=rr;function ar(e,t,r){return Et(e,Rt("EditOracleTolerance",O({key:We((o=t).key),tolerance:v(o.tolerance)})),r);var o}function nr(e,t,r){return Et(e,Rt("UpgradeGov",E(t.wasmHash)),r)}function sr(e,t,r){return Et(e,Rt("UpdateGovDelay",v(t.newDelay)),r)}function ir(e,t,r){return Et(e,Rt("GrantGovRole",xt(t)),r)}function lr(e,t,r){return Et(e,Rt("RevokeGovRole",xt(t)),r)}function ur(e,t,r){return Et(e,Rt("TransferGovOwnership",Tt(t)),r)}function cr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=kt(t.predecessor??vt);return At(e,"execute",[x(),y(t.target),I(t.functionName),r,o,kt(t.salt)])}function pr(e,t,r){return $t(e,Rt("UpgradeGov",E(t.wasmHash)),r)}function dr(e,t,r){return $t(e,Rt("UpdateGovDelay",v(t.newDelay)),r)}function mr(e,t,r){return $t(e,Rt("GrantGovRole",xt(t)),r)}function fr(e,t,r){return $t(e,Rt("RevokeGovRole",xt(t)),r)}function hr(e,t,r){return $t(e,Rt("TransferGovOwnership",Tt(t)),r)}const gr=e=>A(e.map(y));function wr(e,t,r){return At(e,"propose_canceller_reset",[gr(t.newCancellers),kt(r)])}function _r(e,t,r){return At(e,"execute_canceller_reset",[$(t.executor,y),gr(t.newCancellers),kt(r)])}function br(e,t){return At(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen)])}function yr(e,t){return At(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function Sr(e){return At(e,"create_hub",[y(e.caller)])}function vr(e){return At(e,"add_spoke",[y(e.caller)])}function kr(e,t){return At(e,"revoke_role_immediate",[y(t.account),I(t.role)])}function Rr(e){return At(e,"pause",[y(e.caller)])}function Tr(e,t){return Et(e,Rt("Unpause"),t)}const Ir=e=>e.toXDR("base64"),xr=e=>i.ScVal.fromXDR(e,"base64"),Ar=e=>e.map((e=>String(s(xr(e))))).join(":"),Er=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),$r=e=>Number(e),Br=e=>String(e),Nr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Pr=["None","Multiply","Long","Short"],Or=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net"],Ur=e=>Array.isArray(e)?e:[],Lr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Or[$r(o)]??Er(o)),positionType:t,hubId:$r(e[1]),asset:Br(e[2]),scaledAmountRay:Er(e[3]),indexRay:Er(e[4]),amount:Er(e[5]),liquidationThresholdBps:r?void 0:$r(e[6]),liquidationBonusBps:r?void 0:$r(e[7]),loanToValueBps:r?void 0:$r(e[8]),liquidationFeesBps:r?void 0:$r(e[9])};var o},Wr=e=>{return{owner:Br(e[0]),spokeId:$r(e[1]),mode:(t=e[2],Pr[$r(t)]??"None")};var t},qr=e=>Array.isArray(e)?e[1]:void 0,Dr=e=>{const t=(r=e,Array.isArray(r)?Br(r[0]):Br(r));var r;if("Token"===t)return{Token:Br(qr(e))};if("Ref"===t)return{Ref:Br(qr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Br(t.Token)};if(void 0!==t.Ref)return{Ref:Br(t.Ref)}}return{Token:Br(e)}},zr=e=>{const t=e.tolerance??{};return{assetDecimals:$r(e.asset_decimals),maxPriceStaleSeconds:$r(e.max_price_stale_seconds),sources:Ur(e.sources).map((e=>e)),tolerance:{upperRatio:$r(t.upper_ratio_bps),lowerRatio:$r(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Er(e.min_sanity_price_wad),maxSanityPriceWad:Er(e.max_sanity_price_wad)}},Vr={"market:create":e=>({topic:"market:create",data:{hubId:$r(e.hub_id),baseAsset:Br(e.base_asset),maxBorrowRate:Er(e.max_borrow_rate),baseBorrowRate:Er(e.base_borrow_rate),slope1:Er(e.slope1),slope2:Er(e.slope2),slope3:Er(e.slope3),midUtilization:Er(e.mid_utilization),optimalUtilization:Er(e.optimal_utilization),maxUtilization:Er(e.max_utilization),reserveFactor:$r(e.reserve_factor),marketAddress:Br(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Br(e.asset),maxBorrowRateRay:Er(e.max_borrow_rate),baseBorrowRateRay:Er(e.base_borrow_rate),slope1Ray:Er(e.slope1),slope2Ray:Er(e.slope2),slope3Ray:Er(e.slope3),midUtilizationRay:Er(e.mid_utilization),optimalUtilizationRay:Er(e.optimal_utilization),maxUtilizationRay:Er(e.max_utilization),reserveFactorBps:$r(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Ur(e).map((e=>{return t=Ur(e),{hubId:$r(t[0]),asset:Br(t[1]),timestamp:$r(t[2]),supplyIndexRay:Er(t[3]),borrowIndexRay:Er(t[4]),cash:Er(t[5]),suppliedRay:Er(t[6]),borrowedRay:Er(t[7]),revenueRay:Er(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Ur(e).map((e=>{const t=e;return{hubId:$r(t.hub_id),asset:Br(t.asset),params:(r=t.params,{maxBorrowRateRay:Er(r.max_borrow_rate),baseBorrowRateRay:Er(r.base_borrow_rate),slope1Ray:Er(r.slope1),slope2Ray:Er(r.slope2),slope3Ray:Er(r.slope3),midUtilizationRay:Er(r.mid_utilization),optimalUtilizationRay:Er(r.optimal_utilization),maxUtilizationRay:Er(r.max_utilization),reserveFactorBps:$r(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:$r(r.flashloan_fee),assetId:Br(r.asset_id),assetDecimals:$r(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Ur(e);return{topic:"position:batch_update",data:{accountId:Er(t[0]),accountAttributes:Wr(Ur(t[1])),updates:[...Ur(t[2]).map((e=>Lr(Ur(e),"Deposit"))),...Ur(t[3]).map((e=>Lr(Ur(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:$r(e.hub_id),asset:Br(e.asset),receiver:Br(e.receiver),caller:Br(e.caller),amount:Er(e.amount),fee:Er(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Dr(e.key),oracle:zr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Br(e.asset),oracle:zr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Br(e.liquidator),accountId:Er(e.account_id),repaidUsdWad:Er(e.repaid_usd_wad),bonusBps:Er(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Er(e.account_id),totalBorrowUsdWad:Er(e.total_borrow_usd_wad),totalCollateralUsdWad:Er(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Br(e.token),amount:Er(e.amount),usdValueWad:Er(e.usd_value_wad),accountId:Er(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:$r(e.hub_id),asset:Br(e.asset),amount:Er(e.amount),fee:Er(e.fee),amountSent:Er(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Br(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Nr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Br(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Br(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Br(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Br(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Nr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:$r(e.max_supply_positions),maxBorrowPositions:$r(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Er(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Br(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:$r(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Er(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Er(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:$r(t.liquidation_bonus_factor_bps)}}}},Cr=Object.freeze(Object.keys(Vr));function Mr(e,t){const r=Ar(e),o=Vr[r];return o?o(s(xr(t))):null}const Fr="XLENDXLM-a7c9f3",Gr=1e4;function Xr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Fr}-${r}`}function Hr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function jr(e,t=0){return 1e4*e+t}function Jr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Qr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Kr=e=>e.baseUrl??d[e.network];async function Zr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Qr(Kr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function Yr(e){const t=Qr(Kr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const eo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,to=e=>L(e).toXDR("base64");function ro(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=z(eo(a,t.referralId));return{xdr:new n(l,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",y(t.caller),S(t.totalIn),u)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function oo(e,t){return ro(e,t)}function ao(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(io),splitPpm:e.splitPpm}))):[{hops:e.hops.map(io),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function no(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:ao(e,t)}const so=ao,io=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function lo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function uo(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw lo(r.invokedContractId,e);throw e}}async function co(e,t,r){return uo(e,t.xdr,r)}function po(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function mo(e,t){return new Uint8Array(0)}const fo=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function ho(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(fo(t.message)),i.ScVal.scvBytes(fo(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const go={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function wo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=go[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,vt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Cr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Gr as SYNTHETIC_EVENT_ORDER_STRIDE,Fr as XOXNO_LENDING_STELLAR_TICKER,mo as buildSameTokenRepaySwapSteps,et as buildStellarAcceptOwnershipTx,yt as buildStellarAddRewardsTx,st as buildStellarApproveBlendPoolTx,lt as buildStellarApproveTokenTx,oo as buildStellarBatchSwapTx,G as buildStellarBorrowBatchTx,X as buildStellarBorrowTx,ho as buildStellarCctpForwardTx,bt as buildStellarClaimRevenueTx,wt as buildStellarCreateLiquidityPoolTx,_r as buildStellarExecuteCancellerResetTx,ro as buildStellarExecuteStrategyTx,Z as buildStellarFlashLoanTx,vr as buildStellarGovernanceAddSpokeImmediateTx,Sr as buildStellarGovernanceCreateHubImmediateTx,pr as buildStellarGovernanceExecuteGovernanceUpgradeTx,mr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,fr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,hr as buildStellarGovernanceExecuteTransferGovOwnTx,cr as buildStellarGovernanceExecuteTx,dr as buildStellarGovernanceExecuteUpdateDelayTx,Rr as buildStellarGovernancePauseTx,kr as buildStellarGovernanceRevokeRoleImmediateTx,yr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,br as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ke as buildStellarGrantRoleTx,Xr as buildStellarLendingIdentifier,K as buildStellarLiquidateTx,Y as buildStellarMigrateFromBlendTx,je as buildStellarMigrateTx,ee as buildStellarMultiplyTx,Je as buildStellarPauseTx,Dt as buildStellarProposeAddAssetToSpokeTx,Wt as buildStellarProposeAddSpokeTx,Ht as buildStellarProposeApproveBlendPoolTx,Gt as buildStellarProposeApproveTokenTx,wr as buildStellarProposeCancellerResetTx,rr as buildStellarProposeConfigureAssetOracleTx,or as buildStellarProposeConfigureMarketOracleTx,Lt as buildStellarProposeCreateHubTx,Jt as buildStellarProposeCreateLiquidityPoolTx,Kt as buildStellarProposeDeployPoolTx,zt as buildStellarProposeEditAssetInSpokeTx,ar as buildStellarProposeEditOracleToleranceTx,nr as buildStellarProposeGovernanceUpgradeTx,ir as buildStellarProposeGrantGovernanceRoleTx,er as buildStellarProposeMigrateControllerTx,Vt as buildStellarProposeRemoveAssetFromSpokeTx,qt as buildStellarProposeRemoveSpokeTx,jt as buildStellarProposeRevokeBlendPoolTx,lr as buildStellarProposeRevokeGovernanceRoleTx,Xt as buildStellarProposeRevokeTokenTx,Ot as buildStellarProposeSetAccumulatorTx,Pt as buildStellarProposeSetAggregatorTx,Ft as buildStellarProposeSetMinBorrowCollatTx,Ut as buildStellarProposeSetPositionLimitsTx,Mt as buildStellarProposeSetPositionManagerTx,Nt as buildStellarProposeSetPriceAggregatorTx,Ct as buildStellarProposeSetSpokeLiquidationCurveTx,Bt as buildStellarProposeSetSwapAggregatorTx,tr as buildStellarProposeTransferCtrlOwnershipTx,ur as buildStellarProposeTransferGovOwnTx,Tr as buildStellarProposeUnpauseTx,sr as buildStellarProposeUpdateDelayTx,Yt as buildStellarProposeUpgradeControllerTx,Qt as buildStellarProposeUpgradePoolParamsTx,Zt as buildStellarProposeUpgradePoolTx,gt as buildStellarRenewAccountTx,J as buildStellarRepayBatchTx,oe as buildStellarRepayDebtWithCollateralTx,Q as buildStellarRepayTx,it as buildStellarRevokeBlendPoolTx,Ze as buildStellarRevokeRoleTx,ut as buildStellarRevokeTokenTx,at as buildStellarSetAccumulatorTx,ot as buildStellarSetAggregatorTx,pt as buildStellarSetMarketOracleConfigTx,ft as buildStellarSetOracleSanityBoundsTx,dt as buildStellarSetOracleToleranceTx,ct as buildStellarSetOracleTx,nt as buildStellarSetPositionLimitsTx,rt as buildStellarSetPriceAggregatorTx,mt as buildStellarSetSpokeAssetFlagsTx,tt as buildStellarSetSwapAggregatorTx,M as buildStellarSupplyBatchTx,F as buildStellarSupplyTx,re as buildStellarSwapCollateralTx,te as buildStellarSwapDebtTx,Ye as buildStellarTransferOwnershipTx,Qe as buildStellarUnpauseTx,St as buildStellarUpdateAccountThresholdTx,ht as buildStellarUpdateIndexesTx,He as buildStellarUpgradeControllerTx,_t as buildStellarUpgradeLiquidityPoolParamsTx,H as buildStellarWithdrawBatchTx,j as buildStellarWithdrawTx,C as buildTx,Mr as decodeStellarLendingEvent,Ge as encodeAssetOracle,Oe as encodeInterestRateModel,Xe as encodeMarketOracleConfigInput,Ue as encodeMarketParamsRaw,Le as encodePositionLimits,We as encodePriceKey,to as encodeStrategyPayloadToRouteXdr,Hr as extractEventOrder,Be as getStellarAccountDelegates,ve as getStellarAccountPositions,Zr as getStellarAggregatorQuote,h as getStellarAggregatorRouter,he as getStellarAsset,Re as getStellarAssetGraph,we as getStellarAssetMarkets,ge as getStellarAssetPage,ue as getStellarAssets,Ne as getStellarBlendPools,Ee as getStellarContractConfig,$e as getStellarContractRoles,g as getStellarGovernance,ke as getStellarGovernanceProposals,_e as getStellarHub,Te as getStellarHubGraph,ce as getStellarHubs,ie as getStellarLendingContext,f as getStellarLendingController,le as getStellarLendingLiveState,Ae as getStellarProtocolConfig,Yr as getStellarQuoteTokens,me as getStellarReserve,xe as getStellarReserveGraph,fe as getStellarReserveHolders,de as getStellarReserves,be as getStellarSpoke,Ie as getStellarSpokeGraph,pe as getStellarSpokes,Se as getStellarUserActivity,ye as getStellarUserPositions,so as mapQuoteResponseToAggregatorSwap,ao as mapQuoteResponseToStrategyPayload,no as mapQuoteResponseToStrategySwap,wo as mapSorobanError,Jr as mapStellarPositionActivityType,co as prepareStellarBuiltTx,uo as prepareStellarTxXdr,Ar as stellarLendingDispatchKey,Pe as stellarLendingRead,jr as syntheticEventOrder,lo as tagStellarInvokedContractError,Ir as toBase64Xdr,po as toStellarPositionMode};
|
|
@@ -211,3 +211,66 @@ export interface StellarMarketGraphQuery {
|
|
|
211
211
|
/** Bin width as a timespan string (e.g. `1h`, `1d`). */
|
|
212
212
|
bin: string;
|
|
213
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Config and admin state for one deployed contract, event-sourced by the
|
|
216
|
+
* indexer from that contract's own config, pause, ownership and admin events.
|
|
217
|
+
*
|
|
218
|
+
* Every field is optional-by-absence: a contract only populates what its own
|
|
219
|
+
* events carry, so a governance row leaves the controller fields null and vice
|
|
220
|
+
* versa. `paused` is null until a pause or unpause has actually been observed,
|
|
221
|
+
* which is materially different from a confirmed `false`.
|
|
222
|
+
*/
|
|
223
|
+
export interface StellarContractConfig {
|
|
224
|
+
contractAddress: string;
|
|
225
|
+
wasmHash: string | null;
|
|
226
|
+
accumulator: string | null;
|
|
227
|
+
swapAggregator: string | null;
|
|
228
|
+
priceAggregator: string | null;
|
|
229
|
+
maxSupplyPositions: number | null;
|
|
230
|
+
maxBorrowPositions: number | null;
|
|
231
|
+
/** Raw 18-decimal WAD. */
|
|
232
|
+
minBorrowCollateralUsdWad: string | null;
|
|
233
|
+
paused: boolean | null;
|
|
234
|
+
/** Governance timelock delay, in ledgers. */
|
|
235
|
+
minDelayLedgers: number | null;
|
|
236
|
+
owner: string | null;
|
|
237
|
+
pendingOwner: string | null;
|
|
238
|
+
admin: string | null;
|
|
239
|
+
pendingAdmin: string | null;
|
|
240
|
+
pendingAdminLiveUntilLedger: number | null;
|
|
241
|
+
ledger: number;
|
|
242
|
+
updatedAt: number;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* One access-control grant. Revocation flips `granted` rather than removing the
|
|
246
|
+
* row, so a revoked grant stays queryable.
|
|
247
|
+
*/
|
|
248
|
+
export interface StellarContractRole {
|
|
249
|
+
contractAddress: string;
|
|
250
|
+
/** On-chain role symbol, e.g. `ORACLE`, `PROPOSER`. */
|
|
251
|
+
role: string;
|
|
252
|
+
account: string;
|
|
253
|
+
granted: boolean;
|
|
254
|
+
caller: string | null;
|
|
255
|
+
ledger: number;
|
|
256
|
+
updatedAt: number;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* One position-authorization grant. A delegate may act on the owner's position,
|
|
260
|
+
* so this is security-relevant state rather than display metadata.
|
|
261
|
+
*/
|
|
262
|
+
export interface StellarAccountDelegate {
|
|
263
|
+
accountId: number;
|
|
264
|
+
owner: string;
|
|
265
|
+
delegate: string;
|
|
266
|
+
granted: boolean;
|
|
267
|
+
ledger: number;
|
|
268
|
+
updatedAt: number;
|
|
269
|
+
}
|
|
270
|
+
/** Approval state for one Blend pool, kept after revocation as `approved: false`. */
|
|
271
|
+
export interface StellarBlendPool {
|
|
272
|
+
pool: string;
|
|
273
|
+
approved: boolean;
|
|
274
|
+
ledger: number;
|
|
275
|
+
updatedAt: number;
|
|
276
|
+
}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import type { StellarAssetListItem, StellarAssetPage, StellarHubListItem, StellarLendingLiveStateDto, StellarReserveListItem, StellarSpokeListItem, StellarUserActivityItem } from '@xoxno/types/stellar-lending';
|
|
15
15
|
import type { OurRequestInit, XOXNOClient } from '../../utils/api';
|
|
16
|
-
import type { StellarAccountPositions, StellarAsset, StellarAssetMarket, StellarGovernanceProposalsPage, StellarHub, StellarLendingHoldersSide, StellarLendingContext, StellarLendingMarketSide, StellarMarketGraph, StellarMarketGraphQuery, StellarReserve, StellarSpoke, StellarTopHolders } from './lending-read-types';
|
|
16
|
+
import type { StellarAccountDelegate, StellarAccountPositions, StellarAsset, StellarAssetMarket, StellarBlendPool, StellarContractConfig, StellarContractRole, StellarGovernanceProposalsPage, StellarHub, StellarLendingHoldersSide, StellarLendingContext, StellarLendingMarketSide, StellarMarketGraph, StellarMarketGraphQuery, StellarReserve, StellarSpoke, StellarTopHolders } from './lending-read-types';
|
|
17
17
|
type StellarReservesParams = {
|
|
18
18
|
hubId?: number;
|
|
19
19
|
spokeId?: number;
|
|
@@ -82,9 +82,34 @@ export declare const getStellarReserveGraph: (client: XOXNOClient, spokeId: numb
|
|
|
82
82
|
* sites read `read.reserve(spokeId, hubId, asset)` instead of threading the
|
|
83
83
|
* client through every call.
|
|
84
84
|
*/
|
|
85
|
+
/**
|
|
86
|
+
* Config and admin state for every watched contract, or for one address.
|
|
87
|
+
*
|
|
88
|
+
* Event-sourced by the indexer rather than read live from the chain, so this is
|
|
89
|
+
* also where `minBorrowCollateralUsdWad`, position limits and the aggregator
|
|
90
|
+
* addresses come from — `liveState` no longer needs an RPC round-trip for them.
|
|
91
|
+
*/
|
|
92
|
+
export declare const getStellarProtocolConfig: (client: XOXNOClient, init?: OurRequestInit) => Promise<StellarContractConfig[]>;
|
|
93
|
+
/** Config and admin state for a single contract address. */
|
|
94
|
+
export declare const getStellarContractConfig: (client: XOXNOClient, contractAddress: string, init?: OurRequestInit) => Promise<StellarContractConfig>;
|
|
95
|
+
/**
|
|
96
|
+
* Access-control grants, optionally narrowed to one contract. Revoked grants
|
|
97
|
+
* are included with `granted: false` — filter client-side when only current
|
|
98
|
+
* holders matter.
|
|
99
|
+
*/
|
|
100
|
+
export declare const getStellarContractRoles: (client: XOXNOClient, contractAddress?: string, init?: OurRequestInit) => Promise<StellarContractRole[]>;
|
|
101
|
+
/** Position-authorization grants for one account, including revoked ones. */
|
|
102
|
+
export declare const getStellarAccountDelegates: (client: XOXNOClient, accountId: number, init?: OurRequestInit) => Promise<StellarAccountDelegate[]>;
|
|
103
|
+
/** Blend pool approval state, including pools whose approval was revoked. */
|
|
104
|
+
export declare const getStellarBlendPools: (client: XOXNOClient, init?: OurRequestInit) => Promise<StellarBlendPool[]>;
|
|
85
105
|
export declare const stellarLendingRead: (client: XOXNOClient) => {
|
|
86
106
|
context: (init?: OurRequestInit) => Promise<StellarLendingContext>;
|
|
87
107
|
liveState: (init?: OurRequestInit) => Promise<StellarLendingLiveStateDto>;
|
|
108
|
+
protocolConfig: (init?: OurRequestInit) => Promise<StellarContractConfig[]>;
|
|
109
|
+
contractConfig: (contractAddress: string, init?: OurRequestInit) => Promise<StellarContractConfig>;
|
|
110
|
+
contractRoles: (contractAddress?: string, init?: OurRequestInit) => Promise<StellarContractRole[]>;
|
|
111
|
+
accountDelegates: (accountId: number, init?: OurRequestInit) => Promise<StellarAccountDelegate[]>;
|
|
112
|
+
blendPools: (init?: OurRequestInit) => Promise<StellarBlendPool[]>;
|
|
88
113
|
assets: (init?: OurRequestInit) => Promise<StellarAssetListItem[]>;
|
|
89
114
|
hubs: (init?: OurRequestInit) => Promise<StellarHubListItem[]>;
|
|
90
115
|
spokes: (init?: OurRequestInit) => Promise<StellarSpokeListItem[]>;
|