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