@xoxno/sdk-js 1.0.186 → 1.0.187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as o,Contract as r,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const u={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},l={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=u[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=l[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function _(e){const t=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 b=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],w=e=>new t(e).toScVal(),g=e=>new a(e).toI128(),y=e=>i.ScVal.scvU32(e),v=e=>new a("string"==typeof e?e:e.toString()).toU64(),S=e=>i.ScVal.scvBool(e),k=e=>i.ScVal.scvString(e),R=e=>i.ScVal.scvSymbol(e),T=()=>i.ScVal.scvVoid(),I=e=>i.ScVal.scvVec(e),x=(e,t=32)=>{const o=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(o,"hex");if(r.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${r.length} bytes from "${e}")`);return i.ScVal.scvBytes(r)},A=(e,t)=>null==e?T():t(e),E=(e,t)=>N({asset:w(t),hub_id:y(e)}),$=(e,t,o)=>i.ScVal.scvVec([E(e,t),g(o)]),B=e=>i.ScVal.scvVec(e.map((e=>$(e.hubId,e.asset,e.amount)))),N=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:R(t),val:e[t]})));return i.ScVal.scvMap(t)},O=e=>{const t=e.paths.map((e=>{const t=e.hops.map((e=>{return N({amount_out:g(e.amountOut),pool:w(e.pool),token_in:w(e.tokenIn),token_out:w(e.tokenOut),venue:(t=e.venue,i.ScVal.scvVec([R(t)]))});var t}));return N({hops:i.ScVal.scvVec(t),split_ppm:y(e.splitPpm)})}));return N({paths:i.ScVal.scvVec(t),referral_id:v(e.referralId??0),token_in:w(e.tokenIn),token_out:w(e.tokenOut),total_min_out:g(e.totalMinOut)})},P=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},U=()=>i.ScVal.scvBytes(Buffer.alloc(0)),q=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((o=e).length>0&&o.length%2==0&&/^[0-9a-fA-F]+$/.test(o)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var o;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 r=Buffer.from(t,"base64");if(0===r.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return r},L=e=>{if("string"==typeof e)return P(q(e));if(e instanceof Uint8Array)return 0===e.length?U():P(e);if(e&&"object"==typeof e)return"routeXdr"in(o=e)&&"string"==typeof o.routeXdr?P(q(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?P(q(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?P(q(e.bytes)):0===e.bytes.length?U():P(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");let o=0;for(const[e,r]of t.paths.entries()){if(!r||"number"!=typeof r.splitPpm||r.splitPpm<=0||!Array.isArray(r.hops)||0===r.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);o+=r.splitPpm;for(const[t,o]of r.hops.entries())if(!o||"string"!=typeof o.amountOut||"string"!=typeof o.pool||"string"!=typeof o.tokenIn||"string"!=typeof o.tokenOut||!b.includes(o.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have amountOut, pool, tokenIn, tokenOut, and a valid Soroban venue`)}if(1e6!==o)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` must sum to 1_000_000, got ${o}`);return t})(e),i.ScVal.scvBytes(Buffer.from(O(t).toXDR("base64"),"base64")));var t,o;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,o=Buffer.from(t,"hex");return i.ScVal.scvBytes(o)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function z(t,a,s){const i=t.controllerAddress??f(t.network),u=new r(i),l=new e(t.caller,t.sourceSequence);return{xdr:new n(l,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(u.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function W(e,t){const o=t.accountNonce??0,r=t.spokeId??0;return z(e,"supply",[w(e.caller),v(o),y(r),B([...t.assets])])}function D(e,t){return W(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function C(e,t){return z(e,"borrow",[w(e.caller),v(t.accountNonce),B([...t.borrows]),A(t.to,w)])}function G(e,t){return C(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return z(e,"withdraw",[w(e.caller),v(t.accountNonce),B([...t.withdrawals]),A(t.to,w)])}function F(e,t){return X(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function M(e,t){return z(e,"repay",[w(e.caller),v(t.accountNonce),B([...t.payments])])}function H(e,t){return M(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return z(e,"liquidate",[w(e.caller),v(t.accountNonce),B([...t.debtPayments])])}function Q(e,t){return z(e,"flash_loan",[w(e.caller),E(t.hubId,t.asset),g(t.amount),w(t.receiver),V(t.data)])}function Z(e,t){return z(e,"migrate_from_blend",[w(e.caller),v(t.accountId),y(t.spokeId),y(t.hubId),w(t.blendPool),I(t.collateralTokens.map(w)),I(t.supplyTokens.map(w)),(o=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(o.map((e=>{return t=e.token,o=e.amount,i.ScVal.scvVec([w(t),g(o)]);var t,o}))))]);var o}function J(e,t){const o=t.accountNonce??0,r=t.spokeId??0;return z(e,"multiply",[w(e.caller),v(o),y(r),E(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),E(t.debt.hubId,t.debt.asset),y(t.mode),L(t.steps),A(t.initialPayment,(e=>$(e.hubId,e.asset,e.amount))),A(t.convertSwap,L)])}function K(e,t){return z(e,"swap_debt",[w(e.caller),v(t.accountNonce),E(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),E(t.newDebt.hubId,t.newDebt.asset),L(t.steps)])}function Y(e,t){return z(e,"swap_collateral",[w(e.caller),v(t.accountNonce),E(t.current.hubId,t.current.asset),g(t.fromAmount),E(t.newCollateral.hubId,t.newCollateral.asset),L(t.steps)])}function ee(e,t){return z(e,"repay_debt_with_collateral",[w(e.caller),v(t.accountNonce),E(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),E(t.debt.hubId,t.debt.asset),L(t.steps),S(t.closePosition)])}const te="/stellar-lending",oe=25,re=encodeURIComponent,ae=(e,t)=>e.fetchWithTimeout(`${te}/context`,t),ne=(e,t)=>e.fetchWithTimeout(`${te}/assets`,t),se=(e,t)=>e.fetchWithTimeout(`${te}/hubs`,t),ie=(e,t)=>e.fetchWithTimeout(`${te}/spokes`,t),ue=(e,t={},o)=>{const{hubId:r,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${te}/reserves`,{...o,params:{...void 0!==r?{hubId:r}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},le=(e,t,o,r,a)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}`,a),ce=(e,t,o,r,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}/holders`,{...n,params:{side:a}}),pe=(e,t,o)=>e.fetchWithTimeout(`${te}/assets/${re(t)}`,o),de=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/page`,{...r,params:{...o}}),me=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/markets`,{...r,params:{side:o}}),fe=(e,t,o)=>e.fetchWithTimeout(`${te}/hubs/${t}`,o),he=(e,t,o)=>e.fetchWithTimeout(`${te}/spokes/${t}`,o),_e=(e,t,o)=>e.fetchWithTimeout(`${te}/users/${re(t)}/positions`,o),be=(e,t,o={},r)=>{const{skip:a,top:n}=o;return e.fetchWithTimeout(`${te}/users/${re(t)}/activity`,{...r,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},we=(e,t,o)=>e.fetchWithTimeout(`${te}/accounts/${re(t)}/positions`,o),ge=(e,t={},o)=>{const{top:r=oe,continuationToken:a}=t;return e.fetchWithTimeout(`${te}/governance/proposals`,{...o,params:{top:r,...a?{continuationToken:a}:{}}})},ye=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/graph`,{...r,params:{...o}}),ve=(e,t,o,r)=>e.fetchWithTimeout(`${te}/hubs/${t}/graph`,{...r,params:{...o}}),Se=(e,t,o,r)=>e.fetchWithTimeout(`${te}/spokes/${t}/graph`,{...r,params:{...o}}),ke=(e,t,o,r,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}/graph`,{...n,params:{...a}}),Re=e=>({context:t=>ae(e,t),assets:t=>ne(e,t),hubs:t=>se(e,t),spokes:t=>ie(e,t),reserves:(t,o)=>{return void 0===(r=t)||"hubId"in r||"spokeId"in r||"asset"in r?ue(e,t,o):ue(e,{},t);var r},reserve:(t,o,r,a)=>le(e,t,o,r,a),reserveHolders:(t,o,r,a,n)=>ce(e,t,o,r,a,n),asset:(t,o)=>pe(e,t,o),assetMarkets:(t,o,r)=>me(e,t,o,r),hub:(t,o)=>fe(e,t,o),spoke:(t,o)=>he(e,t,o),userPositions:(t,o)=>_e(e,t,o),userActivity:(t,o,r)=>be(e,t,o,r),accountPositions:(t,o)=>we(e,t,o),governanceProposals:(t,o)=>ge(e,t,o),assetGraph:(t,o,r)=>ye(e,t,o,r),hubGraph:(t,o,r)=>ve(e,t,o,r),spokeGraph:(t,o,r)=>Se(e,t,o,r),reserveGraph:(t,o,r,a,n)=>ke(e,t,o,r,a,n)}),Te={Single:0,PrimaryWithAnchor:1},Ie=e=>N({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:y(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),xe=e=>N({asset_decimals:y(e.assetDecimals),asset_id:w(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:y(e.flashloanFeeBps),is_flashloanable:S(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:y(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ae=e=>N({max_borrow_positions:y(e.maxBorrowPositions),max_supply_positions:y(e.maxSupplyPositions)}),Ee=e=>{const t=e.kind;switch(t){case"Stellar":return I([R("Stellar"),w(e.value)]);case"Symbol":return I([R("Symbol"),R(e.value)]);case"String":return I([R("String"),k(e.value)]);default:throw new Error(`Stellar builder: unknown oracle asset ref kind "${t}"`)}},$e=(e,t)=>{if("Twap"===e){if("number"!=typeof t)throw new Error("Stellar builder: oracle source with Twap read mode requires `twapRecords`");return I([R("Twap"),y(t)])}return I([R("Spot")])},Be=e=>{const t=e.provider;if("ReflectorSep40"===t){if(!e.asset)throw new Error("Stellar builder: Reflector oracle source requires `asset`");return I([R("Reflector"),N({asset:Ee(e.asset),contract:w(e.contract),read_mode:$e(e.readMode,e.twapRecords)})])}if("RedStonePriceFeed"===t){if("string"!=typeof e.feedId)throw new Error("Stellar builder: RedStone oracle source requires `feedId`");if("number"!=typeof e.maxStaleSeconds)throw new Error("Stellar builder: RedStone oracle source requires `maxStaleSeconds`");return I([R("RedStone"),N({contract:w(e.contract),feed_id:k(e.feedId),max_stale_seconds:v(e.maxStaleSeconds)})])}throw new Error(`Stellar builder: unknown oracle provider "${t}"`)},Ne=e=>{const t=Te[e.strategy];if(void 0===t)throw new Error(`Stellar builder: unknown oracle strategy "${e.strategy}"`);return N({anchor:(o=e.anchor,I(null==o?[R("None")]:[R("Some"),Be(o)])),max_price_stale_seconds:v(e.maxPriceStaleSeconds),max_sanity_price_wad:g(e.maxSanityPriceWad),min_sanity_price_wad:g(e.minSanityPriceWad),primary:Be(e.primary),strategy:y(t),tolerance_bps:y(e.toleranceBps)});var o};function Oe(e,t){return z(e,"upgrade",[x(t.wasmHash)])}function Pe(e,t){return z(e,"migrate",[y(t.newVersion)])}function Ue(e){return z(e,"pause",[])}function qe(e){return z(e,"unpause",[])}function Le(e,t){return z(e,"grant_role",[w(t.account),R(t.role)])}function Ve(e,t){return z(e,"revoke_role",[w(t.account),R(t.role)])}function ze(e,t){return z(e,"transfer_ownership",[w(t.newOwner),y(t.liveUntilLedger)])}function We(e){return z(e,"accept_ownership",[])}function De(e,t){return z(e,"set_aggregator",[w(t.aggregator)])}function Ce(e,t){return z(e,"set_accumulator",[w(t.accumulator)])}function Ge(e,t){return z(e,"set_liquidity_pool_template",[x(t.wasmHash)])}function Xe(e,t){return z(e,"set_position_limits",[Ae(t)])}function Fe(e,t){return z(e,"approve_token",[w(t.token)])}function Me(e,t){return z(e,"revoke_token",[w(t.token)])}function He(e,t){return z(e,"set_market_oracle_config",[E(t.hubId,t.asset),Ne(t.config)])}function je(e,t){return z(e,"set_oracle_tolerance",[w(t.asset),N({lower_ratio_bps:y(t.lowerRatioBps),upper_ratio_bps:y(t.upperRatioBps)})])}function Qe(e,t){return z(e,"update_indexes",[w(e.caller),I(t.assets.map((e=>E(e.hubId,e.asset))))])}function Ze(e,t){return z(e,"renew_account",[w(e.caller),v(t.accountNonce)])}function Je(e,t){return z(e,"create_liquidity_pool",[y(t.hubId),w(t.asset),xe(t.params)])}function Ke(e,t){return z(e,"upgrade_liquidity_pool_params",[E(t.hubId,t.asset),Ie(t.params)])}function Ye(e,t){return z(e,"claim_revenue",[w(e.caller),I(t.assets.map((e=>E(e.hubId,e.asset))))])}function et(e,t){return z(e,"add_rewards",[w(e.caller),B(t.rewards)])}function tt(e,t){return z(e,"update_account_threshold",[w(e.caller),S(t.hasRisks),I(t.accountNonces.map((e=>v(e))))])}const ot="00".repeat(32),rt=e=>{if("string"==typeof e)return x(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)},at=(e,...t)=>I([R(e),...t]),nt=e=>N({new_owner:w(e.newOwner),live_until_ledger:y(e.liveUntilLedger)}),st=e=>N({asset:w(e.asset),bonus:y(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:S(e.canBorrow),can_collateral:S(e.canCollateral),frozen:S(e.frozen),hub_id:y(e.hubId),paused:S(e.paused),liquidation_fees:y(e.liquidationFees),ltv:y(e.ltv),oracle_override:I([R("None")]),spoke_id:y(e.spokeId),supply_cap:g(e.supplyCap),threshold:y(e.threshold)}),it=e=>N({account:w(e.account),role:R(e.role)});function ut(t,a,s){const i=t.governanceAddress??_(t.network),u=new r(i),l=new e(t.caller,t.sourceSequence);return{xdr:new n(l,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(u.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const lt=(e,t,o)=>ut(e,"propose",[w(e.caller),t,rt(o)]),ct=(e,t,o)=>ut(e,"execute_self",[T(),t,rt(o)]);function pt(e,t,o){return lt(e,at("SetAggregator",w(t.aggregator)),o)}function dt(e,t,o){return lt(e,at("SetAccumulator",w(t.accumulator)),o)}function mt(e,t,o){return lt(e,at("SetLiquidityPoolTemplate",x(t.wasmHash)),o)}function ft(e,t,o){return lt(e,at("SetPositionLimits",Ae(t)),o)}function ht(e,t){return lt(e,at("CreateHub"),t)}function _t(e,t){return lt(e,at("AddSpoke"),t)}function bt(e,t,o){return lt(e,at("RemoveSpoke",y(t.spokeId)),o)}function wt(e,t,o){return lt(e,at("AddAssetToSpoke",st(t)),o)}function gt(e,t,o){return lt(e,at("EditAssetInSpoke",st(t)),o)}function yt(e,t,o){return lt(e,at("RemoveAssetFromSpoke",N({hub_asset:E((r=t).hubId,r.asset),spoke_id:y(r.spokeId)})),o);var r}function vt(e,t,o){return lt(e,at("SetSpokeLiquidationCurve",N({hf_for_max_bonus_wad:g((r=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:y(r.liquidationBonusFactorBps),spoke_id:y(r.spokeId),target_hf_wad:g(r.targetHfWad)})),o);var r}function St(e,t,o){return lt(e,at("SetPositionManager",w(t.manager),S(t.isActive)),o)}function kt(e,t,o){return lt(e,at("SetMinBorrowCollateralUsd",g(t.floorWad)),o)}function Rt(e,t,o){return lt(e,at("ApproveToken",w(t.token)),o)}function Tt(e,t,o){return lt(e,at("RevokeToken",w(t.token)),o)}function It(e,t,o){return lt(e,at("ApproveBlendPool",w(t.pool)),o)}function xt(e,t,o){return lt(e,at("RevokeBlendPool",w(t.pool)),o)}function At(e,t,o){return lt(e,at("CreateLiquidityPool",N({asset:w((r=t).asset),hub_id:y(r.hubId),params:xe(r.params)})),o);var r}function Et(e,t,o){return lt(e,at("UpgradeLiquidityPoolParams",N({hub_asset:E((r=t).hubId,r.asset),params:Ie(r.params)})),o);var r}function $t(e,t){return lt(e,at("DeployPool"),t)}function Bt(e,t,o){return lt(e,at("UpgradePool",x(t.wasmHash)),o)}function Nt(e,t,o){return lt(e,at("UpgradeController",x(t.wasmHash)),o)}function Ot(e,t,o){return lt(e,at("MigrateController",y(t.newVersion)),o)}function Pt(e,t,o){return lt(e,at("TransferCtrlOwnership",nt(t)),o)}function Ut(e,t,o){return lt(e,at("ConfigureMarketOracle",N({cfg:Ne((r=t).config),hub_asset:E(r.hubId,r.asset)})),o);var r}function qt(e,t,o){return lt(e,at("EditOracleTolerance",N({asset:w((r=t).asset),tolerance:y(r.tolerance)})),o);var r}function Lt(e,t,o){return lt(e,at("UpgradeGov",x(t.wasmHash)),o)}function Vt(e,t,o){return lt(e,at("UpdateGovDelay",y(t.newDelay)),o)}function zt(e,t,o){return lt(e,at("GrantGovRole",it(t)),o)}function Wt(e,t,o){return lt(e,at("RevokeGovRole",it(t)),o)}function Dt(e,t,o){return lt(e,at("TransferGovOwnership",nt(t)),o)}function Ct(e,t){const o=I(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),r=rt(t.predecessor??ot);return ut(e,"execute",[T(),w(t.target),R(t.functionName),o,r,rt(t.salt)])}function Gt(e,t,o){return ct(e,at("UpgradeGov",x(t.wasmHash)),o)}function Xt(e,t,o){return ct(e,at("UpdateGovDelay",y(t.newDelay)),o)}function Ft(e,t,o){return ct(e,at("GrantGovRole",it(t)),o)}function Mt(e,t,o){return ct(e,at("RevokeGovRole",it(t)),o)}function Ht(e,t,o){return ct(e,at("TransferGovOwnership",nt(t)),o)}const jt=e=>e.toXDR("base64"),Qt=e=>i.ScVal.fromXDR(e,"base64"),Zt=e=>e.map((e=>String(s(Qt(e))))).join(":"),Jt=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Kt=e=>Number(e),Yt=e=>String(e),eo=e=>null==e?void 0:Jt(e),to=e=>null==e?void 0:Yt(e),oo=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),ro=["None","Multiply","Long","Short"],ao=["Single","PrimaryWithAnchor"],no=["ReflectorSep40","RedStonePriceFeed"],so=["Spot","Twap"],io=["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"],uo=e=>Array.isArray(e)?e:[],lo=(e,t)=>{const o="Borrow"===t;return{action:(r=e[0],io[Kt(r)]??Jt(r)),positionType:t,hubId:Kt(e[1]),asset:Yt(e[2]),scaledAmountRay:Jt(e[3]),indexRay:Jt(e[4]),amount:Jt(e[5]),liquidationThresholdBps:o?void 0:Kt(e[6]),liquidationBonusBps:o?void 0:Kt(e[7]),loanToValueBps:o?void 0:Kt(e[8]),liquidationFeesBps:o?void 0:Kt(e[9])};var r},co=e=>{return{owner:Yt(e[0]),spokeId:Kt(e[1]),mode:(t=e[2],ro[Kt(t)]??"None")};var t},po=(e,t)=>{const o=so[Kt(e[`${t}_read_mode`])]??"Spot",r=e[`${t}_asset`],a=e[`${t}_symbol`],n=null!=r?{kind:"Stellar",value:Yt(r)}:null!=a?{kind:"Symbol",value:Yt(a)}:void 0;return{provider:no[Kt(e[`${t}_provider`])]??"ReflectorSep40",contractAddress:Yt(e[`${t}_contract`]),asset:n,feedId:to(e[`${t}_feed_id`]),readMode:o,twapRecords:"Twap"===o?Kt(e[`${t}_twap_records`]):void 0,decimals:Kt(e[`${t}_decimals`]),resolutionSeconds:Kt(e[`${t}_resolution_seconds`]),maxStaleSeconds:Kt(e[`${t}_max_stale_seconds`])}},mo=e=>{const t=null!==e.anchor_provider&&void 0!==e.anchor_provider;return{baseTokenId:Yt(e.base_token_id),quoteTokenId:Yt(e.quote_token_id),tolerance:{upperRatio:Kt(e.upper_ratio_bps??e.tolerance?.upper_ratio_bps),lowerRatio:Kt(e.lower_ratio_bps??e.tolerance?.lower_ratio_bps)},assetDecimals:Kt(e.asset_decimals),maxPriceStaleSeconds:Kt(e.max_price_stale_seconds),strategy:ao[Kt(e.strategy)]??"Single",primary:po(e,"primary"),anchor:t?po(e,"anchor"):void 0,primaryQuoteToken:to(e.primary_quote_token),anchorQuoteToken:to(e.anchor_quote_token),minSanityPriceWad:eo(e.min_sanity_price_wad),maxSanityPriceWad:eo(e.max_sanity_price_wad)}},fo={"market:create":e=>({topic:"market:create",data:{hubId:Kt(e.hub_id),baseAsset:Yt(e.base_asset),maxBorrowRate:Jt(e.max_borrow_rate),baseBorrowRate:Jt(e.base_borrow_rate),slope1:Jt(e.slope1),slope2:Jt(e.slope2),slope3:Jt(e.slope3),midUtilization:Jt(e.mid_utilization),optimalUtilization:Jt(e.optimal_utilization),maxUtilization:Jt(e.max_utilization),reserveFactor:Kt(e.reserve_factor),marketAddress:Yt(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Yt(e.asset),maxBorrowRateRay:Jt(e.max_borrow_rate),baseBorrowRateRay:Jt(e.base_borrow_rate),slope1Ray:Jt(e.slope1),slope2Ray:Jt(e.slope2),slope3Ray:Jt(e.slope3),midUtilizationRay:Jt(e.mid_utilization),optimalUtilizationRay:Jt(e.optimal_utilization),maxUtilizationRay:Jt(e.max_utilization),reserveFactorBps:Kt(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:uo(e).map((e=>{return t=uo(e),{hubId:Kt(t[0]),asset:Yt(t[1]),timestamp:Kt(t[2]),supplyIndexRay:Jt(t[3]),borrowIndexRay:Jt(t[4]),cash:Jt(t[5]),suppliedRay:Jt(t[6]),borrowedRay:Jt(t[7]),revenueRay:Jt(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:uo(e).map((e=>{const t=e;return{hubId:Kt(t.hub_id),asset:Yt(t.asset),params:(o=t.params,{maxBorrowRateRay:Jt(o.max_borrow_rate),baseBorrowRateRay:Jt(o.base_borrow_rate),slope1Ray:Jt(o.slope1),slope2Ray:Jt(o.slope2),slope3Ray:Jt(o.slope3),midUtilizationRay:Jt(o.mid_utilization),optimalUtilizationRay:Jt(o.optimal_utilization),maxUtilizationRay:Jt(o.max_utilization),reserveFactorBps:Kt(o.reserve_factor),isFlashloanable:Boolean(o.is_flashloanable),flashloanFeeBps:Kt(o.flashloan_fee),assetId:Yt(o.asset_id),assetDecimals:Kt(o.asset_decimals)})};var o}))}}),"position:batch_update":e=>{const t=uo(e);return{topic:"position:batch_update",data:{accountId:Jt(t[0]),accountAttributes:co(uo(t[1])),updates:[...uo(t[2]).map((e=>lo(uo(e),"Deposit"))),...uo(t[3]).map((e=>lo(uo(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Kt(e.hub_id),asset:Yt(e.asset),receiver:Yt(e.receiver),caller:Yt(e.caller),amount:Jt(e.amount),fee:Jt(e.fee)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Yt(e.asset),oracle:mo(e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Yt(e.liquidator),accountId:Jt(e.account_id),repaidUsdWad:Jt(e.repaid_usd_wad),bonusBps:Jt(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Jt(e.account_id),totalBorrowUsdWad:Jt(e.total_borrow_usd_wad),totalCollateralUsdWad:Jt(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Yt(e.token),amount:Jt(e.amount),usdValueWad:Jt(e.usd_value_wad),accountId:Jt(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Kt(e.hub_id),asset:Yt(e.asset),amount:Jt(e.amount),fee:Jt(e.fee),amountSent:Jt(e.amount_sent)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:oo(e.wasm_hash),approved:Boolean(e.approved)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Yt(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Yt(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:oo(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Kt(e.max_supply_positions),maxBorrowPositions:Kt(e.max_borrow_positions)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Yt(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Kt(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Jt(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Jt(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Kt(t.liquidation_bonus_factor_bps)}}}},ho=Object.freeze(Object.keys(fo));function _o(e,t){const o=Zt(e),r=fo[o];return r?r(s(Qt(t))):null}const bo="XLENDXLM-a7c9f3",wo=1e4;function go(e){const t=BigInt(e).toString(16),o=t.length%2==0?t:`0${t}`;return`${bo}-${o}`}function yo(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function vo(e,t=0){return 1e4*e+t}function So(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const ko=(e,t,o)=>{const r=new URL(t,e.endsWith("/")?e:`${e}/`);if(o)for(const[e,t]of Object.entries(o))void 0!==t&&r.searchParams.set(e,String(t));return r.toString()},Ro=e=>e.baseUrl??d[e.network];async function To(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const o=ko(Ro(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}),r=await fetch(o,t.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${o} — ${e}`)}return await r.json()}async function Io(e){const t=ko(Ro(e),"api/v1/tokens"),o=await fetch(t,e.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${t} — ${e}`)}return await o.json()}const xo=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Ao=e=>O(e).toXDR("base64");function Eo(t,a){const s=t.routerAddress??h(t.network),i=new r(s),u=new e(t.caller,t.sourceSequence),l=L(xo(a,t.referralId));return{xdr:new n(u,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",w(t.caller),g(t.totalIn),l)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function $o(e,t){return Eo(e,t)}function Bo(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(Po),splitPpm:e.splitPpm}))):[{hops:e.hops.map(Po),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function No(e,t={}){const o=e;return"string"==typeof o.routeXdr&&o.routeXdr.length>0?{routeXdr:o.routeXdr}:Bo(e,t)}const Oo=Bo,Po=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function Uo(e,t){const o=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${o}`)}async function qo(e,t,o){const r=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(r)).toXDR()}catch(e){if(o?.invokedContractId)throw Uo(o.invokedContractId,e);throw e}}async function Lo(e,t,o){return qo(e,t.xdr,o)}function Vo(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 zo(e,t){return new Uint8Array(0)}const Wo=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 Do(t){const o=new e(t.caller,t.sourceSequence),a=new r(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(Wo(t.message)),i.ScVal.scvBytes(Wo(t.attestation)));return{xdr:new n(o,{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:"InvalidPoolTemplate",message:"The liquidity pool template hash is 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."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetsLimitReached",message:"This spoke has reached its asset limit."},314:{name:"SpokeCapBelowUsage",message:"The new cap is below current usage on this spoke asset."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},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 Go(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const o=Number(t[1]),r=Co[o];return r?{code:o,...r}:null}export{l as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,ot as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,u as STELLAR_LENDING_CONTROLLER,ho as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,wo as SYNTHETIC_EVENT_ORDER_STRIDE,bo as XOXNO_LENDING_STELLAR_TICKER,zo as buildSameTokenRepaySwapSteps,We as buildStellarAcceptOwnershipTx,et as buildStellarAddRewardsTx,Fe as buildStellarApproveTokenTx,$o as buildStellarBatchSwapTx,C as buildStellarBorrowBatchTx,G as buildStellarBorrowTx,Do as buildStellarCctpForwardTx,Ye as buildStellarClaimRevenueTx,Je as buildStellarCreateLiquidityPoolTx,Eo as buildStellarExecuteStrategyTx,Q as buildStellarFlashLoanTx,Gt as buildStellarGovernanceExecuteGovernanceUpgradeTx,Ft as buildStellarGovernanceExecuteGrantGovernanceRoleTx,Mt as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,Ht as buildStellarGovernanceExecuteTransferGovOwnTx,Ct as buildStellarGovernanceExecuteTx,Xt as buildStellarGovernanceExecuteUpdateDelayTx,Le as buildStellarGrantRoleTx,go as buildStellarLendingIdentifier,j as buildStellarLiquidateTx,Z as buildStellarMigrateFromBlendTx,Pe as buildStellarMigrateTx,J as buildStellarMultiplyTx,Ue as buildStellarPauseTx,wt as buildStellarProposeAddAssetToSpokeTx,_t as buildStellarProposeAddSpokeTx,It as buildStellarProposeApproveBlendPoolTx,Rt as buildStellarProposeApproveTokenTx,Ut as buildStellarProposeConfigureMarketOracleTx,ht as buildStellarProposeCreateHubTx,At as buildStellarProposeCreateLiquidityPoolTx,$t as buildStellarProposeDeployPoolTx,gt as buildStellarProposeEditAssetInSpokeTx,qt as buildStellarProposeEditOracleToleranceTx,Lt as buildStellarProposeGovernanceUpgradeTx,zt as buildStellarProposeGrantGovernanceRoleTx,Ot as buildStellarProposeMigrateControllerTx,yt as buildStellarProposeRemoveAssetFromSpokeTx,bt as buildStellarProposeRemoveSpokeTx,xt as buildStellarProposeRevokeBlendPoolTx,Wt as buildStellarProposeRevokeGovernanceRoleTx,Tt as buildStellarProposeRevokeTokenTx,dt as buildStellarProposeSetAccumulatorTx,pt as buildStellarProposeSetAggregatorTx,kt as buildStellarProposeSetMinBorrowCollatTx,mt as buildStellarProposeSetPoolTemplateTx,ft as buildStellarProposeSetPositionLimitsTx,St as buildStellarProposeSetPositionManagerTx,vt as buildStellarProposeSetSpokeLiquidationCurveTx,Pt as buildStellarProposeTransferCtrlOwnershipTx,Dt as buildStellarProposeTransferGovOwnTx,Vt as buildStellarProposeUpdateDelayTx,Nt as buildStellarProposeUpgradeControllerTx,Et as buildStellarProposeUpgradePoolParamsTx,Bt as buildStellarProposeUpgradePoolTx,Ze as buildStellarRenewAccountTx,M as buildStellarRepayBatchTx,ee as buildStellarRepayDebtWithCollateralTx,H as buildStellarRepayTx,Ve as buildStellarRevokeRoleTx,Me as buildStellarRevokeTokenTx,Ce as buildStellarSetAccumulatorTx,De as buildStellarSetAggregatorTx,Ge as buildStellarSetLiquidityPoolTemplateTx,He as buildStellarSetMarketOracleConfigTx,je as buildStellarSetOracleToleranceTx,Xe as buildStellarSetPositionLimitsTx,W as buildStellarSupplyBatchTx,D as buildStellarSupplyTx,Y as buildStellarSwapCollateralTx,K as buildStellarSwapDebtTx,ze as buildStellarTransferOwnershipTx,qe as buildStellarUnpauseTx,tt as buildStellarUpdateAccountThresholdTx,Qe as buildStellarUpdateIndexesTx,Oe as buildStellarUpgradeControllerTx,Ke as buildStellarUpgradeLiquidityPoolParamsTx,X as buildStellarWithdrawBatchTx,F as buildStellarWithdrawTx,z as buildTx,_o as decodeStellarLendingEvent,Ie as encodeInterestRateModel,Ne as encodeMarketOracleConfigInput,xe as encodeMarketParamsRaw,Be as encodeOracleSourceConfigInput,Ae as encodePositionLimits,Ao as encodeStrategyPayloadToRouteXdr,yo as extractEventOrder,we as getStellarAccountPositions,To as getStellarAggregatorQuote,h as getStellarAggregatorRouter,pe as getStellarAsset,ye as getStellarAssetGraph,me as getStellarAssetMarkets,de as getStellarAssetPage,ne as getStellarAssets,_ as getStellarGovernance,ge as getStellarGovernanceProposals,fe as getStellarHub,ve as getStellarHubGraph,se as getStellarHubs,ae as getStellarLendingContext,f as getStellarLendingController,Io as getStellarQuoteTokens,le as getStellarReserve,ke as getStellarReserveGraph,ce as getStellarReserveHolders,ue as getStellarReserves,he as getStellarSpoke,Se as getStellarSpokeGraph,ie as getStellarSpokes,be as getStellarUserActivity,_e as getStellarUserPositions,Oo as mapQuoteResponseToAggregatorSwap,Bo as mapQuoteResponseToStrategyPayload,No as mapQuoteResponseToStrategySwap,Go as mapSorobanError,So as mapStellarPositionActivityType,Lo as prepareStellarBuiltTx,qo as prepareStellarTxXdr,Zt as stellarLendingDispatchKey,Re as stellarLendingRead,vo as syntheticEventOrder,Uo as tagStellarInvokedContractError,jt as toBase64Xdr,Vo as toStellarPositionMode};
1
+ "undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as o,Contract as r,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const u={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},l={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=u[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=l[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function _(e){const t=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 b=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],w=e=>new t(e).toScVal(),g=e=>new a(e).toI128(),y=e=>i.ScVal.scvU32(e),v=e=>new a("string"==typeof e?e:e.toString()).toU64(),S=e=>i.ScVal.scvBool(e),k=e=>i.ScVal.scvString(e),R=e=>i.ScVal.scvSymbol(e),T=()=>i.ScVal.scvVoid(),I=e=>i.ScVal.scvVec(e),x=(e,t=32)=>{const o=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(o,"hex");if(r.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${r.length} bytes from "${e}")`);return i.ScVal.scvBytes(r)},A=(e,t)=>null==e?T():t(e),E=(e,t)=>N({asset:w(t),hub_id:y(e)}),$=(e,t,o)=>i.ScVal.scvVec([E(e,t),g(o)]),B=e=>i.ScVal.scvVec(e.map((e=>$(e.hubId,e.asset,e.amount)))),N=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:R(t),val:e[t]})));return i.ScVal.scvMap(t)},O=e=>{const t=e.paths.map((e=>{const t=e.hops.map((e=>{return N({amount_out:g(e.amountOut),pool:w(e.pool),token_in:w(e.tokenIn),token_out:w(e.tokenOut),venue:(t=e.venue,i.ScVal.scvVec([R(t)]))});var t}));return N({hops:i.ScVal.scvVec(t),split_ppm:y(e.splitPpm)})}));return N({paths:i.ScVal.scvVec(t),referral_id:v(e.referralId??0),token_in:w(e.tokenIn),token_out:w(e.tokenOut),total_min_out:g(e.totalMinOut)})},P=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},U=()=>i.ScVal.scvBytes(Buffer.alloc(0)),q=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((o=e).length>0&&o.length%2==0&&/^[0-9a-fA-F]+$/.test(o)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var o;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 r=Buffer.from(t,"base64");if(0===r.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return r},L=e=>{if("string"==typeof e)return P(q(e));if(e instanceof Uint8Array)return 0===e.length?U():P(e);if(e&&"object"==typeof e)return"routeXdr"in(o=e)&&"string"==typeof o.routeXdr?P(q(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?P(q(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?P(q(e.bytes)):0===e.bytes.length?U():P(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");let o=0;for(const[e,r]of t.paths.entries()){if(!r||"number"!=typeof r.splitPpm||r.splitPpm<=0||!Array.isArray(r.hops)||0===r.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);o+=r.splitPpm;for(const[t,o]of r.hops.entries())if(!o||"string"!=typeof o.amountOut||"string"!=typeof o.pool||"string"!=typeof o.tokenIn||"string"!=typeof o.tokenOut||!b.includes(o.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have amountOut, pool, tokenIn, tokenOut, and a valid Soroban venue`)}if(1e6!==o)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` must sum to 1_000_000, got ${o}`);return t})(e),i.ScVal.scvBytes(Buffer.from(O(t).toXDR("base64"),"base64")));var t,o;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,o=Buffer.from(t,"hex");return i.ScVal.scvBytes(o)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function z(t,a,s){const i=t.controllerAddress??f(t.network),u=new r(i),l=new e(t.caller,t.sourceSequence);return{xdr:new n(l,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(u.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function W(e,t){const o=t.accountNonce??0,r=t.spokeId??0;return z(e,"supply",[w(e.caller),v(o),y(r),B([...t.assets])])}function D(e,t){return W(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function C(e,t){return z(e,"borrow",[w(e.caller),v(t.accountNonce),B([...t.borrows]),A(t.to,w)])}function G(e,t){return C(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return z(e,"withdraw",[w(e.caller),v(t.accountNonce),B([...t.withdrawals]),A(t.to,w)])}function F(e,t){return X(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function M(e,t){return z(e,"repay",[w(e.caller),v(t.accountNonce),B([...t.payments])])}function H(e,t){return M(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return z(e,"liquidate",[w(e.caller),v(t.accountNonce),B([...t.debtPayments])])}function Q(e,t){return z(e,"flash_loan",[w(e.caller),E(t.hubId,t.asset),g(t.amount),w(t.receiver),V(t.data)])}function Z(e,t){return z(e,"migrate_from_blend",[w(e.caller),v(t.accountId),y(t.spokeId),y(t.hubId),w(t.blendPool),I(t.collateralTokens.map(w)),I(t.supplyTokens.map(w)),(o=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(o.map((e=>{return t=e.token,o=e.amount,i.ScVal.scvVec([w(t),g(o)]);var t,o}))))]);var o}function J(e,t){const o=t.accountNonce??0,r=t.spokeId??0;return z(e,"multiply",[w(e.caller),v(o),y(r),E(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),E(t.debt.hubId,t.debt.asset),y(t.mode),L(t.steps),A(t.initialPayment,(e=>$(e.hubId,e.asset,e.amount))),A(t.convertSwap,L)])}function K(e,t){return z(e,"swap_debt",[w(e.caller),v(t.accountNonce),E(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),E(t.newDebt.hubId,t.newDebt.asset),L(t.steps)])}function Y(e,t){return z(e,"swap_collateral",[w(e.caller),v(t.accountNonce),E(t.current.hubId,t.current.asset),g(t.fromAmount),E(t.newCollateral.hubId,t.newCollateral.asset),L(t.steps)])}function ee(e,t){return z(e,"repay_debt_with_collateral",[w(e.caller),v(t.accountNonce),E(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),E(t.debt.hubId,t.debt.asset),L(t.steps),S(t.closePosition)])}const te="/stellar-lending",oe=25,re=encodeURIComponent,ae=(e,t)=>e.fetchWithTimeout(`${te}/context`,t),ne=(e,t)=>e.fetchWithTimeout(`${te}/assets`,t),se=(e,t)=>e.fetchWithTimeout(`${te}/hubs`,t),ie=(e,t)=>e.fetchWithTimeout(`${te}/spokes`,t),ue=(e,t={},o)=>{const{hubId:r,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${te}/reserves`,{...o,params:{...void 0!==r?{hubId:r}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},le=(e,t,o,r,a)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}`,a),ce=(e,t,o,r,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}/holders`,{...n,params:{side:a}}),pe=(e,t,o)=>e.fetchWithTimeout(`${te}/assets/${re(t)}`,o),de=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/page`,{...r,params:{...o}}),me=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/markets`,{...r,params:{side:o}}),fe=(e,t,o)=>e.fetchWithTimeout(`${te}/hubs/${t}`,o),he=(e,t,o)=>e.fetchWithTimeout(`${te}/spokes/${t}`,o),_e=(e,t,o)=>e.fetchWithTimeout(`${te}/users/${re(t)}/positions`,o),be=(e,t,o={},r)=>{const{skip:a,top:n}=o;return e.fetchWithTimeout(`${te}/users/${re(t)}/activity`,{...r,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},we=(e,t,o)=>e.fetchWithTimeout(`${te}/accounts/${re(t)}/positions`,o),ge=(e,t={},o)=>{const{top:r=oe,continuationToken:a}=t;return e.fetchWithTimeout(`${te}/governance/proposals`,{...o,params:{top:r,...a?{continuationToken:a}:{}}})},ye=(e,t,o,r)=>e.fetchWithTimeout(`${te}/assets/${re(t)}/graph`,{...r,params:{...o}}),ve=(e,t,o,r)=>e.fetchWithTimeout(`${te}/hubs/${t}/graph`,{...r,params:{...o}}),Se=(e,t,o,r)=>e.fetchWithTimeout(`${te}/spokes/${t}/graph`,{...r,params:{...o}}),ke=(e,t,o,r,a,n)=>e.fetchWithTimeout(`${te}/reserves/${t}/${o}/${re(r)}/graph`,{...n,params:{...a}}),Re=e=>({context:t=>ae(e,t),assets:t=>ne(e,t),hubs:t=>se(e,t),spokes:t=>ie(e,t),reserves:(t,o)=>{return void 0===(r=t)||"hubId"in r||"spokeId"in r||"asset"in r?ue(e,t,o):ue(e,{},t);var r},reserve:(t,o,r,a)=>le(e,t,o,r,a),reserveHolders:(t,o,r,a,n)=>ce(e,t,o,r,a,n),asset:(t,o)=>pe(e,t,o),assetMarkets:(t,o,r)=>me(e,t,o,r),hub:(t,o)=>fe(e,t,o),spoke:(t,o)=>he(e,t,o),userPositions:(t,o)=>_e(e,t,o),userActivity:(t,o,r)=>be(e,t,o,r),accountPositions:(t,o)=>we(e,t,o),governanceProposals:(t,o)=>ge(e,t,o),assetGraph:(t,o,r)=>ye(e,t,o,r),hubGraph:(t,o,r)=>ve(e,t,o,r),spokeGraph:(t,o,r)=>Se(e,t,o,r),reserveGraph:(t,o,r,a,n)=>ke(e,t,o,r,a,n)}),Te={Single:0,PrimaryWithAnchor:1},Ie="RedStonePriceFeed",xe=e=>N({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:y(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ae=e=>N({asset_decimals:y(e.assetDecimals),asset_id:w(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:y(e.flashloanFeeBps),is_flashloanable:S(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:y(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ee=e=>N({max_borrow_positions:y(e.maxBorrowPositions),max_supply_positions:y(e.maxSupplyPositions)}),$e=e=>{const t=e.kind;switch(t){case"Stellar":return I([R("Stellar"),w(e.value)]);case"Symbol":return I([R("Symbol"),R(e.value)]);case"String":return I([R("String"),k(e.value)]);default:throw new Error(`Stellar builder: unknown oracle asset ref kind "${t}"`)}},Be=(e,t)=>{if("Twap"===e){if("number"!=typeof t)throw new Error("Stellar builder: oracle source with Twap read mode requires `twapRecords`");return I([R("Twap"),y(t)])}return I([R("Spot")])},Ne=e=>{const t=e.provider;if("ReflectorSep40"===t){if(!e.asset)throw new Error("Stellar builder: Reflector oracle source requires `asset`");return I([R("Reflector"),N({asset:$e(e.asset),contract:w(e.contract),read_mode:Be(e.readMode,e.twapRecords)})])}if(t===Ie||"XoxnoPriceFeed"===t){const o=t===Ie?"RedStone":"Xoxno";if("string"!=typeof e.feedId)throw new Error(`Stellar builder: ${o} oracle source requires \`feedId\``);if("number"!=typeof e.maxStaleSeconds)throw new Error(`Stellar builder: ${o} oracle source requires \`maxStaleSeconds\``);return I([R(o),N({contract:w(e.contract),feed_id:k(e.feedId),max_stale_seconds:v(e.maxStaleSeconds)})])}throw new Error(`Stellar builder: unknown oracle provider "${t}"`)},Oe=e=>{const t=Te[e.strategy];if(void 0===t)throw new Error(`Stellar builder: unknown oracle strategy "${e.strategy}"`);return N({anchor:(o=e.anchor,I(null==o?[R("None")]:[R("Some"),Ne(o)])),max_price_stale_seconds:v(e.maxPriceStaleSeconds),max_sanity_price_wad:g(e.maxSanityPriceWad),min_sanity_price_wad:g(e.minSanityPriceWad),primary:Ne(e.primary),strategy:y(t),tolerance_bps:y(e.toleranceBps)});var o};function Pe(e,t){return z(e,"upgrade",[x(t.wasmHash)])}function Ue(e,t){return z(e,"migrate",[y(t.newVersion)])}function qe(e){return z(e,"pause",[])}function Le(e){return z(e,"unpause",[])}function Ve(e,t){return z(e,"grant_role",[w(t.account),R(t.role)])}function ze(e,t){return z(e,"revoke_role",[w(t.account),R(t.role)])}function We(e,t){return z(e,"transfer_ownership",[w(t.newOwner),y(t.liveUntilLedger)])}function De(e){return z(e,"accept_ownership",[])}function Ce(e,t){return z(e,"set_aggregator",[w(t.aggregator)])}function Ge(e,t){return z(e,"set_accumulator",[w(t.accumulator)])}function Xe(e,t){return z(e,"set_liquidity_pool_template",[x(t.wasmHash)])}function Fe(e,t){return z(e,"set_position_limits",[Ee(t)])}function Me(e,t){return z(e,"approve_token",[w(t.token)])}function He(e,t){return z(e,"revoke_token",[w(t.token)])}function je(e,t){return z(e,"set_market_oracle_config",[E(t.hubId,t.asset),Oe(t.config)])}function Qe(e,t){return z(e,"set_oracle_tolerance",[w(t.asset),N({lower_ratio_bps:y(t.lowerRatioBps),upper_ratio_bps:y(t.upperRatioBps)})])}function Ze(e,t){return z(e,"update_indexes",[w(e.caller),I(t.assets.map((e=>E(e.hubId,e.asset))))])}function Je(e,t){return z(e,"renew_account",[w(e.caller),v(t.accountNonce)])}function Ke(e,t){return z(e,"create_liquidity_pool",[y(t.hubId),w(t.asset),Ae(t.params)])}function Ye(e,t){return z(e,"upgrade_liquidity_pool_params",[E(t.hubId,t.asset),xe(t.params)])}function et(e,t){return z(e,"claim_revenue",[w(e.caller),I(t.assets.map((e=>E(e.hubId,e.asset))))])}function tt(e,t){return z(e,"add_rewards",[w(e.caller),B(t.rewards)])}function ot(e,t){return z(e,"update_account_threshold",[w(e.caller),S(t.hasRisks),I(t.accountNonces.map((e=>v(e))))])}const rt="00".repeat(32),at=e=>{if("string"==typeof e)return x(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)},nt=(e,...t)=>I([R(e),...t]),st=e=>N({new_owner:w(e.newOwner),live_until_ledger:y(e.liveUntilLedger)}),it=e=>N({asset:w(e.asset),bonus:y(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:S(e.canBorrow),can_collateral:S(e.canCollateral),frozen:S(e.frozen),hub_id:y(e.hubId),paused:S(e.paused),liquidation_fees:y(e.liquidationFees),ltv:y(e.ltv),oracle_override:I([R("None")]),spoke_id:y(e.spokeId),supply_cap:g(e.supplyCap),threshold:y(e.threshold)}),ut=e=>N({account:w(e.account),role:R(e.role)});function lt(t,a,s){const i=t.governanceAddress??_(t.network),u=new r(i),l=new e(t.caller,t.sourceSequence);return{xdr:new n(l,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(u.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const ct=(e,t,o)=>lt(e,"propose",[w(e.caller),t,at(o)]),pt=(e,t,o)=>lt(e,"execute_self",[T(),t,at(o)]);function dt(e,t,o){return ct(e,nt("SetAggregator",w(t.aggregator)),o)}function mt(e,t,o){return ct(e,nt("SetAccumulator",w(t.accumulator)),o)}function ft(e,t,o){return ct(e,nt("SetLiquidityPoolTemplate",x(t.wasmHash)),o)}function ht(e,t,o){return ct(e,nt("SetPositionLimits",Ee(t)),o)}function _t(e,t){return ct(e,nt("CreateHub"),t)}function bt(e,t){return ct(e,nt("AddSpoke"),t)}function wt(e,t,o){return ct(e,nt("RemoveSpoke",y(t.spokeId)),o)}function gt(e,t,o){return ct(e,nt("AddAssetToSpoke",it(t)),o)}function yt(e,t,o){return ct(e,nt("EditAssetInSpoke",it(t)),o)}function vt(e,t,o){return ct(e,nt("RemoveAssetFromSpoke",N({hub_asset:E((r=t).hubId,r.asset),spoke_id:y(r.spokeId)})),o);var r}function St(e,t,o){return ct(e,nt("SetSpokeLiquidationCurve",N({hf_for_max_bonus_wad:g((r=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:y(r.liquidationBonusFactorBps),spoke_id:y(r.spokeId),target_hf_wad:g(r.targetHfWad)})),o);var r}function kt(e,t,o){return ct(e,nt("SetPositionManager",w(t.manager),S(t.isActive)),o)}function Rt(e,t,o){return ct(e,nt("SetMinBorrowCollateralUsd",g(t.floorWad)),o)}function Tt(e,t,o){return ct(e,nt("ApproveToken",w(t.token)),o)}function It(e,t,o){return ct(e,nt("RevokeToken",w(t.token)),o)}function xt(e,t,o){return ct(e,nt("ApproveBlendPool",w(t.pool)),o)}function At(e,t,o){return ct(e,nt("RevokeBlendPool",w(t.pool)),o)}function Et(e,t,o){return ct(e,nt("CreateLiquidityPool",N({asset:w((r=t).asset),hub_id:y(r.hubId),params:Ae(r.params)})),o);var r}function $t(e,t,o){return ct(e,nt("UpgradeLiquidityPoolParams",N({hub_asset:E((r=t).hubId,r.asset),params:xe(r.params)})),o);var r}function Bt(e,t){return ct(e,nt("DeployPool"),t)}function Nt(e,t,o){return ct(e,nt("UpgradePool",x(t.wasmHash)),o)}function Ot(e,t,o){return ct(e,nt("UpgradeController",x(t.wasmHash)),o)}function Pt(e,t,o){return ct(e,nt("MigrateController",y(t.newVersion)),o)}function Ut(e,t,o){return ct(e,nt("TransferCtrlOwnership",st(t)),o)}function qt(e,t,o){return ct(e,nt("ConfigureMarketOracle",N({cfg:Oe((r=t).config),hub_asset:E(r.hubId,r.asset)})),o);var r}function Lt(e,t,o){return ct(e,nt("EditOracleTolerance",N({asset:w((r=t).asset),tolerance:y(r.tolerance)})),o);var r}function Vt(e,t,o){return ct(e,nt("UpgradeGov",x(t.wasmHash)),o)}function zt(e,t,o){return ct(e,nt("UpdateGovDelay",y(t.newDelay)),o)}function Wt(e,t,o){return ct(e,nt("GrantGovRole",ut(t)),o)}function Dt(e,t,o){return ct(e,nt("RevokeGovRole",ut(t)),o)}function Ct(e,t,o){return ct(e,nt("TransferGovOwnership",st(t)),o)}function Gt(e,t){const o=I(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),r=at(t.predecessor??rt);return lt(e,"execute",[T(),w(t.target),R(t.functionName),o,r,at(t.salt)])}function Xt(e,t,o){return pt(e,nt("UpgradeGov",x(t.wasmHash)),o)}function Ft(e,t,o){return pt(e,nt("UpdateGovDelay",y(t.newDelay)),o)}function Mt(e,t,o){return pt(e,nt("GrantGovRole",ut(t)),o)}function Ht(e,t,o){return pt(e,nt("RevokeGovRole",ut(t)),o)}function jt(e,t,o){return pt(e,nt("TransferGovOwnership",st(t)),o)}const Qt=e=>e.toXDR("base64"),Zt=e=>i.ScVal.fromXDR(e,"base64"),Jt=e=>e.map((e=>String(s(Zt(e))))).join(":"),Kt=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Yt=e=>Number(e),eo=e=>String(e),to=e=>null==e?void 0:Kt(e),oo=e=>null==e?void 0:eo(e),ro=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),ao=["None","Multiply","Long","Short"],no=["Single","PrimaryWithAnchor"],so=["ReflectorSep40","RedStonePriceFeed"],io=["Spot","Twap"],uo=["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"],lo=e=>Array.isArray(e)?e:[],co=(e,t)=>{const o="Borrow"===t;return{action:(r=e[0],uo[Yt(r)]??Kt(r)),positionType:t,hubId:Yt(e[1]),asset:eo(e[2]),scaledAmountRay:Kt(e[3]),indexRay:Kt(e[4]),amount:Kt(e[5]),liquidationThresholdBps:o?void 0:Yt(e[6]),liquidationBonusBps:o?void 0:Yt(e[7]),loanToValueBps:o?void 0:Yt(e[8]),liquidationFeesBps:o?void 0:Yt(e[9])};var r},po=e=>{return{owner:eo(e[0]),spokeId:Yt(e[1]),mode:(t=e[2],ao[Yt(t)]??"None")};var t},mo=(e,t)=>{const o=io[Yt(e[`${t}_read_mode`])]??"Spot",r=e[`${t}_asset`],a=e[`${t}_symbol`],n=null!=r?{kind:"Stellar",value:eo(r)}:null!=a?{kind:"Symbol",value:eo(a)}:void 0;return{provider:so[Yt(e[`${t}_provider`])]??"ReflectorSep40",contractAddress:eo(e[`${t}_contract`]),asset:n,feedId:oo(e[`${t}_feed_id`]),readMode:o,twapRecords:"Twap"===o?Yt(e[`${t}_twap_records`]):void 0,decimals:Yt(e[`${t}_decimals`]),resolutionSeconds:Yt(e[`${t}_resolution_seconds`]),maxStaleSeconds:Yt(e[`${t}_max_stale_seconds`])}},fo=e=>{const t=null!==e.anchor_provider&&void 0!==e.anchor_provider;return{baseTokenId:eo(e.base_token_id),quoteTokenId:eo(e.quote_token_id),tolerance:{upperRatio:Yt(e.upper_ratio_bps??e.tolerance?.upper_ratio_bps),lowerRatio:Yt(e.lower_ratio_bps??e.tolerance?.lower_ratio_bps)},assetDecimals:Yt(e.asset_decimals),maxPriceStaleSeconds:Yt(e.max_price_stale_seconds),strategy:no[Yt(e.strategy)]??"Single",primary:mo(e,"primary"),anchor:t?mo(e,"anchor"):void 0,primaryQuoteToken:oo(e.primary_quote_token),anchorQuoteToken:oo(e.anchor_quote_token),minSanityPriceWad:to(e.min_sanity_price_wad),maxSanityPriceWad:to(e.max_sanity_price_wad)}},ho={"market:create":e=>({topic:"market:create",data:{hubId:Yt(e.hub_id),baseAsset:eo(e.base_asset),maxBorrowRate:Kt(e.max_borrow_rate),baseBorrowRate:Kt(e.base_borrow_rate),slope1:Kt(e.slope1),slope2:Kt(e.slope2),slope3:Kt(e.slope3),midUtilization:Kt(e.mid_utilization),optimalUtilization:Kt(e.optimal_utilization),maxUtilization:Kt(e.max_utilization),reserveFactor:Yt(e.reserve_factor),marketAddress:eo(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:eo(e.asset),maxBorrowRateRay:Kt(e.max_borrow_rate),baseBorrowRateRay:Kt(e.base_borrow_rate),slope1Ray:Kt(e.slope1),slope2Ray:Kt(e.slope2),slope3Ray:Kt(e.slope3),midUtilizationRay:Kt(e.mid_utilization),optimalUtilizationRay:Kt(e.optimal_utilization),maxUtilizationRay:Kt(e.max_utilization),reserveFactorBps:Yt(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:lo(e).map((e=>{return t=lo(e),{hubId:Yt(t[0]),asset:eo(t[1]),timestamp:Yt(t[2]),supplyIndexRay:Kt(t[3]),borrowIndexRay:Kt(t[4]),cash:Kt(t[5]),suppliedRay:Kt(t[6]),borrowedRay:Kt(t[7]),revenueRay:Kt(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:lo(e).map((e=>{const t=e;return{hubId:Yt(t.hub_id),asset:eo(t.asset),params:(o=t.params,{maxBorrowRateRay:Kt(o.max_borrow_rate),baseBorrowRateRay:Kt(o.base_borrow_rate),slope1Ray:Kt(o.slope1),slope2Ray:Kt(o.slope2),slope3Ray:Kt(o.slope3),midUtilizationRay:Kt(o.mid_utilization),optimalUtilizationRay:Kt(o.optimal_utilization),maxUtilizationRay:Kt(o.max_utilization),reserveFactorBps:Yt(o.reserve_factor),isFlashloanable:Boolean(o.is_flashloanable),flashloanFeeBps:Yt(o.flashloan_fee),assetId:eo(o.asset_id),assetDecimals:Yt(o.asset_decimals)})};var o}))}}),"position:batch_update":e=>{const t=lo(e);return{topic:"position:batch_update",data:{accountId:Kt(t[0]),accountAttributes:po(lo(t[1])),updates:[...lo(t[2]).map((e=>co(lo(e),"Deposit"))),...lo(t[3]).map((e=>co(lo(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Yt(e.hub_id),asset:eo(e.asset),receiver:eo(e.receiver),caller:eo(e.caller),amount:Kt(e.amount),fee:Kt(e.fee)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:eo(e.asset),oracle:fo(e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:eo(e.liquidator),accountId:Kt(e.account_id),repaidUsdWad:Kt(e.repaid_usd_wad),bonusBps:Kt(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Kt(e.account_id),totalBorrowUsdWad:Kt(e.total_borrow_usd_wad),totalCollateralUsdWad:Kt(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:eo(e.token),amount:Kt(e.amount),usdValueWad:Kt(e.usd_value_wad),accountId:Kt(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Yt(e.hub_id),asset:eo(e.asset),amount:Kt(e.amount),fee:Kt(e.fee),amountSent:Kt(e.amount_sent)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:ro(e.wasm_hash),approved:Boolean(e.approved)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:eo(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:eo(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:ro(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Yt(e.max_supply_positions),maxBorrowPositions:Yt(e.max_borrow_positions)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:eo(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Yt(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Kt(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Kt(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Yt(t.liquidation_bonus_factor_bps)}}}},_o=Object.freeze(Object.keys(ho));function bo(e,t){const o=Jt(e),r=ho[o];return r?r(s(Zt(t))):null}const wo="XLENDXLM-a7c9f3",go=1e4;function yo(e){const t=BigInt(e).toString(16),o=t.length%2==0?t:`0${t}`;return`${wo}-${o}`}function vo(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function So(e,t=0){return 1e4*e+t}function ko(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"param_upd":return"lendingUpdateAccountParameters";default:return"lendingUpdateAccountPosition"}}const Ro=(e,t,o)=>{const r=new URL(t,e.endsWith("/")?e:`${e}/`);if(o)for(const[e,t]of Object.entries(o))void 0!==t&&r.searchParams.set(e,String(t));return r.toString()},To=e=>e.baseUrl??d[e.network];async function Io(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const o=Ro(To(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),r=await fetch(o,t.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${o} — ${e}`)}return await r.json()}async function xo(e){const t=Ro(To(e),"api/v1/tokens"),o=await fetch(t,e.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${t} — ${e}`)}return await o.json()}const Ao=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,Eo=e=>O(e).toXDR("base64");function $o(t,a){const s=t.routerAddress??h(t.network),i=new r(s),u=new e(t.caller,t.sourceSequence),l=L(Ao(a,t.referralId));return{xdr:new n(u,{fee:t.fee??o,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",w(t.caller),g(t.totalIn),l)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function Bo(e,t){return $o(e,t)}function No(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 Oo(e,t={}){const o=e;return"string"==typeof o.routeXdr&&o.routeXdr.length>0?{routeXdr:o.routeXdr}:No(e,t)}const Po=No,Uo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function qo(e,t){const o=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${o}`)}async function Lo(e,t,o){const r=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(r)).toXDR()}catch(e){if(o?.invokedContractId)throw qo(o.invokedContractId,e);throw e}}async function Vo(e,t,o){return Lo(e,t.xdr,o)}function zo(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 Wo(e,t){return new Uint8Array(0)}const Do=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 Co(t){const o=new e(t.caller,t.sourceSequence),a=new r(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(Do(t.message)),i.ScVal.scvBytes(Do(t.attestation)));return{xdr:new n(o,{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:"InvalidPoolTemplate",message:"The liquidity pool template hash is 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."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetsLimitReached",message:"This spoke has reached its asset limit."},314:{name:"SpokeCapBelowUsage",message:"The new cap is below current usage on this spoke asset."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},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 Xo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const o=Number(t[1]),r=Go[o];return r?{code:o,...r}:null}export{l as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,rt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,u as STELLAR_LENDING_CONTROLLER,_o as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,go as SYNTHETIC_EVENT_ORDER_STRIDE,wo as XOXNO_LENDING_STELLAR_TICKER,Wo as buildSameTokenRepaySwapSteps,De as buildStellarAcceptOwnershipTx,tt as buildStellarAddRewardsTx,Me as buildStellarApproveTokenTx,Bo as buildStellarBatchSwapTx,C as buildStellarBorrowBatchTx,G as buildStellarBorrowTx,Co as buildStellarCctpForwardTx,et as buildStellarClaimRevenueTx,Ke as buildStellarCreateLiquidityPoolTx,$o as buildStellarExecuteStrategyTx,Q as buildStellarFlashLoanTx,Xt as buildStellarGovernanceExecuteGovernanceUpgradeTx,Mt as buildStellarGovernanceExecuteGrantGovernanceRoleTx,Ht as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,jt as buildStellarGovernanceExecuteTransferGovOwnTx,Gt as buildStellarGovernanceExecuteTx,Ft as buildStellarGovernanceExecuteUpdateDelayTx,Ve as buildStellarGrantRoleTx,yo as buildStellarLendingIdentifier,j as buildStellarLiquidateTx,Z as buildStellarMigrateFromBlendTx,Ue as buildStellarMigrateTx,J as buildStellarMultiplyTx,qe as buildStellarPauseTx,gt as buildStellarProposeAddAssetToSpokeTx,bt as buildStellarProposeAddSpokeTx,xt as buildStellarProposeApproveBlendPoolTx,Tt as buildStellarProposeApproveTokenTx,qt as buildStellarProposeConfigureMarketOracleTx,_t as buildStellarProposeCreateHubTx,Et as buildStellarProposeCreateLiquidityPoolTx,Bt as buildStellarProposeDeployPoolTx,yt as buildStellarProposeEditAssetInSpokeTx,Lt as buildStellarProposeEditOracleToleranceTx,Vt as buildStellarProposeGovernanceUpgradeTx,Wt as buildStellarProposeGrantGovernanceRoleTx,Pt as buildStellarProposeMigrateControllerTx,vt as buildStellarProposeRemoveAssetFromSpokeTx,wt as buildStellarProposeRemoveSpokeTx,At as buildStellarProposeRevokeBlendPoolTx,Dt as buildStellarProposeRevokeGovernanceRoleTx,It as buildStellarProposeRevokeTokenTx,mt as buildStellarProposeSetAccumulatorTx,dt as buildStellarProposeSetAggregatorTx,Rt as buildStellarProposeSetMinBorrowCollatTx,ft as buildStellarProposeSetPoolTemplateTx,ht as buildStellarProposeSetPositionLimitsTx,kt as buildStellarProposeSetPositionManagerTx,St as buildStellarProposeSetSpokeLiquidationCurveTx,Ut as buildStellarProposeTransferCtrlOwnershipTx,Ct as buildStellarProposeTransferGovOwnTx,zt as buildStellarProposeUpdateDelayTx,Ot as buildStellarProposeUpgradeControllerTx,$t as buildStellarProposeUpgradePoolParamsTx,Nt as buildStellarProposeUpgradePoolTx,Je as buildStellarRenewAccountTx,M as buildStellarRepayBatchTx,ee as buildStellarRepayDebtWithCollateralTx,H as buildStellarRepayTx,ze as buildStellarRevokeRoleTx,He as buildStellarRevokeTokenTx,Ge as buildStellarSetAccumulatorTx,Ce as buildStellarSetAggregatorTx,Xe as buildStellarSetLiquidityPoolTemplateTx,je as buildStellarSetMarketOracleConfigTx,Qe as buildStellarSetOracleToleranceTx,Fe as buildStellarSetPositionLimitsTx,W as buildStellarSupplyBatchTx,D as buildStellarSupplyTx,Y as buildStellarSwapCollateralTx,K as buildStellarSwapDebtTx,We as buildStellarTransferOwnershipTx,Le as buildStellarUnpauseTx,ot as buildStellarUpdateAccountThresholdTx,Ze as buildStellarUpdateIndexesTx,Pe as buildStellarUpgradeControllerTx,Ye as buildStellarUpgradeLiquidityPoolParamsTx,X as buildStellarWithdrawBatchTx,F as buildStellarWithdrawTx,z as buildTx,bo as decodeStellarLendingEvent,xe as encodeInterestRateModel,Oe as encodeMarketOracleConfigInput,Ae as encodeMarketParamsRaw,Ne as encodeOracleSourceConfigInput,Ee as encodePositionLimits,Eo as encodeStrategyPayloadToRouteXdr,vo as extractEventOrder,we as getStellarAccountPositions,Io as getStellarAggregatorQuote,h as getStellarAggregatorRouter,pe as getStellarAsset,ye as getStellarAssetGraph,me as getStellarAssetMarkets,de as getStellarAssetPage,ne as getStellarAssets,_ as getStellarGovernance,ge as getStellarGovernanceProposals,fe as getStellarHub,ve as getStellarHubGraph,se as getStellarHubs,ae as getStellarLendingContext,f as getStellarLendingController,xo as getStellarQuoteTokens,le as getStellarReserve,ke as getStellarReserveGraph,ce as getStellarReserveHolders,ue as getStellarReserves,he as getStellarSpoke,Se as getStellarSpokeGraph,ie as getStellarSpokes,be as getStellarUserActivity,_e as getStellarUserPositions,Po as mapQuoteResponseToAggregatorSwap,No as mapQuoteResponseToStrategyPayload,Oo as mapQuoteResponseToStrategySwap,Xo as mapSorobanError,ko as mapStellarPositionActivityType,Vo as prepareStellarBuiltTx,Lo as prepareStellarTxXdr,Jt as stellarLendingDispatchKey,Re as stellarLendingRead,So as syntheticEventOrder,qo as tagStellarInvokedContractError,Qt as toBase64Xdr,zo as toStellarPositionMode};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xoxno/sdk-js",
3
- "version": "1.0.186",
3
+ "version": "1.0.187",
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.462"
117
+ "@xoxno/types": "^1.0.463"
118
118
  },
119
119
  "peerDependencies": {
120
120
  "@stellar/stellar-sdk": ">=15.0.0 <17.0.0"