@xoxno/sdk-js 1.0.207 → 1.0.210
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/README.md +6 -0
- package/dist/cjs/sdk/stellar/events/id.d.ts +6 -6
- package/dist/cjs/sdk/swagger.d.ts +14 -1
- package/dist/cjs/utils/__tests__/regex.test.d.ts +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/sdk/stellar/events/id.d.ts +6 -6
- package/dist/sdk/stellar/index.cjs +1 -1
- package/dist/sdk/stellar/index.esm.js +1 -1
- package/dist/sdk/swagger.d.ts +14 -1
- package/dist/utils/__tests__/regex.test.d.ts +2 -0
- 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:()=>_t,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>Xr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>Qr,XOXNO_LENDING_STELLAR_TICKER:()=>jr,buildSameTokenRepaySwapSteps:()=>So,buildStellarAcceptOwnershipTx:()=>Ze,buildStellarAddRewardsTx:()=>bt,buildStellarApproveBlendPoolTx:()=>at,buildStellarApproveTokenTx:()=>st,buildStellarBatchSwapTx:()=>io,buildStellarBorrowBatchTx:()=>W,buildStellarBorrowTx:()=>z,buildStellarCctpForwardTx:()=>wo,buildStellarClaimRevenueTx:()=>St,buildStellarCreateLiquidityPoolTx:()=>ht,buildStellarExecuteCancellerResetTx:()=>Tr,buildStellarExecuteStrategyTx:()=>so,buildStellarFlashLoanTx:()=>J,buildStellarGovernanceAddSpokeImmediateTx:()=>Rr,buildStellarGovernanceCreateHubImmediateTx:()=>kr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>hr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Sr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>br,buildStellarGovernanceExecuteTransferGovOwnTx:()=>wr,buildStellarGovernanceExecuteTx:()=>fr,buildStellarGovernanceExecuteUpdateDelayTx:()=>gr,buildStellarGovernancePauseTx:()=>Er,buildStellarGovernanceRevokeRoleImmediateTx:()=>Ar,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>vr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>xr,buildStellarGrantRoleTx:()=>Qe,buildStellarLendingIdentifier:()=>Jr,buildStellarLiquidateTx:()=>j,buildStellarMigrateFromBlendTx:()=>K,buildStellarMigrateTx:()=>Xe,buildStellarMultiplyTx:()=>Z,buildStellarPauseTx:()=>He,buildStellarProposeAddAssetToSpokeTx:()=>zt,buildStellarProposeAddSpokeTx:()=>Mt,buildStellarProposeApproveBlendPoolTx:()=>Kt,buildStellarProposeApproveTokenTx:()=>Qt,buildStellarProposeCancellerResetTx:()=>yr,buildStellarProposeConfigureAssetOracleTx:()=>sr,buildStellarProposeConfigureMarketOracleTx:()=>ir,buildStellarProposeCreateHubTx:()=>Dt,buildStellarProposeCreateLiquidityPoolTx:()=>Yt,buildStellarProposeDeployPoolTx:()=>tr,buildStellarProposeEditAssetInSpokeTx:()=>Vt,buildStellarProposeEditOracleToleranceTx:()=>lr,buildStellarProposeGovernanceUpgradeTx:()=>ur,buildStellarProposeGrantGovernanceRoleTx:()=>dr,buildStellarProposeMigrateControllerTx:()=>ar,buildStellarProposeRemoveAssetFromSpokeTx:()=>Ft,buildStellarProposeRemoveSpokeTx:()=>Wt,buildStellarProposeRevokeBlendPoolTx:()=>Zt,buildStellarProposeRevokeGovernanceRoleTx:()=>pr,buildStellarProposeRevokeTokenTx:()=>Jt,buildStellarProposeSetAccumulatorTx:()=>Gt,buildStellarProposeSetAggregatorTx:()=>Ut,buildStellarProposeSetMinBorrowCollatTx:()=>jt,buildStellarProposeSetPositionLimitsTx:()=>qt,buildStellarProposeSetPositionManagerTx:()=>Ht,buildStellarProposeSetPriceAggregatorTx:()=>Ct,buildStellarProposeSetSpokeLiquidationCurveTx:()=>Xt,buildStellarProposeSetSwapAggregatorTx:()=>$t,buildStellarProposeTransferCtrlOwnershipTx:()=>nr,buildStellarProposeTransferGovOwnTx:()=>mr,buildStellarProposeUnpauseTx:()=>Pr,buildStellarProposeUpdateDelayTx:()=>cr,buildStellarProposeUpgradeControllerTx:()=>or,buildStellarProposeUpgradePoolParamsTx:()=>er,buildStellarProposeUpgradePoolTx:()=>rr,buildStellarRenewAccountTx:()=>ft,buildStellarRepayBatchTx:()=>X,buildStellarRepayDebtWithCollateralTx:()=>te,buildStellarRepayTx:()=>H,buildStellarRevokeBlendPoolTx:()=>nt,buildStellarRevokeRoleTx:()=>Je,buildStellarRevokeTokenTx:()=>it,buildStellarSetAccumulatorTx:()=>rt,buildStellarSetAggregatorTx:()=>tt,buildStellarSetMarketOracleConfigTx:()=>ut,buildStellarSetOracleSanityBoundsTx:()=>pt,buildStellarSetOracleToleranceTx:()=>ct,buildStellarSetOracleTx:()=>lt,buildStellarSetPositionLimitsTx:()=>ot,buildStellarSetPriceAggregatorTx:()=>et,buildStellarSetSpokeAssetFlagsTx:()=>dt,buildStellarSetSwapAggregatorTx:()=>Ye,buildStellarSupplyBatchTx:()=>D,buildStellarSupplyTx:()=>M,buildStellarSwapCollateralTx:()=>ee,buildStellarSwapDebtTx:()=>Y,buildStellarTransferOwnershipTx:()=>Ke,buildStellarUnpauseTx:()=>je,buildStellarUpdateAccountThresholdTx:()=>wt,buildStellarUpdateIndexesTx:()=>mt,buildStellarUpgradeControllerTx:()=>Fe,buildStellarUpgradeLiquidityPoolParamsTx:()=>gt,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>F,buildTx:()=>q,decodeStellarLendingEvent:()=>Hr,decodeStellarLiquidateReturn:()=>Q,encodeAssetOracle:()=>ze,encodeInterestRateModel:()=>Be,encodeMarketOracleConfigInput:()=>Ve,encodeMarketParamsRaw:()=>Ne,encodePositionLimits:()=>Le,encodePriceKey:()=>$e,encodeStrategyPayloadToRouteXdr:()=>no,extractEventOrder:()=>Kr,getStellarAccountDelegates:()=>Pe,getStellarAccountPositions:()=>_e,getStellarAggregatorQuote:()=>ro,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>me,getStellarAssetGraph:()=>Te,getStellarAssetMarkets:()=>he,getStellarAssetPage:()=>fe,getStellarAssets:()=>ie,getStellarBlendPools:()=>Ie,getStellarContractConfig:()=>Ae,getStellarContractRoles:()=>Ee,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>ye,getStellarHub:()=>ge,getStellarHubGraph:()=>xe,getStellarHubs:()=>le,getStellarLendingContext:()=>ne,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>se,getStellarProtocolConfig:()=>Re,getStellarQuoteTokens:()=>oo,getStellarReserve:()=>de,getStellarReserveGraph:()=>ke,getStellarReserveHolders:()=>pe,getStellarReserves:()=>ce,getStellarSpoke:()=>Se,getStellarSpokeGraph:()=>ve,getStellarSpokes:()=>ue,getStellarUserActivity:()=>we,getStellarUserPositions:()=>be,mapQuoteResponseToAggregatorSwap:()=>co,mapQuoteResponseToStrategyPayload:()=>lo,mapQuoteResponseToStrategySwap:()=>uo,mapSorobanError:()=>yo,mapStellarPositionActivityType:()=>Yr,prepareStellarBuiltTx:()=>ho,prepareStellarTxXdr:()=>fo,stellarLendingDispatchKey:()=>Br,stellarLendingRead:()=>Oe,syntheticEventOrder:()=>Zr,tagStellarInvokedContractError:()=>mo,toBase64Xdr:()=>Ir,toStellarPositionMode:()=>go});const r={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},o={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},a={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},n={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},s={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},i={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function l(e){const t=r[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function u(e){const t=o[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function c(e){const t=a[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const d=require("@stellar/stellar-sdk"),p=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],m={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},f=1e6,h=e=>new d.Address(e).toScVal(),g=e=>new d.ScInt(e).toI128(),S=e=>d.xdr.ScVal.scvU32(e),b=e=>new d.ScInt("string"==typeof e?e:e.toString()).toU64(),w=e=>d.xdr.ScVal.scvBool(e),_=e=>d.xdr.ScVal.scvString(e),y=e=>d.xdr.ScVal.scvSymbol(e),T=()=>d.xdr.ScVal.scvVoid(),x=e=>d.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return d.xdr.ScVal.scvBytes(o)},k=(e,t)=>null==e?T():t(e),R=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([h(t),g(r)]);var t,r}))),A=(e,t)=>O({asset:h(t),hub_id:S(e)}),E=(e,t,r)=>d.xdr.ScVal.scvVec([A(e,t),g(r)]),P=e=>d.xdr.ScVal.scvVec(e.map((e=>E(e.hubId,e.asset,e.amount)))),I=e=>{if("Transfer"===e)return x([y("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return x([y("Credit"),b(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},O=e=>{const t=Object.keys(e).sort().map((t=>new d.xdr.ScMapEntry({key:y(t),val:e[t]})));return d.xdr.ScVal.scvMap(t)};class B{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>f)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(m[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>f)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===f;let i=f;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*f/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const N=e=>{const t=new B(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(m.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return O({amounts:d.xdr.ScVal.scvVec(t.amountList.map((e=>g(e)))),assets:d.xdr.ScVal.scvVec(t.assetList.map((e=>h(e)))),ops:d.xdr.ScVal.scvBytes(t.toBytes(r,o,a))})},L=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return d.xdr.ScVal.scvBytes(t)},$=()=>d.xdr.ScVal.scvBytes(Buffer.alloc(0)),C=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},U=e=>{if("string"==typeof e)return L(C(e));if(e instanceof Uint8Array)return 0===e.length?$():L(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?L(C(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?L(C(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?L(C(e.bytes)):0===e.bytes.length?$():L(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!p.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(N(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},G=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return d.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return d.xdr.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function q(e,t,r){const o=e.controllerAddress??l(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"supply",[h(e.caller),b(r),S(o),P([...t.assets])])}function M(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function W(e,t){return q(e,"borrow",[h(e.caller),b(t.accountNonce),P([...t.borrows]),k(t.to,h)])}function z(e,t){return W(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function V(e,t){return q(e,"withdraw",[h(e.caller),b(t.accountNonce),P([...t.withdrawals]),k(t.to,h)])}function F(e,t){return V(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return q(e,"repay",[h(e.caller),b(t.accountNonce),P([...t.payments])])}function H(e,t){return X(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return q(e,"liquidate",[h(e.caller),b(t.accountNonce),P([...t.debtPayments]),I(t.seizeMode??"Transfer")])}function Q(e){const t=(0,d.scValToNative)(d.xdr.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function J(e,t){return q(e,"flash_loan",[h(e.caller),A(t.hubId,t.asset),g(t.amount),h(t.receiver),G(t.data)])}function K(e,t){return q(e,"migrate_from_blend",[h(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),h(t.blendPool),x(t.collateralTokens.map(h)),x(t.supplyTokens.map(h)),R(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function Z(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"multiply",[h(e.caller),b(r),S(o),A(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),A(t.debt.hubId,t.debt.asset),S(t.mode),U(t.steps),k(t.initialPayment,(e=>E(e.hubId,e.asset,e.amount))),k(t.convertSwap,U)])}function Y(e,t){return q(e,"swap_debt",[h(e.caller),b(t.accountNonce),A(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),A(t.newDebt.hubId,t.newDebt.asset),U(t.steps)])}function ee(e,t){return q(e,"swap_collateral",[h(e.caller),b(t.accountNonce),A(t.current.hubId,t.current.asset),g(t.fromAmount),A(t.newCollateral.hubId,t.newCollateral.asset),U(t.steps)])}function te(e,t){return q(e,"repay_debt_with_collateral",[h(e.caller),b(t.accountNonce),A(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),A(t.debt.hubId,t.debt.asset),U(t.steps),w(t.closePosition)])}const re="/stellar-lending",oe=25,ae=encodeURIComponent,ne=(e,t)=>e.fetchWithTimeout(`${re}/context`,t),se=(e,t)=>e.fetchWithTimeout(`${re}/live-state`,t),ie=(e,t)=>e.fetchWithTimeout(`${re}/assets`,t),le=(e,t)=>e.fetchWithTimeout(`${re}/hubs`,t),ue=(e,t)=>e.fetchWithTimeout(`${re}/spokes`,t),ce=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${re}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},de=(e,t,r,o,a)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}`,a),pe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/holders`,{...n,params:{side:a}}),me=(e,t,r)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}`,r),fe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/page`,{...o,params:{...r}}),he=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/markets`,{...o,params:{side:r}}),ge=(e,t,r)=>e.fetchWithTimeout(`${re}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${re}/spokes/${t}`,r),be=(e,t,r)=>e.fetchWithTimeout(`${re}/users/${ae(t)}/positions`,r),we=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${re}/users/${ae(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},_e=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(t)}/positions`,r),ye=(e,t={},r)=>{const{top:o=oe,continuationToken:a}=t;return e.fetchWithTimeout(`${re}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Te=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/hubs/${t}/graph`,{...o,params:{...r}}),ve=(e,t,r,o)=>e.fetchWithTimeout(`${re}/spokes/${t}/graph`,{...o,params:{...r}}),ke=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/graph`,{...n,params:{...a}}),Re=(e,t)=>e.fetchWithTimeout(`${re}/protocol-config`,t),Ae=(e,t,r)=>e.fetchWithTimeout(`${re}/protocol-config/${ae(t)}`,r),Ee=(e,t,r)=>e.fetchWithTimeout(t?`${re}/roles?contractAddress=${ae(t)}`:`${re}/roles`,r),Pe=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(String(t))}/delegates`,r),Ie=(e,t)=>e.fetchWithTimeout(`${re}/blend-pools`,t),Oe=e=>({context:t=>ne(e,t),liveState:t=>se(e,t),protocolConfig:t=>Re(e,t),contractConfig:(t,r)=>Ae(e,t,r),contractRoles:(t,r)=>Ee(e,t,r),accountDelegates:(t,r)=>Pe(e,t,r),blendPools:t=>Ie(e,t),assets:t=>ie(e,t),hubs:t=>le(e,t),spokes:t=>ue(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?ce(e,t,r):ce(e,{},t);var o},reserve:(t,r,o,a)=>de(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>pe(e,t,r,o,a,n),asset:(t,r)=>me(e,t,r),assetMarkets:(t,r,o)=>he(e,t,r,o),hub:(t,r)=>ge(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>be(e,t,r),userActivity:(t,r,o)=>we(e,t,r,o),accountPositions:(t,r)=>_e(e,t,r),governanceProposals:(t,r)=>ye(e,t,r),assetGraph:(t,r,o)=>Te(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>ve(e,t,r,o),reserveGraph:(t,r,o,a,n)=>ke(e,t,r,o,a,n)}),Be=e=>O({base_borrow_rate:g(e.baseBorrowRateRay),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ne=e=>O({asset_decimals:S(e.assetDecimals),asset_id:h(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:w(e.isFlashloanable),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Le=e=>O({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),$e=e=>{if("Token"in e&&e.Token)return x([y("Token"),h(e.Token)]);if("Ref"in e&&e.Ref)return x([y("Ref"),y(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Ce=e=>{if("Stellar"in e)return x([y("Stellar"),h(e.Stellar)]);if("Symbol"in e)return x([y("Symbol"),y(e.Symbol)]);if("String"in e)return x([y("String"),_(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ue=e=>{if("Spot"===e)return x([y("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([y("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ge=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},qe=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},De=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),O({asset:Ce(t.asset),contract:h(t.contract),read_mode:Ue(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([y("MultiFeed"),O({contract:h(t.contract),feed_id:_(t.feedId),kind:Ge(t.kind),nature:qe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Me=e=>{const t=e;return O({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:De(t.provider)})},We=e=>{if("RequireDisjoint"===e)return x([y("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return x([y("AllowShared"),x(t.map((e=>O({contract:h(e.contract),kind:Ge(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},ze=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return O({asset_decimals:S(Number(t.assetDecimals)),independence:We(t.independence),max_price_stale_seconds:b(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:g(String(t.maxSanityPriceWad)),min_sanity_price_wad:g(String(t.minSanityPriceWad)),sources:x(r.map((e=>(e=>{if("Feed"in e)return x([y("Feed"),Me(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),O({factor:Me(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:$e(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),O({key_a:$e(t.keyA),key_b:$e(t.keyB),kind:x([y(t.kind||"ConstantProduct")]),pool:h(t.pool),reserve_a_decimals:S(t.reserveADecimals),reserve_b_decimals:S(t.reserveBDecimals),share_decimals:S(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:O({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Ve=ze;function Fe(e,t){return q(e,"upgrade",[v(t.wasmHash)])}function Xe(e,t){return q(e,"migrate",[S(t.newVersion)])}function He(e){return q(e,"pause",[])}function je(e){return q(e,"unpause",[])}function Qe(e,t){return q(e,"grant_role",[h(t.account),y(t.role)])}function Je(e,t){return q(e,"revoke_role",[h(t.account),y(t.role)])}function Ke(e,t){return q(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Ze(e){return q(e,"accept_ownership",[])}function Ye(e,t){return q(e,"set_swap_aggregator",[h(t.aggregator)])}function et(e,t){return q(e,"set_price_aggregator",[h(t.aggregator)])}const tt=Ye;function rt(e,t){return q(e,"set_accumulator",[h(t.accumulator)])}function ot(e,t){return q(e,"set_position_limits",[Le(t)])}function at(e,t){return q(e,"approve_blend_pool",[h(t.pool)])}function nt(e,t){return q(e,"revoke_blend_pool",[h(t.pool)])}const st=at,it=nt;function lt(e,t){return q(e,"set_oracle",[$e(t.key),ze(t.oracle)])}const ut=lt;function ct(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return q(e,"set_tolerance",[$e(t.key),O({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function dt(e,t){return q(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function pt(e,t){return q(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function mt(e,t){return q(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function ft(e,t){return q(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function ht(e,t){return q(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Ne(t.params)])}function gt(e,t){return q(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),Be(t.params)])}function St(e,t){return q(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function bt(e,t){return q(e,"add_rewards",[h(e.caller),P(t.rewards)])}function wt(e,t){return q(e,"update_account_threshold",[h(e.caller),w(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const _t="00".repeat(32),yt=e=>{if("string"==typeof e)return v(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return d.xdr.ScVal.scvBytes(t)},Tt=(e,...t)=>x([y(e),...t]),xt=e=>O({asset:h(e.asset),hub_id:S(e.hubId),params:Ne(e.params)}),vt=e=>O({hub_asset:A(e.hubId,e.asset),params:Be(e.params)}),kt=e=>O({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),Rt=e=>O({key:$e(e.key),oracle:ze(e.oracle)}),At=e=>O({asset:h(e.asset),bonus:S(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:w(e.canBorrow),can_collateral:w(e.canCollateral),frozen:w(e.frozen),hub_id:S(e.hubId),paused:w(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),no_seize:w(e.noSeize),spoke_id:S(e.spokeId),supply_cap:g(e.supplyCap),threshold:S(e.threshold)}),Et=e=>O({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),Pt=e=>O({hf_for_max_bonus_wad:g(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:g(e.targetHfWad)}),It=e=>O({key:$e(e.key),tolerance:S(e.tolerance)}),Ot=e=>O({account:h(e.account),role:y(e.role)});function Bt(e,t,r){const o=e.governanceAddress??c(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Nt=(e,t,r)=>Bt(e,"propose",[h(e.caller),t,yt(r)]),Lt=(e,t,r)=>Bt(e,"execute_self",[T(),t,yt(r)]);function $t(e,t,r){return Nt(e,Tt("SetSwapAggregator",h(t.aggregator)),r)}function Ct(e,t,r){return Nt(e,Tt("SetPriceAggregator",h(t.aggregator)),r)}const Ut=$t;function Gt(e,t,r){return Nt(e,Tt("SetAccumulator",h(t.accumulator)),r)}function qt(e,t,r){return Nt(e,Tt("SetPositionLimits",Le(t)),r)}function Dt(e,t){return Nt(e,Tt("CreateHub"),t)}function Mt(e,t){return Nt(e,Tt("AddSpoke"),t)}function Wt(e,t,r){return Nt(e,Tt("RemoveSpoke",S(t.spokeId)),r)}function zt(e,t,r){return Nt(e,Tt("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Nt(e,Tt("EditAssetInSpoke",At(t)),r)}function Ft(e,t,r){return Nt(e,Tt("RemoveAssetFromSpoke",Et(t)),r)}function Xt(e,t,r){return Nt(e,Tt("SetSpokeLiquidationCurve",Pt(t)),r)}function Ht(e,t,r){return Nt(e,Tt("SetPositionManager",h(t.manager),w(t.isActive)),r)}function jt(e,t,r){return Nt(e,Tt("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Qt(e,t,r){return Nt(e,Tt("ApproveToken",h(t.token)),r)}function Jt(e,t,r){return Nt(e,Tt("RevokeToken",h(t.token)),r)}function Kt(e,t,r){return Nt(e,Tt("ApproveBlendPool",h(t.pool)),r)}function Zt(e,t,r){return Nt(e,Tt("RevokeBlendPool",h(t.pool)),r)}function Yt(e,t,r){return Nt(e,Tt("CreateLiquidityPool",xt(t)),r)}function er(e,t,r){return Nt(e,Tt("UpgradeLiquidityPoolParams",vt(t)),r)}function tr(e,t,r){return Nt(e,Tt("DeployPool",v(t.wasmHash)),r)}function rr(e,t,r){return Nt(e,Tt("UpgradePool",v(t.wasmHash)),r)}function or(e,t,r){return Nt(e,Tt("UpgradeController",v(t.wasmHash)),r)}function ar(e,t,r){return Nt(e,Tt("MigrateController",S(t.newVersion)),r)}function nr(e,t,r){return Nt(e,Tt("TransferCtrlOwnership",kt(t)),r)}function sr(e,t,r){return Nt(e,Tt("ConfigureAssetOracle",Rt(t)),r)}const ir=sr;function lr(e,t,r){return Nt(e,Tt("EditOracleTolerance",It(t)),r)}function ur(e,t,r){return Nt(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function cr(e,t,r){return Nt(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function dr(e,t,r){return Nt(e,Tt("GrantGovRole",Ot(t)),r)}function pr(e,t,r){return Nt(e,Tt("RevokeGovRole",Ot(t)),r)}function mr(e,t,r){return Nt(e,Tt("TransferGovOwnership",kt(t)),r)}function fr(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=yt(t.predecessor??_t);return Bt(e,"execute",[T(),h(t.target),y(t.functionName),r,o,yt(t.salt)])}function hr(e,t,r){return Lt(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function gr(e,t,r){return Lt(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function Sr(e,t,r){return Lt(e,Tt("GrantGovRole",Ot(t)),r)}function br(e,t,r){return Lt(e,Tt("RevokeGovRole",Ot(t)),r)}function wr(e,t,r){return Lt(e,Tt("TransferGovOwnership",kt(t)),r)}const _r=e=>x(e.map(h));function yr(e,t,r){return Bt(e,"propose_canceller_reset",[_r(t.newCancellers),yt(r)])}function Tr(e,t,r){return Bt(e,"execute_canceller_reset",[k(t.executor,h),_r(t.newCancellers),yt(r)])}function xr(e,t){return Bt(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function vr(e,t){return Bt(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function kr(e){return Bt(e,"create_hub",[h(e.caller)])}function Rr(e){return Bt(e,"add_spoke",[h(e.caller)])}function Ar(e,t){return Bt(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function Er(e){return Bt(e,"pause",[h(e.caller)])}function Pr(e,t){return Nt(e,Tt("Unpause"),t)}const Ir=e=>e.toXDR("base64"),Or=e=>d.xdr.ScVal.fromXDR(e,"base64"),Br=e=>e.map((e=>String((0,d.scValToNative)(Or(e))))).join(":"),Nr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Lr=e=>Number(e),$r=e=>String(e),Cr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],Gr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],qr=e=>Array.isArray(e)?e:[],Dr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Gr[Lr(o)]??Nr(o)),positionType:t,hubId:Lr(e[1]),asset:$r(e[2]),scaledAmountRay:Nr(e[3]),indexRay:Nr(e[4]),amount:Nr(e[5]),liquidationThresholdBps:r?void 0:Lr(e[6]),liquidationBonusBps:r?void 0:Lr(e[7]),loanToValueBps:r?void 0:Lr(e[8]),liquidationFeesBps:r?void 0:Lr(e[9])};var o},Mr=e=>{return{owner:$r(e[0]),spokeId:Lr(e[1]),mode:(t=e[2],Ur[Lr(t)]??"None")};var t},Wr=e=>Array.isArray(e)?e[1]:void 0,zr=e=>{const t=(r=e,Array.isArray(r)?$r(r[0]):$r(r));var r;if("Token"===t)return{Token:$r(Wr(e))};if("Ref"===t)return{Ref:$r(Wr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:$r(t.Token)};if(void 0!==t.Ref)return{Ref:$r(t.Ref)}}return{Token:$r(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:Lr(e.asset_decimals),maxPriceStaleSeconds:Lr(e.max_price_stale_seconds),sources:qr(e.sources).map((e=>e)),tolerance:{upperRatio:Lr(t.upper_ratio_bps),lowerRatio:Lr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Nr(e.min_sanity_price_wad),maxSanityPriceWad:Nr(e.max_sanity_price_wad)}},Fr={"market:create":e=>({topic:"market:create",data:{hubId:Lr(e.hub_id),baseAsset:$r(e.base_asset),maxBorrowRate:Nr(e.max_borrow_rate),baseBorrowRate:Nr(e.base_borrow_rate),slope1:Nr(e.slope1),slope2:Nr(e.slope2),slope3:Nr(e.slope3),midUtilization:Nr(e.mid_utilization),optimalUtilization:Nr(e.optimal_utilization),maxUtilization:Nr(e.max_utilization),reserveFactor:Lr(e.reserve_factor),marketAddress:$r(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:$r(e.asset),maxBorrowRateRay:Nr(e.max_borrow_rate),baseBorrowRateRay:Nr(e.base_borrow_rate),slope1Ray:Nr(e.slope1),slope2Ray:Nr(e.slope2),slope3Ray:Nr(e.slope3),midUtilizationRay:Nr(e.mid_utilization),optimalUtilizationRay:Nr(e.optimal_utilization),maxUtilizationRay:Nr(e.max_utilization),reserveFactorBps:Lr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:qr(e).map((e=>{return t=qr(e),{hubId:Lr(t[0]),asset:$r(t[1]),timestamp:Lr(t[2]),supplyIndexRay:Nr(t[3]),borrowIndexRay:Nr(t[4]),cash:Nr(t[5]),suppliedRay:Nr(t[6]),borrowedRay:Nr(t[7]),revenueRay:Nr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:qr(e).map((e=>{const t=e;return{hubId:Lr(t.hub_id),asset:$r(t.asset),params:(r=t.params,{maxBorrowRateRay:Nr(r.max_borrow_rate),baseBorrowRateRay:Nr(r.base_borrow_rate),slope1Ray:Nr(r.slope1),slope2Ray:Nr(r.slope2),slope3Ray:Nr(r.slope3),midUtilizationRay:Nr(r.mid_utilization),optimalUtilizationRay:Nr(r.optimal_utilization),maxUtilizationRay:Nr(r.max_utilization),reserveFactorBps:Lr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Lr(r.flashloan_fee),assetId:$r(r.asset_id),assetDecimals:Lr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=qr(e);return{topic:"position:batch_update",data:{accountId:Nr(t[0]),accountAttributes:Mr(qr(t[1])),updates:[...qr(t[2]).map((e=>Dr(qr(e),"Deposit"))),...qr(t[3]).map((e=>Dr(qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Lr(e.hub_id),asset:$r(e.asset),receiver:$r(e.receiver),caller:$r(e.caller),amount:Nr(e.amount),fee:Nr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:zr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:$r(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:$r(e.liquidator),accountId:Nr(e.account_id),repaidUsdWad:Nr(e.repaid_usd_wad),bonusBps:Nr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Nr(e.account_id),totalBorrowUsdWad:Nr(e.total_borrow_usd_wad),totalCollateralUsdWad:Nr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:$r(e.token),amount:Nr(e.amount),usdValueWad:Nr(e.usd_value_wad),accountId:Nr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Lr(e.hub_id),asset:$r(e.asset),amount:Nr(e.amount),fee:Nr(e.fee),amountSent:Nr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:$r(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Cr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:$r(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:$r(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:$r(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:$r(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Cr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Lr(e.max_supply_positions),maxBorrowPositions:Lr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Nr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:$r(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Lr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Nr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Nr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Lr(t.liquidation_bonus_factor_bps)}}}},Xr=Object.freeze(Object.keys(Fr));function Hr(e,t){const r=Br(e),o=Fr[r];return o?o((0,d.scValToNative)(Or(t))):null}const jr="XLENDXLM-a7c9f3",Qr=1e4;function Jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${jr}-${r}`}function Kr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Zr(e,t=0){return e*Qr+t}function Yr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const eo=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},to=e=>e.baseUrl??s[e.network];async function ro(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=eo(to(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function oo(e){const t=eo(to(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ao=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,no=e=>N(e).toXDR("base64");function so(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=U(ao(t,e.referralId));return{xdr:new d.TransactionBuilder(a,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(o.call("execute_strategy",h(e.caller),g(e.totalIn),n)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function io(e,t){return so(e,t)}function lo(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(po),splitPpm:e.splitPpm}))):[{hops:e.hops.map(po),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function uo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:lo(e,t)}const co=lo,po=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function mo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function fo(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw mo(r.invokedContractId,e);throw e}}async function ho(e,t,r){return fo(e,t.xdr,r)}function go(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function So(e,t){return new Uint8Array(0)}const bo=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function wo(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(bo(e.message)),d.xdr.ScVal.scvBytes(bo(e.attestation)));return{xdr:new d.TransactionBuilder(t,{fee:e.fee??"10000000",networkPassphrase:i[e.network]}).addOperation(r).setTimeout(e.timeoutSeconds??120).build().toXDR()}}const _o={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function yo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=_o[r];return o?{code:r,...o}:null}module.exports=t})();
|
|
1
|
+
"undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis),(()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{STELLAR_AGGREGATOR_ROUTER:()=>o,STELLAR_GOVERNANCE:()=>a,STELLAR_GOVERNANCE_ZERO_PREDECESSOR:()=>_t,STELLAR_LENDING_CONTROLLER:()=>r,STELLAR_LENDING_TOPICS:()=>Xr,STELLAR_NETWORK_PASSPHRASE:()=>i,STELLAR_QUOTE_URL:()=>s,STELLAR_SOROBAN_RPC_URL:()=>n,SYNTHETIC_EVENT_ORDER_STRIDE:()=>jr,buildSameTokenRepaySwapSteps:()=>go,buildStellarAcceptOwnershipTx:()=>Ze,buildStellarAddRewardsTx:()=>bt,buildStellarApproveBlendPoolTx:()=>at,buildStellarApproveTokenTx:()=>st,buildStellarBatchSwapTx:()=>so,buildStellarBorrowBatchTx:()=>M,buildStellarBorrowTx:()=>z,buildStellarCctpForwardTx:()=>bo,buildStellarClaimRevenueTx:()=>St,buildStellarCreateLiquidityPoolTx:()=>ht,buildStellarExecuteCancellerResetTx:()=>Tr,buildStellarExecuteStrategyTx:()=>no,buildStellarFlashLoanTx:()=>J,buildStellarGovernanceAddSpokeImmediateTx:()=>Rr,buildStellarGovernanceCreateHubImmediateTx:()=>kr,buildStellarGovernanceExecuteGovernanceUpgradeTx:()=>hr,buildStellarGovernanceExecuteGrantGovernanceRoleTx:()=>Sr,buildStellarGovernanceExecuteRevokeGovernanceRoleTx:()=>br,buildStellarGovernanceExecuteTransferGovOwnTx:()=>wr,buildStellarGovernanceExecuteTx:()=>fr,buildStellarGovernanceExecuteUpdateDelayTx:()=>gr,buildStellarGovernancePauseTx:()=>Pr,buildStellarGovernanceRevokeRoleImmediateTx:()=>Ar,buildStellarGovernanceSetOracleSanityBoundsImmediateTx:()=>vr,buildStellarGovernanceSetSpokeAssetFlagsImmediateTx:()=>xr,buildStellarGrantRoleTx:()=>Qe,buildStellarLendingIdentifier:()=>Qr,buildStellarLiquidateTx:()=>j,buildStellarMigrateFromBlendTx:()=>K,buildStellarMigrateTx:()=>Xe,buildStellarMultiplyTx:()=>Z,buildStellarPauseTx:()=>He,buildStellarProposeAddAssetToSpokeTx:()=>zt,buildStellarProposeAddSpokeTx:()=>Wt,buildStellarProposeApproveBlendPoolTx:()=>Kt,buildStellarProposeApproveTokenTx:()=>Qt,buildStellarProposeCancellerResetTx:()=>yr,buildStellarProposeConfigureAssetOracleTx:()=>sr,buildStellarProposeConfigureMarketOracleTx:()=>ir,buildStellarProposeCreateHubTx:()=>Dt,buildStellarProposeCreateLiquidityPoolTx:()=>Yt,buildStellarProposeDeployPoolTx:()=>tr,buildStellarProposeEditAssetInSpokeTx:()=>Vt,buildStellarProposeEditOracleToleranceTx:()=>lr,buildStellarProposeGovernanceUpgradeTx:()=>ur,buildStellarProposeGrantGovernanceRoleTx:()=>dr,buildStellarProposeMigrateControllerTx:()=>ar,buildStellarProposeRemoveAssetFromSpokeTx:()=>Ft,buildStellarProposeRemoveSpokeTx:()=>Mt,buildStellarProposeRevokeBlendPoolTx:()=>Zt,buildStellarProposeRevokeGovernanceRoleTx:()=>pr,buildStellarProposeRevokeTokenTx:()=>Jt,buildStellarProposeSetAccumulatorTx:()=>Gt,buildStellarProposeSetAggregatorTx:()=>Ut,buildStellarProposeSetMinBorrowCollatTx:()=>jt,buildStellarProposeSetPositionLimitsTx:()=>qt,buildStellarProposeSetPositionManagerTx:()=>Ht,buildStellarProposeSetPriceAggregatorTx:()=>Ct,buildStellarProposeSetSpokeLiquidationCurveTx:()=>Xt,buildStellarProposeSetSwapAggregatorTx:()=>Lt,buildStellarProposeTransferCtrlOwnershipTx:()=>nr,buildStellarProposeTransferGovOwnTx:()=>mr,buildStellarProposeUnpauseTx:()=>Er,buildStellarProposeUpdateDelayTx:()=>cr,buildStellarProposeUpgradeControllerTx:()=>or,buildStellarProposeUpgradePoolParamsTx:()=>er,buildStellarProposeUpgradePoolTx:()=>rr,buildStellarRenewAccountTx:()=>ft,buildStellarRepayBatchTx:()=>X,buildStellarRepayDebtWithCollateralTx:()=>te,buildStellarRepayTx:()=>H,buildStellarRevokeBlendPoolTx:()=>nt,buildStellarRevokeRoleTx:()=>Je,buildStellarRevokeTokenTx:()=>it,buildStellarSetAccumulatorTx:()=>rt,buildStellarSetAggregatorTx:()=>tt,buildStellarSetMarketOracleConfigTx:()=>ut,buildStellarSetOracleSanityBoundsTx:()=>pt,buildStellarSetOracleToleranceTx:()=>ct,buildStellarSetOracleTx:()=>lt,buildStellarSetPositionLimitsTx:()=>ot,buildStellarSetPriceAggregatorTx:()=>et,buildStellarSetSpokeAssetFlagsTx:()=>dt,buildStellarSetSwapAggregatorTx:()=>Ye,buildStellarSupplyBatchTx:()=>D,buildStellarSupplyTx:()=>W,buildStellarSwapCollateralTx:()=>ee,buildStellarSwapDebtTx:()=>Y,buildStellarTransferOwnershipTx:()=>Ke,buildStellarUnpauseTx:()=>je,buildStellarUpdateAccountThresholdTx:()=>wt,buildStellarUpdateIndexesTx:()=>mt,buildStellarUpgradeControllerTx:()=>Fe,buildStellarUpgradeLiquidityPoolParamsTx:()=>gt,buildStellarWithdrawBatchTx:()=>V,buildStellarWithdrawTx:()=>F,buildTx:()=>q,decodeStellarLendingEvent:()=>Hr,decodeStellarLiquidateReturn:()=>Q,encodeAssetOracle:()=>ze,encodeInterestRateModel:()=>Oe,encodeMarketOracleConfigInput:()=>Ve,encodeMarketParamsRaw:()=>Ne,encodePositionLimits:()=>$e,encodePriceKey:()=>Le,encodeStrategyPayloadToRouteXdr:()=>ao,extractEventOrder:()=>Jr,getStellarAccountDelegates:()=>Ee,getStellarAccountPositions:()=>_e,getStellarAggregatorQuote:()=>to,getStellarAggregatorRouter:()=>u,getStellarAsset:()=>me,getStellarAssetGraph:()=>Te,getStellarAssetMarkets:()=>he,getStellarAssetPage:()=>fe,getStellarAssets:()=>ie,getStellarBlendPools:()=>Ie,getStellarContractConfig:()=>Ae,getStellarContractRoles:()=>Pe,getStellarGovernance:()=>c,getStellarGovernanceProposals:()=>ye,getStellarHub:()=>ge,getStellarHubGraph:()=>xe,getStellarHubs:()=>le,getStellarLendingContext:()=>ne,getStellarLendingController:()=>l,getStellarLendingLiveState:()=>se,getStellarProtocolConfig:()=>Re,getStellarQuoteTokens:()=>ro,getStellarReserve:()=>de,getStellarReserveGraph:()=>ke,getStellarReserveHolders:()=>pe,getStellarReserves:()=>ce,getStellarSpoke:()=>Se,getStellarSpokeGraph:()=>ve,getStellarSpokes:()=>ue,getStellarUserActivity:()=>we,getStellarUserPositions:()=>be,mapQuoteResponseToAggregatorSwap:()=>uo,mapQuoteResponseToStrategyPayload:()=>io,mapQuoteResponseToStrategySwap:()=>lo,mapSorobanError:()=>_o,mapStellarPositionActivityType:()=>Zr,prepareStellarBuiltTx:()=>fo,prepareStellarTxXdr:()=>mo,stellarLendingDispatchKey:()=>Or,stellarLendingRead:()=>Be,syntheticEventOrder:()=>Kr,tagStellarInvokedContractError:()=>po,toBase64Xdr:()=>Ir,toStellarPositionMode:()=>ho});const r={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},o={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},a={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},n={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},s={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},i={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function l(e){const t=r[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function u(e){const t=o[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function c(e){const t=a[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const d=require("@stellar/stellar-sdk"),p=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],m={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},f=1e6,h=e=>new d.Address(e).toScVal(),g=e=>new d.ScInt(e).toI128(),S=e=>d.xdr.ScVal.scvU32(e),b=e=>new d.ScInt("string"==typeof e?e:e.toString()).toU64(),w=e=>d.xdr.ScVal.scvBool(e),_=e=>d.xdr.ScVal.scvString(e),y=e=>d.xdr.ScVal.scvSymbol(e),T=()=>d.xdr.ScVal.scvVoid(),x=e=>d.xdr.ScVal.scvVec(e),v=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return d.xdr.ScVal.scvBytes(o)},k=(e,t)=>null==e?T():t(e),R=e=>d.xdr.ScVal.scvVec(e.map((e=>{return t=e.token,r=e.amount,d.xdr.ScVal.scvVec([h(t),g(r)]);var t,r}))),A=(e,t)=>B({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=>{if("Transfer"===e)return x([y("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return x([y("Credit"),b(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},B=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 N=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 B({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))})},$=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)),C=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},U=e=>{if("string"==typeof e)return $(C(e));if(e instanceof Uint8Array)return 0===e.length?L():$(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?$(C(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?$(C(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?$(C(e.bytes)):0===e.bytes.length?L():$(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!p.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==f)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),d.xdr.ScVal.scvBytes(Buffer.from(N(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},G=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return d.xdr.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return d.xdr.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function q(e,t,r){const o=e.controllerAddress??l(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}function D(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"supply",[h(e.caller),b(r),S(o),E([...t.assets])])}function W(e,t){return D(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function M(e,t){return q(e,"borrow",[h(e.caller),b(t.accountNonce),E([...t.borrows]),k(t.to,h)])}function z(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 q(e,"withdraw",[h(e.caller),b(t.accountNonce),E([...t.withdrawals]),k(t.to,h)])}function F(e,t){return V(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function X(e,t){return q(e,"repay",[h(e.caller),b(t.accountNonce),E([...t.payments])])}function H(e,t){return X(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function j(e,t){return q(e,"liquidate",[h(e.caller),b(t.accountNonce),E([...t.debtPayments]),I(t.seizeMode??"Transfer")])}function Q(e){const t=(0,d.scValToNative)(d.xdr.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function J(e,t){return q(e,"flash_loan",[h(e.caller),A(t.hubId,t.asset),g(t.amount),h(t.receiver),G(t.data)])}function K(e,t){return q(e,"migrate_from_blend",[h(e.caller),b(t.accountId),S(t.spokeId),S(t.hubId),h(t.blendPool),x(t.collateralTokens.map(h)),x(t.supplyTokens.map(h)),R(t.debtCaps.map((e=>({token:e.token,amount:e.cap}))))])}function Z(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return q(e,"multiply",[h(e.caller),b(r),S(o),A(t.collateral.hubId,t.collateral.asset),g(t.debtToFlashLoan),A(t.debt.hubId,t.debt.asset),S(t.mode),U(t.steps),k(t.initialPayment,(e=>P(e.hubId,e.asset,e.amount))),k(t.convertSwap,U)])}function Y(e,t){return q(e,"swap_debt",[h(e.caller),b(t.accountNonce),A(t.existingDebt.hubId,t.existingDebt.asset),g(t.newDebtAmount),A(t.newDebt.hubId,t.newDebt.asset),U(t.steps)])}function ee(e,t){return q(e,"swap_collateral",[h(e.caller),b(t.accountNonce),A(t.current.hubId,t.current.asset),g(t.fromAmount),A(t.newCollateral.hubId,t.newCollateral.asset),U(t.steps)])}function te(e,t){return q(e,"repay_debt_with_collateral",[h(e.caller),b(t.accountNonce),A(t.collateral.hubId,t.collateral.asset),g(t.collateralAmount),A(t.debt.hubId,t.debt.asset),U(t.steps),w(t.closePosition)])}const re="/stellar-lending",oe=25,ae=encodeURIComponent,ne=(e,t)=>e.fetchWithTimeout(`${re}/context`,t),se=(e,t)=>e.fetchWithTimeout(`${re}/live-state`,t),ie=(e,t)=>e.fetchWithTimeout(`${re}/assets`,t),le=(e,t)=>e.fetchWithTimeout(`${re}/hubs`,t),ue=(e,t)=>e.fetchWithTimeout(`${re}/spokes`,t),ce=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${re}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},de=(e,t,r,o,a)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}`,a),pe=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/holders`,{...n,params:{side:a}}),me=(e,t,r)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}`,r),fe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/page`,{...o,params:{...r}}),he=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/markets`,{...o,params:{side:r}}),ge=(e,t,r)=>e.fetchWithTimeout(`${re}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${re}/spokes/${t}`,r),be=(e,t,r)=>e.fetchWithTimeout(`${re}/users/${ae(t)}/positions`,r),we=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${re}/users/${ae(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},_e=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(t)}/positions`,r),ye=(e,t={},r)=>{const{top:o=oe,continuationToken:a}=t;return e.fetchWithTimeout(`${re}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Te=(e,t,r,o)=>e.fetchWithTimeout(`${re}/assets/${ae(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${re}/hubs/${t}/graph`,{...o,params:{...r}}),ve=(e,t,r,o)=>e.fetchWithTimeout(`${re}/spokes/${t}/graph`,{...o,params:{...r}}),ke=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${re}/reserves/${t}/${r}/${ae(o)}/graph`,{...n,params:{...a}}),Re=(e,t)=>e.fetchWithTimeout(`${re}/protocol-config`,t),Ae=(e,t,r)=>e.fetchWithTimeout(`${re}/protocol-config/${ae(t)}`,r),Pe=(e,t,r)=>e.fetchWithTimeout(t?`${re}/roles?contractAddress=${ae(t)}`:`${re}/roles`,r),Ee=(e,t,r)=>e.fetchWithTimeout(`${re}/accounts/${ae(String(t))}/delegates`,r),Ie=(e,t)=>e.fetchWithTimeout(`${re}/blend-pools`,t),Be=e=>({context:t=>ne(e,t),liveState:t=>se(e,t),protocolConfig:t=>Re(e,t),contractConfig:(t,r)=>Ae(e,t,r),contractRoles:(t,r)=>Pe(e,t,r),accountDelegates:(t,r)=>Ee(e,t,r),blendPools:t=>Ie(e,t),assets:t=>ie(e,t),hubs:t=>le(e,t),spokes:t=>ue(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?ce(e,t,r):ce(e,{},t);var o},reserve:(t,r,o,a)=>de(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>pe(e,t,r,o,a,n),asset:(t,r)=>me(e,t,r),assetMarkets:(t,r,o)=>he(e,t,r,o),hub:(t,r)=>ge(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>be(e,t,r),userActivity:(t,r,o)=>we(e,t,r,o),accountPositions:(t,r)=>_e(e,t,r),governanceProposals:(t,r)=>ye(e,t,r),assetGraph:(t,r,o)=>Te(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>ve(e,t,r,o),reserveGraph:(t,r,o,a,n)=>ke(e,t,r,o,a,n)}),Oe=e=>B({base_borrow_rate:g(e.baseBorrowRateRay),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),Ne=e=>B({asset_decimals:S(e.assetDecimals),asset_id:h(e.assetId),base_borrow_rate:g(e.baseBorrowRateRay),flashloan_fee:S(e.flashloanFeeBps),is_flashloanable:w(e.isFlashloanable),max_borrow_rate:g(e.maxBorrowRateRay),max_utilization:g(e.maxUtilizationRay),mid_utilization:g(e.midUtilizationRay),optimal_utilization:g(e.optimalUtilizationRay),reserve_factor:S(e.reserveFactorBps),slope1:g(e.slope1Ray),slope2:g(e.slope2Ray),slope3:g(e.slope3Ray)}),$e=e=>B({max_borrow_positions:S(e.maxBorrowPositions),max_supply_positions:S(e.maxSupplyPositions)}),Le=e=>{if("Token"in e&&e.Token)return x([y("Token"),h(e.Token)]);if("Ref"in e&&e.Ref)return x([y("Ref"),y(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Ce=e=>{if("Stellar"in e)return x([y("Stellar"),h(e.Stellar)]);if("Symbol"in e)return x([y("Symbol"),y(e.Symbol)]);if("String"in e)return x([y("String"),_(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ue=e=>{if("Spot"===e)return x([y("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return x([y("Twap"),S(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ge=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},qe=e=>{if("Market"===e||"Fundamental"===e)return x([y(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},De=e=>{if("Reflector"in e){const t=e.Reflector;return x([y("Reflector"),B({asset:Ce(t.asset),contract:h(t.contract),read_mode:Ue(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return x([y("MultiFeed"),B({contract:h(t.contract),feed_id:_(t.feedId),kind:Ge(t.kind),nature:qe(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},We=e=>{const t=e;return B({decimals:S(t.decimals),max_stale_seconds:b(t.maxStaleSeconds),provider:De(t.provider)})},Me=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=>B({contract:h(e.contract),kind:Ge(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},ze=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return B({asset_decimals:S(Number(t.assetDecimals)),independence:Me(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"),We(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return x([y("Scaled"),B({factor:We(t.factor),max_factor_wad:g(t.maxFactorWad),min_factor_wad:g(t.minFactorWad),quote:Le(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return x([y("LpShare"),B({key_a:Le(t.keyA),key_b:Le(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:B({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})})},Ve=ze;function Fe(e,t){return q(e,"upgrade",[v(t.wasmHash)])}function Xe(e,t){return q(e,"migrate",[S(t.newVersion)])}function He(e){return q(e,"pause",[])}function je(e){return q(e,"unpause",[])}function Qe(e,t){return q(e,"grant_role",[h(t.account),y(t.role)])}function Je(e,t){return q(e,"revoke_role",[h(t.account),y(t.role)])}function Ke(e,t){return q(e,"transfer_ownership",[h(t.newOwner),S(t.liveUntilLedger)])}function Ze(e){return q(e,"accept_ownership",[])}function Ye(e,t){return q(e,"set_swap_aggregator",[h(t.aggregator)])}function et(e,t){return q(e,"set_price_aggregator",[h(t.aggregator)])}const tt=Ye;function rt(e,t){return q(e,"set_accumulator",[h(t.accumulator)])}function ot(e,t){return q(e,"set_position_limits",[$e(t)])}function at(e,t){return q(e,"approve_blend_pool",[h(t.pool)])}function nt(e,t){return q(e,"revoke_blend_pool",[h(t.pool)])}const st=at,it=nt;function lt(e,t){return q(e,"set_oracle",[Le(t.key),ze(t.oracle)])}const ut=lt;function ct(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return q(e,"set_tolerance",[Le(t.key),B({lower_ratio_bps:S(a),upper_ratio_bps:S(o)})])}function dt(e,t){return q(e,"set_spoke_asset_flags",[S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function pt(e,t){return q(e,"set_oracle_sanity_bounds",[h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function mt(e,t){return q(e,"update_indexes",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function ft(e,t){return q(e,"renew_account",[h(e.caller),b(t.accountNonce)])}function ht(e,t){return q(e,"create_liquidity_pool",[S(t.hubId),h(t.asset),Ne(t.params)])}function gt(e,t){return q(e,"upgrade_liquidity_pool_params",[A(t.hubId,t.asset),Oe(t.params)])}function St(e,t){return q(e,"claim_revenue",[h(e.caller),x(t.assets.map((e=>A(e.hubId,e.asset))))])}function bt(e,t){return q(e,"add_rewards",[h(e.caller),E(t.rewards)])}function wt(e,t){return q(e,"update_account_threshold",[h(e.caller),w(t.hasRisks),x(t.accountNonces.map((e=>b(e))))])}const _t="00".repeat(32),yt=e=>{if("string"==typeof e)return v(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return d.xdr.ScVal.scvBytes(t)},Tt=(e,...t)=>x([y(e),...t]),xt=e=>B({asset:h(e.asset),hub_id:S(e.hubId),params:Ne(e.params)}),vt=e=>B({hub_asset:A(e.hubId,e.asset),params:Oe(e.params)}),kt=e=>B({new_owner:h(e.newOwner),live_until_ledger:S(e.liveUntilLedger)}),Rt=e=>B({key:Le(e.key),oracle:ze(e.oracle)}),At=e=>B({asset:h(e.asset),bonus:S(e.bonus),borrow_cap:g(e.borrowCap),can_borrow:w(e.canBorrow),can_collateral:w(e.canCollateral),frozen:w(e.frozen),hub_id:S(e.hubId),paused:w(e.paused),liquidation_fees:S(e.liquidationFees),ltv:S(e.ltv),no_seize:w(e.noSeize),spoke_id:S(e.spokeId),supply_cap:g(e.supplyCap),threshold:S(e.threshold)}),Pt=e=>B({hub_asset:A(e.hubId,e.asset),spoke_id:S(e.spokeId)}),Et=e=>B({hf_for_max_bonus_wad:g(e.hfForMaxBonusWad),liquidation_bonus_factor_bps:S(e.liquidationBonusFactorBps),spoke_id:S(e.spokeId),target_hf_wad:g(e.targetHfWad)}),It=e=>B({key:Le(e.key),tolerance:S(e.tolerance)}),Bt=e=>B({account:h(e.account),role:y(e.role)});function Ot(e,t,r){const o=e.governanceAddress??c(e.network),a=new d.Contract(o),n=new d.Account(e.caller,e.sourceSequence);return{xdr:new d.TransactionBuilder(n,{fee:e.fee??d.BASE_FEE,networkPassphrase:i[e.network]}).addOperation(a.call(t,...r)).setTimeout(e.timeoutSeconds??300).build().toXDR()}}const Nt=(e,t,r)=>Ot(e,"propose",[h(e.caller),t,yt(r)]),$t=(e,t,r)=>Ot(e,"execute_self",[T(),t,yt(r)]);function Lt(e,t,r){return Nt(e,Tt("SetSwapAggregator",h(t.aggregator)),r)}function Ct(e,t,r){return Nt(e,Tt("SetPriceAggregator",h(t.aggregator)),r)}const Ut=Lt;function Gt(e,t,r){return Nt(e,Tt("SetAccumulator",h(t.accumulator)),r)}function qt(e,t,r){return Nt(e,Tt("SetPositionLimits",$e(t)),r)}function Dt(e,t){return Nt(e,Tt("CreateHub"),t)}function Wt(e,t){return Nt(e,Tt("AddSpoke"),t)}function Mt(e,t,r){return Nt(e,Tt("RemoveSpoke",S(t.spokeId)),r)}function zt(e,t,r){return Nt(e,Tt("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Nt(e,Tt("EditAssetInSpoke",At(t)),r)}function Ft(e,t,r){return Nt(e,Tt("RemoveAssetFromSpoke",Pt(t)),r)}function Xt(e,t,r){return Nt(e,Tt("SetSpokeLiquidationCurve",Et(t)),r)}function Ht(e,t,r){return Nt(e,Tt("SetPositionManager",h(t.manager),w(t.isActive)),r)}function jt(e,t,r){return Nt(e,Tt("SetMinBorrowCollateralUsd",g(t.floorWad)),r)}function Qt(e,t,r){return Nt(e,Tt("ApproveToken",h(t.token)),r)}function Jt(e,t,r){return Nt(e,Tt("RevokeToken",h(t.token)),r)}function Kt(e,t,r){return Nt(e,Tt("ApproveBlendPool",h(t.pool)),r)}function Zt(e,t,r){return Nt(e,Tt("RevokeBlendPool",h(t.pool)),r)}function Yt(e,t,r){return Nt(e,Tt("CreateLiquidityPool",xt(t)),r)}function er(e,t,r){return Nt(e,Tt("UpgradeLiquidityPoolParams",vt(t)),r)}function tr(e,t,r){return Nt(e,Tt("DeployPool",v(t.wasmHash)),r)}function rr(e,t,r){return Nt(e,Tt("UpgradePool",v(t.wasmHash)),r)}function or(e,t,r){return Nt(e,Tt("UpgradeController",v(t.wasmHash)),r)}function ar(e,t,r){return Nt(e,Tt("MigrateController",S(t.newVersion)),r)}function nr(e,t,r){return Nt(e,Tt("TransferCtrlOwnership",kt(t)),r)}function sr(e,t,r){return Nt(e,Tt("ConfigureAssetOracle",Rt(t)),r)}const ir=sr;function lr(e,t,r){return Nt(e,Tt("EditOracleTolerance",It(t)),r)}function ur(e,t,r){return Nt(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function cr(e,t,r){return Nt(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function dr(e,t,r){return Nt(e,Tt("GrantGovRole",Bt(t)),r)}function pr(e,t,r){return Nt(e,Tt("RevokeGovRole",Bt(t)),r)}function mr(e,t,r){return Nt(e,Tt("TransferGovOwnership",kt(t)),r)}function fr(e,t){const r=x(t.argsXdr.map((e=>d.xdr.ScVal.fromXDR(e,"base64")))),o=yt(t.predecessor??_t);return Ot(e,"execute",[T(),h(t.target),y(t.functionName),r,o,yt(t.salt)])}function hr(e,t,r){return $t(e,Tt("UpgradeGov",v(t.wasmHash)),r)}function gr(e,t,r){return $t(e,Tt("UpdateGovDelay",S(t.newDelay)),r)}function Sr(e,t,r){return $t(e,Tt("GrantGovRole",Bt(t)),r)}function br(e,t,r){return $t(e,Tt("RevokeGovRole",Bt(t)),r)}function wr(e,t,r){return $t(e,Tt("TransferGovOwnership",kt(t)),r)}const _r=e=>x(e.map(h));function yr(e,t,r){return Ot(e,"propose_canceller_reset",[_r(t.newCancellers),yt(r)])}function Tr(e,t,r){return Ot(e,"execute_canceller_reset",[k(t.executor,h),_r(t.newCancellers),yt(r)])}function xr(e,t){return Ot(e,"set_spoke_asset_flags",[h(e.caller),S(t.spokeId),A(t.hubId,t.asset),w(t.paused),w(t.frozen),w(t.noSeize)])}function vr(e,t){return Ot(e,"set_oracle_sanity_bounds",[h(e.caller),h(t.asset),g(t.minPriceWad),g(t.maxPriceWad)])}function kr(e){return Ot(e,"create_hub",[h(e.caller)])}function Rr(e){return Ot(e,"add_spoke",[h(e.caller)])}function Ar(e,t){return Ot(e,"revoke_role_immediate",[h(t.account),y(t.role)])}function Pr(e){return Ot(e,"pause",[h(e.caller)])}function Er(e,t){return Nt(e,Tt("Unpause"),t)}const Ir=e=>e.toXDR("base64"),Br=e=>d.xdr.ScVal.fromXDR(e,"base64"),Or=e=>e.map((e=>String((0,d.scValToNative)(Br(e))))).join(":"),Nr=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),$r=e=>Number(e),Lr=e=>String(e),Cr=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],Gr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],qr=e=>Array.isArray(e)?e:[],Dr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Gr[$r(o)]??Nr(o)),positionType:t,hubId:$r(e[1]),asset:Lr(e[2]),scaledAmountRay:Nr(e[3]),indexRay:Nr(e[4]),amount:Nr(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:Lr(e[0]),spokeId:$r(e[1]),mode:(t=e[2],Ur[$r(t)]??"None")};var t},Mr=e=>Array.isArray(e)?e[1]:void 0,zr=e=>{const t=(r=e,Array.isArray(r)?Lr(r[0]):Lr(r));var r;if("Token"===t)return{Token:Lr(Mr(e))};if("Ref"===t)return{Ref:Lr(Mr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Lr(t.Token)};if(void 0!==t.Ref)return{Ref:Lr(t.Ref)}}return{Token:Lr(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:$r(e.asset_decimals),maxPriceStaleSeconds:$r(e.max_price_stale_seconds),sources:qr(e.sources).map((e=>e)),tolerance:{upperRatio:$r(t.upper_ratio_bps),lowerRatio:$r(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Nr(e.min_sanity_price_wad),maxSanityPriceWad:Nr(e.max_sanity_price_wad)}},Fr={"market:create":e=>({topic:"market:create",data:{hubId:$r(e.hub_id),baseAsset:Lr(e.base_asset),maxBorrowRate:Nr(e.max_borrow_rate),baseBorrowRate:Nr(e.base_borrow_rate),slope1:Nr(e.slope1),slope2:Nr(e.slope2),slope3:Nr(e.slope3),midUtilization:Nr(e.mid_utilization),optimalUtilization:Nr(e.optimal_utilization),maxUtilization:Nr(e.max_utilization),reserveFactor:$r(e.reserve_factor),marketAddress:Lr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Lr(e.asset),maxBorrowRateRay:Nr(e.max_borrow_rate),baseBorrowRateRay:Nr(e.base_borrow_rate),slope1Ray:Nr(e.slope1),slope2Ray:Nr(e.slope2),slope3Ray:Nr(e.slope3),midUtilizationRay:Nr(e.mid_utilization),optimalUtilizationRay:Nr(e.optimal_utilization),maxUtilizationRay:Nr(e.max_utilization),reserveFactorBps:$r(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:qr(e).map((e=>{return t=qr(e),{hubId:$r(t[0]),asset:Lr(t[1]),timestamp:$r(t[2]),supplyIndexRay:Nr(t[3]),borrowIndexRay:Nr(t[4]),cash:Nr(t[5]),suppliedRay:Nr(t[6]),borrowedRay:Nr(t[7]),revenueRay:Nr(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:qr(e).map((e=>{const t=e;return{hubId:$r(t.hub_id),asset:Lr(t.asset),params:(r=t.params,{maxBorrowRateRay:Nr(r.max_borrow_rate),baseBorrowRateRay:Nr(r.base_borrow_rate),slope1Ray:Nr(r.slope1),slope2Ray:Nr(r.slope2),slope3Ray:Nr(r.slope3),midUtilizationRay:Nr(r.mid_utilization),optimalUtilizationRay:Nr(r.optimal_utilization),maxUtilizationRay:Nr(r.max_utilization),reserveFactorBps:$r(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:$r(r.flashloan_fee),assetId:Lr(r.asset_id),assetDecimals:$r(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=qr(e);return{topic:"position:batch_update",data:{accountId:Nr(t[0]),accountAttributes:Wr(qr(t[1])),updates:[...qr(t[2]).map((e=>Dr(qr(e),"Deposit"))),...qr(t[3]).map((e=>Dr(qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:$r(e.hub_id),asset:Lr(e.asset),receiver:Lr(e.receiver),caller:Lr(e.caller),amount:Nr(e.amount),fee:Nr(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:zr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Lr(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Lr(e.liquidator),accountId:Nr(e.account_id),repaidUsdWad:Nr(e.repaid_usd_wad),bonusBps:Nr(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Nr(e.account_id),totalBorrowUsdWad:Nr(e.total_borrow_usd_wad),totalCollateralUsdWad:Nr(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Lr(e.token),amount:Nr(e.amount),usdValueWad:Nr(e.usd_value_wad),accountId:Nr(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:$r(e.hub_id),asset:Lr(e.asset),amount:Nr(e.amount),fee:Nr(e.fee),amountSent:Nr(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Lr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Cr(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Lr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Lr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Lr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Lr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Cr(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:$r(e.max_supply_positions),maxBorrowPositions:$r(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Nr(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Lr(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:Nr(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Nr(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:$r(t.liquidation_bonus_factor_bps)}}}},Xr=Object.freeze(Object.keys(Fr));function Hr(e,t){const r=Or(e),o=Fr[r];return o?o((0,d.scValToNative)(Br(t))):null}const jr=1e4;function Qr(e,t){return`${e}-${BigInt(t).toString(10)}`}function Jr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Kr(e,t=0){return e*jr+t}function Zr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const Yr=(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()},eo=e=>e.baseUrl??s[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 r=Yr(eo(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 ro(e){const t=Yr(eo(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 oo=(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=>N(e).toXDR("base64");function no(e,t){const r=e.routerAddress??u(e.network),o=new d.Contract(r),a=new d.Account(e.caller,e.sourceSequence),n=U(oo(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 so(e,t){return no(e,t)}function io(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(co),splitPpm:e.splitPpm}))):[{hops:e.hops.map(co),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function lo(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:io(e,t)}const uo=io,co=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function po(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function mo(e,t,r){const o=d.TransactionBuilder.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw po(r.invokedContractId,e);throw e}}async function fo(e,t,r){return mo(e,t.xdr,r)}function ho(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 go(e,t){return new Uint8Array(0)}const So=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 bo(e){const t=new d.Account(e.caller,e.sourceSequence),r=new d.Contract(e.forwarderAddress).call("mint_and_forward",d.xdr.ScVal.scvBytes(So(e.message)),d.xdr.ScVal.scvBytes(So(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 wo={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function _o(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=wo[r];return o?{code:r,...o}:null}module.exports=t})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as r,Contract as o,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const l={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},u={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},c={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},p={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},d={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},m={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function f(e){const t=l[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function h(e){const t=u[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function g(e){const t=c[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const w=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],_={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},b=1e6,y=e=>new t(e).toScVal(),S=e=>new a(e).toI128(),v=e=>i.ScVal.scvU32(e),k=e=>new a("string"==typeof e?e:e.toString()).toU64(),R=e=>i.ScVal.scvBool(e),T=e=>i.ScVal.scvString(e),I=e=>i.ScVal.scvSymbol(e),x=()=>i.ScVal.scvVoid(),A=e=>i.ScVal.scvVec(e),E=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.ScVal.scvBytes(o)},$=(e,t)=>null==e?x():t(e),B=(e,t)=>U({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([B(e,t),S(r)]),P=e=>i.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),O=e=>{if("Transfer"===e)return A([I("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return A([I("Credit"),k(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},U=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:I(t),val:e[t]})));return i.ScVal.scvMap(t)};class L{assets=[];amounts=[];ops=[];weights=[];constructor(e){this.amounts.push(e)}asset(e){const t=this.assets.indexOf(e);if(-1!==t)return t;if(this.assets.length>=256)throw new Error("Stellar builder: strategy references more than 256 distinct addresses");return this.assets.push(e),this.assets.length-1}amount(e){if(this.amounts.length>=126)throw new Error("Stellar builder: strategy references too many distinct amounts");return this.amounts.push(e),this.amounts.length-1}weight(e){if(this.weights.length>=32)throw new Error("Stellar builder: strategy uses more than 32 split weights");if(!Number.isInteger(e)||e<=0||e>b)throw new Error(`Stellar builder: split weight ${e} outside 1..=1000000`);return this.weights.push(e),this.weights.length-1}emit(e,t,r,o,a){this.ops.push([e,t,r,o,a])}emitPath(e,t){e.hops.forEach(((r,o)=>{if(r.tokenIn===r.tokenOut)throw new Error("Stellar builder: hop swaps a token for itself");const a=e.hops[o-1];if(a&&r.tokenIn!==a.tokenOut)throw new Error("Stellar builder: hop does not chain onto its predecessor's output");this.emit(_[r.venue],0===o?t:1,this.asset(r.pool),this.asset(r.tokenIn),this.asset(r.tokenOut))}))}lowerPaths(e){const t=e.filter((e=>e.hops.length>0)),r=Array.from({length:t.length},(()=>!1));for(let e=0;e<t.length;e+=1){if(r[e])continue;const o=t[e].hops[0]?.tokenIn,a=[];for(let r=e;r<t.length;r+=1)t[r].hops[0]?.tokenIn===o&&a.push(r);const n=a.reduce(((e,r)=>e+t[r].splitPpm),0);if(n>b)throw new Error(`Stellar builder: split weights for one token sum to ${n}, above 1000000`);const s=n===b;let i=b;a.forEach(((e,o)=>{r[e]=!0;const n=t[e];let l;if(o+1===a.length&&s)l=0;else{if(0===i)throw new Error("Stellar builder: split weights exhaust the group before its last path");const e=Math.floor(n.splitPpm*b/i);i-=Math.min(n.splitPpm,i),l=128+this.weight(e)}this.emitPath(n,l)}))}}toBytes(e,t,r){if(0===this.ops.length)throw new Error("Stellar builder: strategy lowered to zero instructions");if(this.ops.length>48)throw new Error(`Stellar builder: strategy has ${this.ops.length} instructions, the router accepts 48`);const o=[1,e,t,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,this.ops.length,this.weights.length];for(const e of this.ops)o.push(...e);for(const e of this.weights)o.push(e>>>16&255,e>>>8&255,255&e);return Buffer.from(o)}get assetList(){return this.assets}get amountList(){return this.amounts}}const q=e=>{const t=new L(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(_.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return U({amounts:i.ScVal.scvVec(t.amountList.map((e=>S(e)))),assets:i.ScVal.scvVec(t.assetList.map((e=>y(e)))),ops:i.ScVal.scvBytes(t.toBytes(r,o,a))})},z=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},W=()=>i.ScVal.scvBytes(Buffer.alloc(0)),D=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},C=e=>{if("string"==typeof e)return z(D(e));if(e instanceof Uint8Array)return 0===e.length?W():z(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?z(D(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?z(D(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?z(D(e.bytes)):0===e.bytes.length?W():z(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!w.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),i.ScVal.scvBytes(Buffer.from(q(t).toXDR("base64"),"base64")));var t,r;throw new Error("Stellar builder: `steps` must be opaque strategy bytes (`routeXdr`, base64/hex string, or Uint8Array)")},V=e=>{if("string"==typeof e)return(e=>{const t=e.startsWith("0x")?e.slice(2):e,r=Buffer.from(t,"hex");return i.ScVal.scvBytes(r)})(e);if(e instanceof Uint8Array)return i.ScVal.scvBytes(Buffer.from(e));throw new Error("Stellar builder: `data` must be a hex string or Uint8Array (Soroban Bytes payload)")};function M(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function F(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"supply",[y(e.caller),k(r),v(o),P([...t.assets])])}function G(e,t){return F(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function X(e,t){return M(e,"borrow",[y(e.caller),k(t.accountNonce),P([...t.borrows]),$(t.to,y)])}function H(e,t){return X(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function j(e,t){return M(e,"withdraw",[y(e.caller),k(t.accountNonce),P([...t.withdrawals]),$(t.to,y)])}function J(e,t){return j(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function Q(e,t){return M(e,"repay",[y(e.caller),k(t.accountNonce),P([...t.payments])])}function K(e,t){return Q(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function Z(e,t){return M(e,"liquidate",[y(e.caller),k(t.accountNonce),P([...t.debtPayments]),O(t.seizeMode??"Transfer")])}function Y(e){const t=s(i.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function ee(e,t){return M(e,"flash_loan",[y(e.caller),B(t.hubId,t.asset),S(t.amount),y(t.receiver),V(t.data)])}function te(e,t){return M(e,"migrate_from_blend",[y(e.caller),k(t.accountId),v(t.spokeId),v(t.hubId),y(t.blendPool),A(t.collateralTokens.map(y)),A(t.supplyTokens.map(y)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,i.ScVal.scvVec([y(t),S(r)]);var t,r}))))]);var r}function re(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"multiply",[y(e.caller),k(r),v(o),B(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),B(t.debt.hubId,t.debt.asset),v(t.mode),C(t.steps),$(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),$(t.convertSwap,C)])}function oe(e,t){return M(e,"swap_debt",[y(e.caller),k(t.accountNonce),B(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),B(t.newDebt.hubId,t.newDebt.asset),C(t.steps)])}function ae(e,t){return M(e,"swap_collateral",[y(e.caller),k(t.accountNonce),B(t.current.hubId,t.current.asset),S(t.fromAmount),B(t.newCollateral.hubId,t.newCollateral.asset),C(t.steps)])}function ne(e,t){return M(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),B(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),B(t.debt.hubId,t.debt.asset),C(t.steps),R(t.closePosition)])}const se="/stellar-lending",ie=25,le=encodeURIComponent,ue=(e,t)=>e.fetchWithTimeout(`${se}/context`,t),ce=(e,t)=>e.fetchWithTimeout(`${se}/live-state`,t),pe=(e,t)=>e.fetchWithTimeout(`${se}/assets`,t),de=(e,t)=>e.fetchWithTimeout(`${se}/hubs`,t),me=(e,t)=>e.fetchWithTimeout(`${se}/spokes`,t),fe=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${se}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},he=(e,t,r,o,a)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}`,a),ge=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/holders`,{...n,params:{side:a}}),we=(e,t,r)=>e.fetchWithTimeout(`${se}/assets/${le(t)}`,r),_e=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/page`,{...o,params:{...r}}),be=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/markets`,{...o,params:{side:r}}),ye=(e,t,r)=>e.fetchWithTimeout(`${se}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${se}/spokes/${t}`,r),ve=(e,t,r)=>e.fetchWithTimeout(`${se}/users/${le(t)}/positions`,r),ke=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${se}/users/${le(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},Re=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(t)}/positions`,r),Te=(e,t={},r)=>{const{top:o=ie,continuationToken:a}=t;return e.fetchWithTimeout(`${se}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Ie=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${se}/hubs/${t}/graph`,{...o,params:{...r}}),Ae=(e,t,r,o)=>e.fetchWithTimeout(`${se}/spokes/${t}/graph`,{...o,params:{...r}}),Ee=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/graph`,{...n,params:{...a}}),$e=(e,t)=>e.fetchWithTimeout(`${se}/protocol-config`,t),Be=(e,t,r)=>e.fetchWithTimeout(`${se}/protocol-config/${le(t)}`,r),Ne=(e,t,r)=>e.fetchWithTimeout(t?`${se}/roles?contractAddress=${le(t)}`:`${se}/roles`,r),Pe=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(String(t))}/delegates`,r),Oe=(e,t)=>e.fetchWithTimeout(`${se}/blend-pools`,t),Ue=e=>({context:t=>ue(e,t),liveState:t=>ce(e,t),protocolConfig:t=>$e(e,t),contractConfig:(t,r)=>Be(e,t,r),contractRoles:(t,r)=>Ne(e,t,r),accountDelegates:(t,r)=>Pe(e,t,r),blendPools:t=>Oe(e,t),assets:t=>pe(e,t),hubs:t=>de(e,t),spokes:t=>me(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?fe(e,t,r):fe(e,{},t);var o},reserve:(t,r,o,a)=>he(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ge(e,t,r,o,a,n),asset:(t,r)=>we(e,t,r),assetMarkets:(t,r,o)=>be(e,t,r,o),hub:(t,r)=>ye(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>ve(e,t,r),userActivity:(t,r,o)=>ke(e,t,r,o),accountPositions:(t,r)=>Re(e,t,r),governanceProposals:(t,r)=>Te(e,t,r),assetGraph:(t,r,o)=>Ie(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>Ae(e,t,r,o),reserveGraph:(t,r,o,a,n)=>Ee(e,t,r,o,a,n)}),Le=e=>U({base_borrow_rate:S(e.baseBorrowRateRay),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),qe=e=>U({asset_decimals:v(e.assetDecimals),asset_id:y(e.assetId),base_borrow_rate:S(e.baseBorrowRateRay),flashloan_fee:v(e.flashloanFeeBps),is_flashloanable:R(e.isFlashloanable),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),ze=e=>U({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),We=e=>{if("Token"in e&&e.Token)return A([I("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([I("Ref"),I(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},De=e=>{if("Stellar"in e)return A([I("Stellar"),y(e.Stellar)]);if("Symbol"in e)return A([I("Symbol"),I(e.Symbol)]);if("String"in e)return A([I("String"),T(e.String)]);throw new Error(`Stellar builder: unknown OracleAssetRef ${JSON.stringify(e)}`)},Ce=e=>{if("Spot"===e)return A([I("Spot")]);if(e&&"object"==typeof e&&"Twap"in e)return A([I("Twap"),v(Number(e.Twap))]);throw new Error(`Stellar builder: unknown OracleReadMode ${JSON.stringify(e)}`)},Ve=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Me=e=>{if("Market"===e||"Fundamental"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Fe=e=>{if("Reflector"in e){const t=e.Reflector;return A([I("Reflector"),U({asset:De(t.asset),contract:y(t.contract),read_mode:Ce(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([I("MultiFeed"),U({contract:y(t.contract),feed_id:T(t.feedId),kind:Ve(t.kind),nature:Me(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ge=e=>{const t=e;return U({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:Fe(t.provider)})},Xe=e=>{if("RequireDisjoint"===e)return A([I("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([I("AllowShared"),A(t.map((e=>U({contract:y(e.contract),kind:Ve(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},He=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return U({asset_decimals:v(Number(t.assetDecimals)),independence:Xe(t.independence),max_price_stale_seconds:k(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:S(String(t.maxSanityPriceWad)),min_sanity_price_wad:S(String(t.minSanityPriceWad)),sources:A(r.map((e=>(e=>{if("Feed"in e)return A([I("Feed"),Ge(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([I("Scaled"),U({factor:Ge(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:We(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([I("LpShare"),U({key_a:We(t.keyA),key_b:We(t.keyB),kind:A([I(t.kind||"ConstantProduct")]),pool:y(t.pool),reserve_a_decimals:v(t.reserveADecimals),reserve_b_decimals:v(t.reserveBDecimals),share_decimals:v(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})})},je=He;function Je(e,t){return M(e,"upgrade",[E(t.wasmHash)])}function Qe(e,t){return M(e,"migrate",[v(t.newVersion)])}function Ke(e){return M(e,"pause",[])}function Ze(e){return M(e,"unpause",[])}function Ye(e,t){return M(e,"grant_role",[y(t.account),I(t.role)])}function et(e,t){return M(e,"revoke_role",[y(t.account),I(t.role)])}function tt(e,t){return M(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function rt(e){return M(e,"accept_ownership",[])}function ot(e,t){return M(e,"set_swap_aggregator",[y(t.aggregator)])}function at(e,t){return M(e,"set_price_aggregator",[y(t.aggregator)])}const nt=ot;function st(e,t){return M(e,"set_accumulator",[y(t.accumulator)])}function it(e,t){return M(e,"set_position_limits",[ze(t)])}function lt(e,t){return M(e,"approve_blend_pool",[y(t.pool)])}function ut(e,t){return M(e,"revoke_blend_pool",[y(t.pool)])}const ct=lt,pt=ut;function dt(e,t){return M(e,"set_oracle",[We(t.key),He(t.oracle)])}const mt=dt;function ft(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return M(e,"set_tolerance",[We(t.key),U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function ht(e,t){return M(e,"set_spoke_asset_flags",[v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function gt(e,t){return M(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function wt(e,t){return M(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function _t(e,t){return M(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function bt(e,t){return M(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),qe(t.params)])}function yt(e,t){return M(e,"upgrade_liquidity_pool_params",[B(t.hubId,t.asset),Le(t.params)])}function St(e,t){return M(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function vt(e,t){return M(e,"add_rewards",[y(e.caller),P(t.rewards)])}function kt(e,t){return M(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const Rt="00".repeat(32),Tt=e=>{if("string"==typeof e)return E(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return i.ScVal.scvBytes(t)},It=(e,...t)=>A([I(e),...t]),xt=e=>U({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),At=e=>U({asset:y(e.asset),bonus:v(e.bonus),borrow_cap:S(e.borrowCap),can_borrow:R(e.canBorrow),can_collateral:R(e.canCollateral),frozen:R(e.frozen),hub_id:v(e.hubId),paused:R(e.paused),liquidation_fees:v(e.liquidationFees),ltv:v(e.ltv),no_seize:R(e.noSeize),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),Et=e=>U({account:y(e.account),role:I(e.role)});function $t(t,a,s){const i=t.governanceAddress??g(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const Bt=(e,t,r)=>$t(e,"propose",[y(e.caller),t,Tt(r)]),Nt=(e,t,r)=>$t(e,"execute_self",[x(),t,Tt(r)]);function Pt(e,t,r){return Bt(e,It("SetSwapAggregator",y(t.aggregator)),r)}function Ot(e,t,r){return Bt(e,It("SetPriceAggregator",y(t.aggregator)),r)}const Ut=Pt;function Lt(e,t,r){return Bt(e,It("SetAccumulator",y(t.accumulator)),r)}function qt(e,t,r){return Bt(e,It("SetPositionLimits",ze(t)),r)}function zt(e,t){return Bt(e,It("CreateHub"),t)}function Wt(e,t){return Bt(e,It("AddSpoke"),t)}function Dt(e,t,r){return Bt(e,It("RemoveSpoke",v(t.spokeId)),r)}function Ct(e,t,r){return Bt(e,It("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Bt(e,It("EditAssetInSpoke",At(t)),r)}function Mt(e,t,r){return Bt(e,It("RemoveAssetFromSpoke",U({hub_asset:B((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function Ft(e,t,r){return Bt(e,It("SetSpokeLiquidationCurve",U({hf_for_max_bonus_wad:S((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:v(o.liquidationBonusFactorBps),spoke_id:v(o.spokeId),target_hf_wad:S(o.targetHfWad)})),r);var o}function Gt(e,t,r){return Bt(e,It("SetPositionManager",y(t.manager),R(t.isActive)),r)}function Xt(e,t,r){return Bt(e,It("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Ht(e,t,r){return Bt(e,It("ApproveToken",y(t.token)),r)}function jt(e,t,r){return Bt(e,It("RevokeToken",y(t.token)),r)}function Jt(e,t,r){return Bt(e,It("ApproveBlendPool",y(t.pool)),r)}function Qt(e,t,r){return Bt(e,It("RevokeBlendPool",y(t.pool)),r)}function Kt(e,t,r){return Bt(e,It("CreateLiquidityPool",U({asset:y((o=t).asset),hub_id:v(o.hubId),params:qe(o.params)})),r);var o}function Zt(e,t,r){return Bt(e,It("UpgradeLiquidityPoolParams",U({hub_asset:B((o=t).hubId,o.asset),params:Le(o.params)})),r);var o}function Yt(e,t,r){return Bt(e,It("DeployPool",E(t.wasmHash)),r)}function er(e,t,r){return Bt(e,It("UpgradePool",E(t.wasmHash)),r)}function tr(e,t,r){return Bt(e,It("UpgradeController",E(t.wasmHash)),r)}function rr(e,t,r){return Bt(e,It("MigrateController",v(t.newVersion)),r)}function or(e,t,r){return Bt(e,It("TransferCtrlOwnership",xt(t)),r)}function ar(e,t,r){return Bt(e,It("ConfigureAssetOracle",U({key:We((o=t).key),oracle:He(o.oracle)})),r);var o}const nr=ar;function sr(e,t,r){return Bt(e,It("EditOracleTolerance",U({key:We((o=t).key),tolerance:v(o.tolerance)})),r);var o}function ir(e,t,r){return Bt(e,It("UpgradeGov",E(t.wasmHash)),r)}function lr(e,t,r){return Bt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function ur(e,t,r){return Bt(e,It("GrantGovRole",Et(t)),r)}function cr(e,t,r){return Bt(e,It("RevokeGovRole",Et(t)),r)}function pr(e,t,r){return Bt(e,It("TransferGovOwnership",xt(t)),r)}function dr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=Tt(t.predecessor??Rt);return $t(e,"execute",[x(),y(t.target),I(t.functionName),r,o,Tt(t.salt)])}function mr(e,t,r){return Nt(e,It("UpgradeGov",E(t.wasmHash)),r)}function fr(e,t,r){return Nt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function hr(e,t,r){return Nt(e,It("GrantGovRole",Et(t)),r)}function gr(e,t,r){return Nt(e,It("RevokeGovRole",Et(t)),r)}function wr(e,t,r){return Nt(e,It("TransferGovOwnership",xt(t)),r)}const _r=e=>A(e.map(y));function br(e,t,r){return $t(e,"propose_canceller_reset",[_r(t.newCancellers),Tt(r)])}function yr(e,t,r){return $t(e,"execute_canceller_reset",[$(t.executor,y),_r(t.newCancellers),Tt(r)])}function Sr(e,t){return $t(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function vr(e,t){return $t(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function kr(e){return $t(e,"create_hub",[y(e.caller)])}function Rr(e){return $t(e,"add_spoke",[y(e.caller)])}function Tr(e,t){return $t(e,"revoke_role_immediate",[y(t.account),I(t.role)])}function Ir(e){return $t(e,"pause",[y(e.caller)])}function xr(e,t){return Bt(e,It("Unpause"),t)}const Ar=e=>e.toXDR("base64"),Er=e=>i.ScVal.fromXDR(e,"base64"),$r=e=>e.map((e=>String(s(Er(e))))).join(":"),Br=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Nr=e=>Number(e),Pr=e=>String(e),Or=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],Lr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],qr=e=>Array.isArray(e)?e:[],zr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],Lr[Nr(o)]??Br(o)),positionType:t,hubId:Nr(e[1]),asset:Pr(e[2]),scaledAmountRay:Br(e[3]),indexRay:Br(e[4]),amount:Br(e[5]),liquidationThresholdBps:r?void 0:Nr(e[6]),liquidationBonusBps:r?void 0:Nr(e[7]),loanToValueBps:r?void 0:Nr(e[8]),liquidationFeesBps:r?void 0:Nr(e[9])};var o},Wr=e=>{return{owner:Pr(e[0]),spokeId:Nr(e[1]),mode:(t=e[2],Ur[Nr(t)]??"None")};var t},Dr=e=>Array.isArray(e)?e[1]:void 0,Cr=e=>{const t=(r=e,Array.isArray(r)?Pr(r[0]):Pr(r));var r;if("Token"===t)return{Token:Pr(Dr(e))};if("Ref"===t)return{Ref:Pr(Dr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Pr(t.Token)};if(void 0!==t.Ref)return{Ref:Pr(t.Ref)}}return{Token:Pr(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:Nr(e.asset_decimals),maxPriceStaleSeconds:Nr(e.max_price_stale_seconds),sources:qr(e.sources).map((e=>e)),tolerance:{upperRatio:Nr(t.upper_ratio_bps),lowerRatio:Nr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Br(e.min_sanity_price_wad),maxSanityPriceWad:Br(e.max_sanity_price_wad)}},Mr={"market:create":e=>({topic:"market:create",data:{hubId:Nr(e.hub_id),baseAsset:Pr(e.base_asset),maxBorrowRate:Br(e.max_borrow_rate),baseBorrowRate:Br(e.base_borrow_rate),slope1:Br(e.slope1),slope2:Br(e.slope2),slope3:Br(e.slope3),midUtilization:Br(e.mid_utilization),optimalUtilization:Br(e.optimal_utilization),maxUtilization:Br(e.max_utilization),reserveFactor:Nr(e.reserve_factor),marketAddress:Pr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Pr(e.asset),maxBorrowRateRay:Br(e.max_borrow_rate),baseBorrowRateRay:Br(e.base_borrow_rate),slope1Ray:Br(e.slope1),slope2Ray:Br(e.slope2),slope3Ray:Br(e.slope3),midUtilizationRay:Br(e.mid_utilization),optimalUtilizationRay:Br(e.optimal_utilization),maxUtilizationRay:Br(e.max_utilization),reserveFactorBps:Nr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:qr(e).map((e=>{return t=qr(e),{hubId:Nr(t[0]),asset:Pr(t[1]),timestamp:Nr(t[2]),supplyIndexRay:Br(t[3]),borrowIndexRay:Br(t[4]),cash:Br(t[5]),suppliedRay:Br(t[6]),borrowedRay:Br(t[7]),revenueRay:Br(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:qr(e).map((e=>{const t=e;return{hubId:Nr(t.hub_id),asset:Pr(t.asset),params:(r=t.params,{maxBorrowRateRay:Br(r.max_borrow_rate),baseBorrowRateRay:Br(r.base_borrow_rate),slope1Ray:Br(r.slope1),slope2Ray:Br(r.slope2),slope3Ray:Br(r.slope3),midUtilizationRay:Br(r.mid_utilization),optimalUtilizationRay:Br(r.optimal_utilization),maxUtilizationRay:Br(r.max_utilization),reserveFactorBps:Nr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Nr(r.flashloan_fee),assetId:Pr(r.asset_id),assetDecimals:Nr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=qr(e);return{topic:"position:batch_update",data:{accountId:Br(t[0]),accountAttributes:Wr(qr(t[1])),updates:[...qr(t[2]).map((e=>zr(qr(e),"Deposit"))),...qr(t[3]).map((e=>zr(qr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),receiver:Pr(e.receiver),caller:Pr(e.caller),amount:Br(e.amount),fee:Br(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Cr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Pr(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Pr(e.liquidator),accountId:Br(e.account_id),repaidUsdWad:Br(e.repaid_usd_wad),bonusBps:Br(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Br(e.account_id),totalBorrowUsdWad:Br(e.total_borrow_usd_wad),totalCollateralUsdWad:Br(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Pr(e.token),amount:Br(e.amount),usdValueWad:Br(e.usd_value_wad),accountId:Br(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),amount:Br(e.amount),fee:Br(e.fee),amountSent:Br(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Pr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Or(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Pr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Pr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Pr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Pr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Or(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Nr(e.max_supply_positions),maxBorrowPositions:Nr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Br(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Pr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Nr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Br(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Br(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Nr(t.liquidation_bonus_factor_bps)}}}},Fr=Object.freeze(Object.keys(Mr));function Gr(e,t){const r=$r(e),o=Mr[r];return o?o(s(Er(t))):null}const Xr="XLENDXLM-a7c9f3",Hr=1e4;function jr(e){const t=BigInt(e).toString(16),r=t.length%2==0?t:`0${t}`;return`${Xr}-${r}`}function Jr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Qr(e,t=0){return 1e4*e+t}function Kr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const Zr=(e,t,r)=>{const o=new URL(t,e.endsWith("/")?e:`${e}/`);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&o.searchParams.set(e,String(t));return o.toString()},Yr=e=>e.baseUrl??d[e.network];async function eo(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Zr(Yr(t),"api/v1/quote",{from:e.from,to:e.to,amountIn:e.amountIn,amountOut:e.amountOut,maxHops:e.maxHops,maxSplits:e.maxSplits,slippage:e.slippage,includePaths:e.includePaths,sender:e.sender,router:e.router,platform:e.platform,fresh:e.fresh}),o=await fetch(r,t.fetchOptions);if(!o.ok){const e=await o.text().catch((()=>""));throw new Error(`Stellar quote server responded ${o.status} ${o.statusText} for ${r} — ${e}`)}return await o.json()}async function to(e){const t=Zr(Yr(e),"api/v1/tokens"),r=await fetch(t,e.fetchOptions);if(!r.ok){const e=await r.text().catch((()=>""));throw new Error(`Stellar quote server responded ${r.status} ${r.statusText} for ${t} — ${e}`)}return await r.json()}const ro=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,oo=e=>q(e).toXDR("base64");function ao(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=C(ro(a,t.referralId));return{xdr:new n(l,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(i.call("execute_strategy",y(t.caller),S(t.totalIn),u)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function no(e,t){return ao(e,t)}function so(e,t={}){if("string"!=typeof e.amountOutMin)throw new Error("mapQuoteResponseToStrategyPayload: quote response is missing `amountOutMin`. Pass `slippage` when fetching the quote.");return{paths:e.paths?e.paths.map((e=>({hops:e.swaps.map(uo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(uo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function io(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:so(e,t)}const lo=so,uo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function co(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function po(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw co(r.invokedContractId,e);throw e}}async function mo(e,t,r){return po(e,t.xdr,r)}function fo(e){if(e<=0||e>4)throw new Error(`Invalid PositionMode ${e} for Stellar — expected 1 (Normal) through 4 (Short). "None" (0) has no Stellar equivalent.`);return e-1}function ho(e,t){return new Uint8Array(0)}const go=e=>{const t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!=0)throw new Error("buildStellarCctpForwardTx: hex input must have even length");return Buffer.from(t,"hex")};function wo(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(go(t.message)),i.ScVal.scvBytes(go(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const _o={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function bo(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=_o[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,Rt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Fr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Hr as SYNTHETIC_EVENT_ORDER_STRIDE,Xr as XOXNO_LENDING_STELLAR_TICKER,ho as buildSameTokenRepaySwapSteps,rt as buildStellarAcceptOwnershipTx,vt as buildStellarAddRewardsTx,lt as buildStellarApproveBlendPoolTx,ct as buildStellarApproveTokenTx,no as buildStellarBatchSwapTx,X as buildStellarBorrowBatchTx,H as buildStellarBorrowTx,wo as buildStellarCctpForwardTx,St as buildStellarClaimRevenueTx,bt as buildStellarCreateLiquidityPoolTx,yr as buildStellarExecuteCancellerResetTx,ao as buildStellarExecuteStrategyTx,ee as buildStellarFlashLoanTx,Rr as buildStellarGovernanceAddSpokeImmediateTx,kr as buildStellarGovernanceCreateHubImmediateTx,mr as buildStellarGovernanceExecuteGovernanceUpgradeTx,hr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,gr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,wr as buildStellarGovernanceExecuteTransferGovOwnTx,dr as buildStellarGovernanceExecuteTx,fr as buildStellarGovernanceExecuteUpdateDelayTx,Ir as buildStellarGovernancePauseTx,Tr as buildStellarGovernanceRevokeRoleImmediateTx,vr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,Sr as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ye as buildStellarGrantRoleTx,jr as buildStellarLendingIdentifier,Z as buildStellarLiquidateTx,te as buildStellarMigrateFromBlendTx,Qe as buildStellarMigrateTx,re as buildStellarMultiplyTx,Ke as buildStellarPauseTx,Ct as buildStellarProposeAddAssetToSpokeTx,Wt as buildStellarProposeAddSpokeTx,Jt as buildStellarProposeApproveBlendPoolTx,Ht as buildStellarProposeApproveTokenTx,br as buildStellarProposeCancellerResetTx,ar as buildStellarProposeConfigureAssetOracleTx,nr as buildStellarProposeConfigureMarketOracleTx,zt as buildStellarProposeCreateHubTx,Kt as buildStellarProposeCreateLiquidityPoolTx,Yt as buildStellarProposeDeployPoolTx,Vt as buildStellarProposeEditAssetInSpokeTx,sr as buildStellarProposeEditOracleToleranceTx,ir as buildStellarProposeGovernanceUpgradeTx,ur as buildStellarProposeGrantGovernanceRoleTx,rr as buildStellarProposeMigrateControllerTx,Mt as buildStellarProposeRemoveAssetFromSpokeTx,Dt as buildStellarProposeRemoveSpokeTx,Qt as buildStellarProposeRevokeBlendPoolTx,cr as buildStellarProposeRevokeGovernanceRoleTx,jt as buildStellarProposeRevokeTokenTx,Lt as buildStellarProposeSetAccumulatorTx,Ut as buildStellarProposeSetAggregatorTx,Xt as buildStellarProposeSetMinBorrowCollatTx,qt as buildStellarProposeSetPositionLimitsTx,Gt as buildStellarProposeSetPositionManagerTx,Ot as buildStellarProposeSetPriceAggregatorTx,Ft as buildStellarProposeSetSpokeLiquidationCurveTx,Pt as buildStellarProposeSetSwapAggregatorTx,or as buildStellarProposeTransferCtrlOwnershipTx,pr as buildStellarProposeTransferGovOwnTx,xr as buildStellarProposeUnpauseTx,lr as buildStellarProposeUpdateDelayTx,tr as buildStellarProposeUpgradeControllerTx,Zt as buildStellarProposeUpgradePoolParamsTx,er as buildStellarProposeUpgradePoolTx,_t as buildStellarRenewAccountTx,Q as buildStellarRepayBatchTx,ne as buildStellarRepayDebtWithCollateralTx,K as buildStellarRepayTx,ut as buildStellarRevokeBlendPoolTx,et as buildStellarRevokeRoleTx,pt as buildStellarRevokeTokenTx,st as buildStellarSetAccumulatorTx,nt as buildStellarSetAggregatorTx,mt as buildStellarSetMarketOracleConfigTx,gt as buildStellarSetOracleSanityBoundsTx,ft as buildStellarSetOracleToleranceTx,dt as buildStellarSetOracleTx,it as buildStellarSetPositionLimitsTx,at as buildStellarSetPriceAggregatorTx,ht as buildStellarSetSpokeAssetFlagsTx,ot as buildStellarSetSwapAggregatorTx,F as buildStellarSupplyBatchTx,G as buildStellarSupplyTx,ae as buildStellarSwapCollateralTx,oe as buildStellarSwapDebtTx,tt as buildStellarTransferOwnershipTx,Ze as buildStellarUnpauseTx,kt as buildStellarUpdateAccountThresholdTx,wt as buildStellarUpdateIndexesTx,Je as buildStellarUpgradeControllerTx,yt as buildStellarUpgradeLiquidityPoolParamsTx,j as buildStellarWithdrawBatchTx,J as buildStellarWithdrawTx,M as buildTx,Gr as decodeStellarLendingEvent,Y as decodeStellarLiquidateReturn,He as encodeAssetOracle,Le as encodeInterestRateModel,je as encodeMarketOracleConfigInput,qe as encodeMarketParamsRaw,ze as encodePositionLimits,We as encodePriceKey,oo as encodeStrategyPayloadToRouteXdr,Jr as extractEventOrder,Pe as getStellarAccountDelegates,Re as getStellarAccountPositions,eo as getStellarAggregatorQuote,h as getStellarAggregatorRouter,we as getStellarAsset,Ie as getStellarAssetGraph,be as getStellarAssetMarkets,_e as getStellarAssetPage,pe as getStellarAssets,Oe as getStellarBlendPools,Be as getStellarContractConfig,Ne as getStellarContractRoles,g as getStellarGovernance,Te as getStellarGovernanceProposals,ye as getStellarHub,xe as getStellarHubGraph,de as getStellarHubs,ue as getStellarLendingContext,f as getStellarLendingController,ce as getStellarLendingLiveState,$e as getStellarProtocolConfig,to as getStellarQuoteTokens,he as getStellarReserve,Ee as getStellarReserveGraph,ge as getStellarReserveHolders,fe as getStellarReserves,Se as getStellarSpoke,Ae as getStellarSpokeGraph,me as getStellarSpokes,ke as getStellarUserActivity,ve as getStellarUserPositions,lo as mapQuoteResponseToAggregatorSwap,so as mapQuoteResponseToStrategyPayload,io as mapQuoteResponseToStrategySwap,bo as mapSorobanError,Kr as mapStellarPositionActivityType,mo as prepareStellarBuiltTx,po as prepareStellarTxXdr,$r as stellarLendingDispatchKey,Ue as stellarLendingRead,Qr as syntheticEventOrder,co as tagStellarInvokedContractError,Ar as toBase64Xdr,fo as toStellarPositionMode};
|
|
1
|
+
"undefined"!=typeof globalThis&&void 0===globalThis.self&&(globalThis.self=globalThis);import{Account as e,Address as t,BASE_FEE as r,Contract as o,ScInt as a,TransactionBuilder as n,scValToNative as s,xdr as i}from"@stellar/stellar-sdk";const l={mainnet:process.env.STELLAR_LENDING_CONTROLLER_MAINNET??"",testnet:process.env.STELLAR_LENDING_CONTROLLER_TESTNET??""},u={mainnet:process.env.STELLAR_AGGREGATOR_ROUTER_MAINNET??"",testnet:process.env.STELLAR_AGGREGATOR_ROUTER_TESTNET??""},c={mainnet:process.env.STELLAR_GOVERNANCE_MAINNET??"",testnet:process.env.STELLAR_GOVERNANCE_TESTNET??""},p={mainnet:"https://soroban-rpc.stellar.org",testnet:"https://soroban-testnet.stellar.org"},d={mainnet:process.env.STELLAR_QUOTE_URL_MAINNET??"https://stellar-swap.xoxno.com",testnet:process.env.STELLAR_QUOTE_URL_TESTNET??"https://testnet-stellar-swap.xoxno.com"},m={mainnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"};function f(e){const t=l[e];if(!t)throw new Error(`Stellar lending controller address not configured for network "${e}". Set STELLAR_LENDING_CONTROLLER_${e.toUpperCase()} env var.`);return t}function h(e){const t=u[e];if(!t)throw new Error(`Stellar aggregator router address not configured for network "${e}". Set STELLAR_AGGREGATOR_ROUTER_${e.toUpperCase()} env var.`);return t}function g(e){const t=c[e];if(!t)throw new Error(`Stellar governance address not configured for network "${e}". Set STELLAR_GOVERNANCE_${e.toUpperCase()} env var.`);return t}const w=["Soroswap","Aquarius","Phoenix","Sushi","CometDex"],_={Soroswap:0,Aquarius:1,Phoenix:2,Sushi:3,CometDex:4},b=1e6,y=e=>new t(e).toScVal(),S=e=>new a(e).toI128(),v=e=>i.ScVal.scvU32(e),k=e=>new a("string"==typeof e?e:e.toString()).toU64(),R=e=>i.ScVal.scvBool(e),T=e=>i.ScVal.scvString(e),I=e=>i.ScVal.scvSymbol(e),x=()=>i.ScVal.scvVoid(),A=e=>i.ScVal.scvVec(e),E=(e,t=32)=>{const r=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(r,"hex");if(o.length!==t)throw new Error(`Stellar builder: expected a ${t}-byte BytesN (got ${o.length} bytes from "${e}")`);return i.ScVal.scvBytes(o)},$=(e,t)=>null==e?x():t(e),B=(e,t)=>U({asset:y(t),hub_id:v(e)}),N=(e,t,r)=>i.ScVal.scvVec([B(e,t),S(r)]),P=e=>i.ScVal.scvVec(e.map((e=>N(e.hubId,e.asset,e.amount)))),O=e=>{if("Transfer"===e)return A([I("Transfer")]);if(e&&"object"==typeof e&&"Credit"in e){const t=e.Credit;if("number"==typeof t&&!Number.isInteger(t))throw new Error(`Stellar builder: SeizeMode Credit account id must be an integer u64, got ${t}`);return A([I("Credit"),k(t)])}throw new Error(`Stellar builder: SeizeMode must be 'Transfer' or { Credit: accountId }, got ${JSON.stringify(e)}`)},U=e=>{const t=Object.keys(e).sort().map((t=>new i.ScMapEntry({key:I(t),val:e[t]})));return i.ScVal.scvMap(t)};class q{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 q(e.totalMinOut),r=t.asset(e.tokenIn),o=t.asset(e.tokenOut);if(r===o)throw new Error("Stellar builder: `tokenIn` and `tokenOut` are the same asset");if(e.burnPool){const o=t.asset(e.burnPool),a=t.amountList.length;for(const r of e.burnMinAmounts??[])t.amount(r);t.emit(5,0,o,r,a)}if(t.lowerPaths(e.paths),e.mintPool){const r=e.preSwapAmount;if(r&&BigInt(r)>0n){const o=e.mintPoolTokens;if(!o||2!==o.length)throw new Error("Stellar builder: `preSwapAmount` needs `mintPoolTokens` to name the pool’s two constituents");const[a,n]=o,[s,i]=e.preSwapFromA?[a,n]:[n,a];t.emit(_.Aquarius,2+t.amount(r),t.asset(e.mintPool),t.asset(s),t.asset(i))}t.emit(6,0,t.asset(e.mintPool),o,t.amount(e.mintMinShares??"1"))}const a=Number(e.referralId??0);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error(`Stellar builder: referral id ${e.referralId} does not fit the wire’s u32`);return U({amounts:i.ScVal.scvVec(t.amountList.map((e=>S(e)))),assets:i.ScVal.scvVec(t.assetList.map((e=>y(e)))),ops:i.ScVal.scvBytes(t.toBytes(r,o,a))})},z=e=>{const t=Buffer.from(e);if(0===t.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return i.ScVal.scvBytes(t)},W=()=>i.ScVal.scvBytes(Buffer.alloc(0)),C=e=>{const t=e.trim();if(t.startsWith("0x")){const e=t.slice(2);if(!((r=e).length>0&&r.length%2==0&&/^[0-9a-fA-F]+$/.test(r)))throw new Error("Stellar builder: strategy swap bytes hex string must be 0x-prefixed and even-length");return Buffer.from(e,"hex")}var r;if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Stellar builder: strategy swap bytes must be base64 routeXdr or 0x-prefixed hex");const o=Buffer.from(t,"base64");if(0===o.length)throw new Error("Stellar builder: strategy swap bytes must be non-empty base64 routeXdr, 0x hex string, or Uint8Array");return o},D=e=>{if("string"==typeof e)return z(C(e));if(e instanceof Uint8Array)return 0===e.length?W():z(e);if(e&&"object"==typeof e)return"routeXdr"in(r=e)&&"string"==typeof r.routeXdr?z(C(e.routeXdr)):(e=>"swapXdr"in e&&"string"==typeof e.swapXdr)(e)?z(C(e.swapXdr)):(e=>"bytes"in e&&("string"==typeof e.bytes||e.bytes instanceof Uint8Array))(e)?"string"==typeof e.bytes?z(C(e.bytes)):0===e.bytes.length?W():z(e.bytes):(t=(e=>{if(!e||"object"!=typeof e)throw new Error("Stellar builder: decoded strategy `steps` must be a StrategyPayload ({ paths, tokenIn, tokenOut, totalMinOut })");const t=e;if(!Array.isArray(t.paths)||0===t.paths.length)throw new Error("Stellar builder: `steps.paths` must be a non-empty array of strategy paths");if("string"!=typeof t.tokenIn)throw new Error("Stellar builder: `steps.tokenIn` must be a contract address");if("string"!=typeof t.tokenOut)throw new Error("Stellar builder: `steps.tokenOut` must be a contract address");if("string"!=typeof t.totalMinOut)throw new Error("Stellar builder: `steps.totalMinOut` must be an i128 decimal string");const r=new Map;for(const[e,o]of t.paths.entries()){if(!o||"number"!=typeof o.splitPpm||o.splitPpm<=0||!Array.isArray(o.hops)||0===o.hops.length)throw new Error(`Stellar builder: \`steps.paths[${e}]\` must have splitPpm > 0 and a non-empty hops array`);for(const[t,r]of o.hops.entries())if(!r||"string"!=typeof r.pool||"string"!=typeof r.tokenIn||"string"!=typeof r.tokenOut||!w.includes(r.venue))throw new Error(`Stellar builder: \`steps.paths[${e}].hops[${t}]\` must have pool, tokenIn, tokenOut, and a valid Soroban venue`);const t=o.hops[0];r.set(t.tokenIn,(r.get(t.tokenIn)??0)+o.splitPpm)}for(const[e,o]of r){if(o>b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} sums to ${o}, above 1000000`);if(!t.mintPool&&o!==b)throw new Error(`Stellar builder: \`steps.paths[].splitPpm\` for ${e} must sum to 1000000, got ${o}`)}return t})(e),i.ScVal.scvBytes(Buffer.from(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 M(t,a,s){const i=t.controllerAddress??f(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}function F(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"supply",[y(e.caller),k(r),v(o),P([...t.assets])])}function G(e,t){return F(e,{accountNonce:t.accountNonce,spokeId:t.spokeId,assets:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function X(e,t){return M(e,"borrow",[y(e.caller),k(t.accountNonce),P([...t.borrows]),$(t.to,y)])}function H(e,t){return X(e,{accountNonce:t.accountNonce,borrows:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function j(e,t){return M(e,"withdraw",[y(e.caller),k(t.accountNonce),P([...t.withdrawals]),$(t.to,y)])}function J(e,t){return j(e,{accountNonce:t.accountNonce,withdrawals:[{hubId:t.hubId,asset:t.asset,amount:t.amount}],to:t.to})}function Q(e,t){return M(e,"repay",[y(e.caller),k(t.accountNonce),P([...t.payments])])}function K(e,t){return Q(e,{accountNonce:t.accountNonce,payments:[{hubId:t.hubId,asset:t.asset,amount:t.amount}]})}function Z(e,t){return M(e,"liquidate",[y(e.caller),k(t.accountNonce),P([...t.debtPayments]),O(t.seizeMode??"Transfer")])}function Y(e){const t=s(i.ScVal.fromXDR(e,"base64"));if("bigint"==typeof t||"number"==typeof t)return t.toString();throw new Error("Stellar builder: liquidate return value must be a u64, got "+typeof t)}function ee(e,t){return M(e,"flash_loan",[y(e.caller),B(t.hubId,t.asset),S(t.amount),y(t.receiver),V(t.data)])}function te(e,t){return M(e,"migrate_from_blend",[y(e.caller),k(t.accountId),v(t.spokeId),v(t.hubId),y(t.blendPool),A(t.collateralTokens.map(y)),A(t.supplyTokens.map(y)),(r=t.debtCaps.map((e=>({token:e.token,amount:e.cap}))),i.ScVal.scvVec(r.map((e=>{return t=e.token,r=e.amount,i.ScVal.scvVec([y(t),S(r)]);var t,r}))))]);var r}function re(e,t){const r=t.accountNonce??0,o=t.spokeId??0;return M(e,"multiply",[y(e.caller),k(r),v(o),B(t.collateral.hubId,t.collateral.asset),S(t.debtToFlashLoan),B(t.debt.hubId,t.debt.asset),v(t.mode),D(t.steps),$(t.initialPayment,(e=>N(e.hubId,e.asset,e.amount))),$(t.convertSwap,D)])}function oe(e,t){return M(e,"swap_debt",[y(e.caller),k(t.accountNonce),B(t.existingDebt.hubId,t.existingDebt.asset),S(t.newDebtAmount),B(t.newDebt.hubId,t.newDebt.asset),D(t.steps)])}function ae(e,t){return M(e,"swap_collateral",[y(e.caller),k(t.accountNonce),B(t.current.hubId,t.current.asset),S(t.fromAmount),B(t.newCollateral.hubId,t.newCollateral.asset),D(t.steps)])}function ne(e,t){return M(e,"repay_debt_with_collateral",[y(e.caller),k(t.accountNonce),B(t.collateral.hubId,t.collateral.asset),S(t.collateralAmount),B(t.debt.hubId,t.debt.asset),D(t.steps),R(t.closePosition)])}const se="/stellar-lending",ie=25,le=encodeURIComponent,ue=(e,t)=>e.fetchWithTimeout(`${se}/context`,t),ce=(e,t)=>e.fetchWithTimeout(`${se}/live-state`,t),pe=(e,t)=>e.fetchWithTimeout(`${se}/assets`,t),de=(e,t)=>e.fetchWithTimeout(`${se}/hubs`,t),me=(e,t)=>e.fetchWithTimeout(`${se}/spokes`,t),fe=(e,t={},r)=>{const{hubId:o,spokeId:a,asset:n}=t;return e.fetchWithTimeout(`${se}/reserves`,{...r,params:{...void 0!==o?{hubId:o}:{},...void 0!==a?{spokeId:a}:{},...n?{asset:n}:{}}})},he=(e,t,r,o,a)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}`,a),ge=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/holders`,{...n,params:{side:a}}),we=(e,t,r)=>e.fetchWithTimeout(`${se}/assets/${le(t)}`,r),_e=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/page`,{...o,params:{...r}}),be=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/markets`,{...o,params:{side:r}}),ye=(e,t,r)=>e.fetchWithTimeout(`${se}/hubs/${t}`,r),Se=(e,t,r)=>e.fetchWithTimeout(`${se}/spokes/${t}`,r),ve=(e,t,r)=>e.fetchWithTimeout(`${se}/users/${le(t)}/positions`,r),ke=(e,t,r={},o)=>{const{skip:a,top:n}=r;return e.fetchWithTimeout(`${se}/users/${le(t)}/activity`,{...o,params:{...void 0!==a?{skip:a}:{},...void 0!==n?{top:n}:{}}})},Re=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(t)}/positions`,r),Te=(e,t={},r)=>{const{top:o=ie,continuationToken:a}=t;return e.fetchWithTimeout(`${se}/governance/proposals`,{...r,params:{top:o,...a?{continuationToken:a}:{}}})},Ie=(e,t,r,o)=>e.fetchWithTimeout(`${se}/assets/${le(t)}/graph`,{...o,params:{...r}}),xe=(e,t,r,o)=>e.fetchWithTimeout(`${se}/hubs/${t}/graph`,{...o,params:{...r}}),Ae=(e,t,r,o)=>e.fetchWithTimeout(`${se}/spokes/${t}/graph`,{...o,params:{...r}}),Ee=(e,t,r,o,a,n)=>e.fetchWithTimeout(`${se}/reserves/${t}/${r}/${le(o)}/graph`,{...n,params:{...a}}),$e=(e,t)=>e.fetchWithTimeout(`${se}/protocol-config`,t),Be=(e,t,r)=>e.fetchWithTimeout(`${se}/protocol-config/${le(t)}`,r),Ne=(e,t,r)=>e.fetchWithTimeout(t?`${se}/roles?contractAddress=${le(t)}`:`${se}/roles`,r),Pe=(e,t,r)=>e.fetchWithTimeout(`${se}/accounts/${le(String(t))}/delegates`,r),Oe=(e,t)=>e.fetchWithTimeout(`${se}/blend-pools`,t),Ue=e=>({context:t=>ue(e,t),liveState:t=>ce(e,t),protocolConfig:t=>$e(e,t),contractConfig:(t,r)=>Be(e,t,r),contractRoles:(t,r)=>Ne(e,t,r),accountDelegates:(t,r)=>Pe(e,t,r),blendPools:t=>Oe(e,t),assets:t=>pe(e,t),hubs:t=>de(e,t),spokes:t=>me(e,t),reserves:(t,r)=>{return void 0===(o=t)||"hubId"in o||"spokeId"in o||"asset"in o?fe(e,t,r):fe(e,{},t);var o},reserve:(t,r,o,a)=>he(e,t,r,o,a),reserveHolders:(t,r,o,a,n)=>ge(e,t,r,o,a,n),asset:(t,r)=>we(e,t,r),assetMarkets:(t,r,o)=>be(e,t,r,o),hub:(t,r)=>ye(e,t,r),spoke:(t,r)=>Se(e,t,r),userPositions:(t,r)=>ve(e,t,r),userActivity:(t,r,o)=>ke(e,t,r,o),accountPositions:(t,r)=>Re(e,t,r),governanceProposals:(t,r)=>Te(e,t,r),assetGraph:(t,r,o)=>Ie(e,t,r,o),hubGraph:(t,r,o)=>xe(e,t,r,o),spokeGraph:(t,r,o)=>Ae(e,t,r,o),reserveGraph:(t,r,o,a,n)=>Ee(e,t,r,o,a,n)}),qe=e=>U({base_borrow_rate:S(e.baseBorrowRateRay),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),Le=e=>U({asset_decimals:v(e.assetDecimals),asset_id:y(e.assetId),base_borrow_rate:S(e.baseBorrowRateRay),flashloan_fee:v(e.flashloanFeeBps),is_flashloanable:R(e.isFlashloanable),max_borrow_rate:S(e.maxBorrowRateRay),max_utilization:S(e.maxUtilizationRay),mid_utilization:S(e.midUtilizationRay),optimal_utilization:S(e.optimalUtilizationRay),reserve_factor:v(e.reserveFactorBps),slope1:S(e.slope1Ray),slope2:S(e.slope2Ray),slope3:S(e.slope3Ray)}),ze=e=>U({max_borrow_positions:v(e.maxBorrowPositions),max_supply_positions:v(e.maxSupplyPositions)}),We=e=>{if("Token"in e&&e.Token)return A([I("Token"),y(e.Token)]);if("Ref"in e&&e.Ref)return A([I("Ref"),I(e.Ref)]);throw new Error(`Stellar builder: PriceKey must be { Token } or { Ref }, got ${JSON.stringify(e)}`)},Ce=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)}`)},Ve=e=>{if("Reflector"===e||"RedStone"===e||"Xoxno"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown ProviderKind "${e}"`)},Me=e=>{if("Market"===e||"Fundamental"===e)return A([I(e)]);throw new Error(`Stellar builder: unknown FeedNature "${e}"`)},Fe=e=>{if("Reflector"in e){const t=e.Reflector;return A([I("Reflector"),U({asset:Ce(t.asset),contract:y(t.contract),read_mode:De(t.readMode)})])}if("MultiFeed"in e){const t=e.MultiFeed;return A([I("MultiFeed"),U({contract:y(t.contract),feed_id:T(t.feedId),kind:Ve(t.kind),nature:Me(t.nature)})])}throw new Error(`Stellar builder: unknown ProviderRef ${JSON.stringify(e)}`)},Ge=e=>{const t=e;return U({decimals:v(t.decimals),max_stale_seconds:k(t.maxStaleSeconds),provider:Fe(t.provider)})},Xe=e=>{if("RequireDisjoint"===e)return A([I("RequireDisjoint")]);if(e&&"object"==typeof e&&"AllowShared"in e){const t=e.AllowShared;return A([I("AllowShared"),A(t.map((e=>U({contract:y(e.contract),kind:Ve(e.kind)}))))])}throw new Error(`Stellar builder: unknown IndependencePolicy ${JSON.stringify(e)}`)},He=e=>{const t=e,r=t.sources??[];let o,a;if("number"==typeof t.toleranceBps)o=1e4+t.toleranceBps,a=Math.max(1,Math.floor(1e8/o));else{const e=t.tolerance??{};o=Number(e.upperRatioBps),a=Number(e.lowerRatioBps)}return U({asset_decimals:v(Number(t.assetDecimals)),independence:Xe(t.independence),max_price_stale_seconds:k(Number(t.maxPriceStaleSeconds)),max_sanity_price_wad:S(String(t.maxSanityPriceWad)),min_sanity_price_wad:S(String(t.minSanityPriceWad)),sources:A(r.map((e=>(e=>{if("Feed"in e)return A([I("Feed"),Ge(e.Feed)]);if("Scaled"in e){const t=e.Scaled;return A([I("Scaled"),U({factor:Ge(t.factor),max_factor_wad:S(t.maxFactorWad),min_factor_wad:S(t.minFactorWad),quote:We(t.quote)})])}if("LpShare"in e){const t=e.LpShare;return A([I("LpShare"),U({key_a:We(t.keyA),key_b:We(t.keyB),kind:A([I(t.kind||"ConstantProduct")]),pool:y(t.pool),reserve_a_decimals:v(t.reserveADecimals),reserve_b_decimals:v(t.reserveBDecimals),share_decimals:v(t.shareDecimals)})])}throw new Error(`Stellar builder: unknown PriceSource ${JSON.stringify(e)}`)})(e)))),tolerance:U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})})},je=He;function Je(e,t){return M(e,"upgrade",[E(t.wasmHash)])}function Qe(e,t){return M(e,"migrate",[v(t.newVersion)])}function Ke(e){return M(e,"pause",[])}function Ze(e){return M(e,"unpause",[])}function Ye(e,t){return M(e,"grant_role",[y(t.account),I(t.role)])}function et(e,t){return M(e,"revoke_role",[y(t.account),I(t.role)])}function tt(e,t){return M(e,"transfer_ownership",[y(t.newOwner),v(t.liveUntilLedger)])}function rt(e){return M(e,"accept_ownership",[])}function ot(e,t){return M(e,"set_swap_aggregator",[y(t.aggregator)])}function at(e,t){return M(e,"set_price_aggregator",[y(t.aggregator)])}const nt=ot;function st(e,t){return M(e,"set_accumulator",[y(t.accumulator)])}function it(e,t){return M(e,"set_position_limits",[ze(t)])}function lt(e,t){return M(e,"approve_blend_pool",[y(t.pool)])}function ut(e,t){return M(e,"revoke_blend_pool",[y(t.pool)])}const ct=lt,pt=ut;function dt(e,t){return M(e,"set_oracle",[We(t.key),He(t.oracle)])}const mt=dt;function ft(e,t){const r=t.toleranceBps,o=t.upperRatioBps??1e4+r,a=t.lowerRatioBps??Math.max(1,Math.floor(1e8/o));return M(e,"set_tolerance",[We(t.key),U({lower_ratio_bps:v(a),upper_ratio_bps:v(o)})])}function ht(e,t){return M(e,"set_spoke_asset_flags",[v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function gt(e,t){return M(e,"set_oracle_sanity_bounds",[y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function wt(e,t){return M(e,"update_indexes",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function _t(e,t){return M(e,"renew_account",[y(e.caller),k(t.accountNonce)])}function bt(e,t){return M(e,"create_liquidity_pool",[v(t.hubId),y(t.asset),Le(t.params)])}function yt(e,t){return M(e,"upgrade_liquidity_pool_params",[B(t.hubId,t.asset),qe(t.params)])}function St(e,t){return M(e,"claim_revenue",[y(e.caller),A(t.assets.map((e=>B(e.hubId,e.asset))))])}function vt(e,t){return M(e,"add_rewards",[y(e.caller),P(t.rewards)])}function kt(e,t){return M(e,"update_account_threshold",[y(e.caller),R(t.hasRisks),A(t.accountNonces.map((e=>k(e))))])}const Rt="00".repeat(32),Tt=e=>{if("string"==typeof e)return E(e);const t=Buffer.from(e);if(32!==t.length)throw new Error(`Stellar governance builder: expected a 32-byte salt (got ${t.length} bytes)`);return i.ScVal.scvBytes(t)},It=(e,...t)=>A([I(e),...t]),xt=e=>U({new_owner:y(e.newOwner),live_until_ledger:v(e.liveUntilLedger)}),At=e=>U({asset:y(e.asset),bonus:v(e.bonus),borrow_cap:S(e.borrowCap),can_borrow:R(e.canBorrow),can_collateral:R(e.canCollateral),frozen:R(e.frozen),hub_id:v(e.hubId),paused:R(e.paused),liquidation_fees:v(e.liquidationFees),ltv:v(e.ltv),no_seize:R(e.noSeize),spoke_id:v(e.spokeId),supply_cap:S(e.supplyCap),threshold:v(e.threshold)}),Et=e=>U({account:y(e.account),role:I(e.role)});function $t(t,a,s){const i=t.governanceAddress??g(t.network),l=new o(i),u=new e(t.caller,t.sourceSequence);return{xdr:new n(u,{fee:t.fee??r,networkPassphrase:m[t.network]}).addOperation(l.call(a,...s)).setTimeout(t.timeoutSeconds??300).build().toXDR()}}const Bt=(e,t,r)=>$t(e,"propose",[y(e.caller),t,Tt(r)]),Nt=(e,t,r)=>$t(e,"execute_self",[x(),t,Tt(r)]);function Pt(e,t,r){return Bt(e,It("SetSwapAggregator",y(t.aggregator)),r)}function Ot(e,t,r){return Bt(e,It("SetPriceAggregator",y(t.aggregator)),r)}const Ut=Pt;function qt(e,t,r){return Bt(e,It("SetAccumulator",y(t.accumulator)),r)}function Lt(e,t,r){return Bt(e,It("SetPositionLimits",ze(t)),r)}function zt(e,t){return Bt(e,It("CreateHub"),t)}function Wt(e,t){return Bt(e,It("AddSpoke"),t)}function Ct(e,t,r){return Bt(e,It("RemoveSpoke",v(t.spokeId)),r)}function Dt(e,t,r){return Bt(e,It("AddAssetToSpoke",At(t)),r)}function Vt(e,t,r){return Bt(e,It("EditAssetInSpoke",At(t)),r)}function Mt(e,t,r){return Bt(e,It("RemoveAssetFromSpoke",U({hub_asset:B((o=t).hubId,o.asset),spoke_id:v(o.spokeId)})),r);var o}function Ft(e,t,r){return Bt(e,It("SetSpokeLiquidationCurve",U({hf_for_max_bonus_wad:S((o=t).hfForMaxBonusWad),liquidation_bonus_factor_bps:v(o.liquidationBonusFactorBps),spoke_id:v(o.spokeId),target_hf_wad:S(o.targetHfWad)})),r);var o}function Gt(e,t,r){return Bt(e,It("SetPositionManager",y(t.manager),R(t.isActive)),r)}function Xt(e,t,r){return Bt(e,It("SetMinBorrowCollateralUsd",S(t.floorWad)),r)}function Ht(e,t,r){return Bt(e,It("ApproveToken",y(t.token)),r)}function jt(e,t,r){return Bt(e,It("RevokeToken",y(t.token)),r)}function Jt(e,t,r){return Bt(e,It("ApproveBlendPool",y(t.pool)),r)}function Qt(e,t,r){return Bt(e,It("RevokeBlendPool",y(t.pool)),r)}function Kt(e,t,r){return Bt(e,It("CreateLiquidityPool",U({asset:y((o=t).asset),hub_id:v(o.hubId),params:Le(o.params)})),r);var o}function Zt(e,t,r){return Bt(e,It("UpgradeLiquidityPoolParams",U({hub_asset:B((o=t).hubId,o.asset),params:qe(o.params)})),r);var o}function Yt(e,t,r){return Bt(e,It("DeployPool",E(t.wasmHash)),r)}function er(e,t,r){return Bt(e,It("UpgradePool",E(t.wasmHash)),r)}function tr(e,t,r){return Bt(e,It("UpgradeController",E(t.wasmHash)),r)}function rr(e,t,r){return Bt(e,It("MigrateController",v(t.newVersion)),r)}function or(e,t,r){return Bt(e,It("TransferCtrlOwnership",xt(t)),r)}function ar(e,t,r){return Bt(e,It("ConfigureAssetOracle",U({key:We((o=t).key),oracle:He(o.oracle)})),r);var o}const nr=ar;function sr(e,t,r){return Bt(e,It("EditOracleTolerance",U({key:We((o=t).key),tolerance:v(o.tolerance)})),r);var o}function ir(e,t,r){return Bt(e,It("UpgradeGov",E(t.wasmHash)),r)}function lr(e,t,r){return Bt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function ur(e,t,r){return Bt(e,It("GrantGovRole",Et(t)),r)}function cr(e,t,r){return Bt(e,It("RevokeGovRole",Et(t)),r)}function pr(e,t,r){return Bt(e,It("TransferGovOwnership",xt(t)),r)}function dr(e,t){const r=A(t.argsXdr.map((e=>i.ScVal.fromXDR(e,"base64")))),o=Tt(t.predecessor??Rt);return $t(e,"execute",[x(),y(t.target),I(t.functionName),r,o,Tt(t.salt)])}function mr(e,t,r){return Nt(e,It("UpgradeGov",E(t.wasmHash)),r)}function fr(e,t,r){return Nt(e,It("UpdateGovDelay",v(t.newDelay)),r)}function hr(e,t,r){return Nt(e,It("GrantGovRole",Et(t)),r)}function gr(e,t,r){return Nt(e,It("RevokeGovRole",Et(t)),r)}function wr(e,t,r){return Nt(e,It("TransferGovOwnership",xt(t)),r)}const _r=e=>A(e.map(y));function br(e,t,r){return $t(e,"propose_canceller_reset",[_r(t.newCancellers),Tt(r)])}function yr(e,t,r){return $t(e,"execute_canceller_reset",[$(t.executor,y),_r(t.newCancellers),Tt(r)])}function Sr(e,t){return $t(e,"set_spoke_asset_flags",[y(e.caller),v(t.spokeId),B(t.hubId,t.asset),R(t.paused),R(t.frozen),R(t.noSeize)])}function vr(e,t){return $t(e,"set_oracle_sanity_bounds",[y(e.caller),y(t.asset),S(t.minPriceWad),S(t.maxPriceWad)])}function kr(e){return $t(e,"create_hub",[y(e.caller)])}function Rr(e){return $t(e,"add_spoke",[y(e.caller)])}function Tr(e,t){return $t(e,"revoke_role_immediate",[y(t.account),I(t.role)])}function Ir(e){return $t(e,"pause",[y(e.caller)])}function xr(e,t){return Bt(e,It("Unpause"),t)}const Ar=e=>e.toXDR("base64"),Er=e=>i.ScVal.fromXDR(e,"base64"),$r=e=>e.map((e=>String(s(Er(e))))).join(":"),Br=e=>"bigint"==typeof e||"number"==typeof e?e.toString():String(e),Nr=e=>Number(e),Pr=e=>String(e),Or=e=>e instanceof Uint8Array?Buffer.from(e).toString("hex"):Buffer.isBuffer(e)?e.toString("hex"):String(e),Ur=["None","Multiply","Long","Short"],qr=["supply","borrow","withdraw","repay","liq_repay","liq_seize","multiply","param_upd","sw_debt_r","sw_col_wd","rp_col_wd","rp_col_r","close_wd","migrate","rp_col_net","liq_credit"],Lr=e=>Array.isArray(e)?e:[],zr=(e,t)=>{const r="Borrow"===t;return{action:(o=e[0],qr[Nr(o)]??Br(o)),positionType:t,hubId:Nr(e[1]),asset:Pr(e[2]),scaledAmountRay:Br(e[3]),indexRay:Br(e[4]),amount:Br(e[5]),liquidationThresholdBps:r?void 0:Nr(e[6]),liquidationBonusBps:r?void 0:Nr(e[7]),loanToValueBps:r?void 0:Nr(e[8]),liquidationFeesBps:r?void 0:Nr(e[9])};var o},Wr=e=>{return{owner:Pr(e[0]),spokeId:Nr(e[1]),mode:(t=e[2],Ur[Nr(t)]??"None")};var t},Cr=e=>Array.isArray(e)?e[1]:void 0,Dr=e=>{const t=(r=e,Array.isArray(r)?Pr(r[0]):Pr(r));var r;if("Token"===t)return{Token:Pr(Cr(e))};if("Ref"===t)return{Ref:Pr(Cr(e))};if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;if(void 0!==t.Token)return{Token:Pr(t.Token)};if(void 0!==t.Ref)return{Ref:Pr(t.Ref)}}return{Token:Pr(e)}},Vr=e=>{const t=e.tolerance??{};return{assetDecimals:Nr(e.asset_decimals),maxPriceStaleSeconds:Nr(e.max_price_stale_seconds),sources:Lr(e.sources).map((e=>e)),tolerance:{upperRatio:Nr(t.upper_ratio_bps),lowerRatio:Nr(t.lower_ratio_bps)},independence:e.independence,minSanityPriceWad:Br(e.min_sanity_price_wad),maxSanityPriceWad:Br(e.max_sanity_price_wad)}},Mr={"market:create":e=>({topic:"market:create",data:{hubId:Nr(e.hub_id),baseAsset:Pr(e.base_asset),maxBorrowRate:Br(e.max_borrow_rate),baseBorrowRate:Br(e.base_borrow_rate),slope1:Br(e.slope1),slope2:Br(e.slope2),slope3:Br(e.slope3),midUtilization:Br(e.mid_utilization),optimalUtilization:Br(e.optimal_utilization),maxUtilization:Br(e.max_utilization),reserveFactor:Nr(e.reserve_factor),marketAddress:Pr(e.market_address)}}),"market:params_update":e=>({topic:"market:params_update",data:{asset:Pr(e.asset),maxBorrowRateRay:Br(e.max_borrow_rate),baseBorrowRateRay:Br(e.base_borrow_rate),slope1Ray:Br(e.slope1),slope2Ray:Br(e.slope2),slope3Ray:Br(e.slope3),midUtilizationRay:Br(e.mid_utilization),optimalUtilizationRay:Br(e.optimal_utilization),maxUtilizationRay:Br(e.max_utilization),reserveFactorBps:Nr(e.reserve_factor)}}),"market:batch_state_update":e=>({topic:"market:batch_state_update",data:{updates:Lr(e).map((e=>{return t=Lr(e),{hubId:Nr(t[0]),asset:Pr(t[1]),timestamp:Nr(t[2]),supplyIndexRay:Br(t[3]),borrowIndexRay:Br(t[4]),cash:Br(t[5]),suppliedRay:Br(t[6]),borrowedRay:Br(t[7]),revenueRay:Br(t[8])};var t}))}}),"market:batch_params_update":e=>({topic:"market:batch_params_update",data:{updates:Lr(e).map((e=>{const t=e;return{hubId:Nr(t.hub_id),asset:Pr(t.asset),params:(r=t.params,{maxBorrowRateRay:Br(r.max_borrow_rate),baseBorrowRateRay:Br(r.base_borrow_rate),slope1Ray:Br(r.slope1),slope2Ray:Br(r.slope2),slope3Ray:Br(r.slope3),midUtilizationRay:Br(r.mid_utilization),optimalUtilizationRay:Br(r.optimal_utilization),maxUtilizationRay:Br(r.max_utilization),reserveFactorBps:Nr(r.reserve_factor),isFlashloanable:Boolean(r.is_flashloanable),flashloanFeeBps:Nr(r.flashloan_fee),assetId:Pr(r.asset_id),assetDecimals:Nr(r.asset_decimals)})};var r}))}}),"position:batch_update":e=>{const t=Lr(e);return{topic:"position:batch_update",data:{accountId:Br(t[0]),accountAttributes:Wr(Lr(t[1])),updates:[...Lr(t[2]).map((e=>zr(Lr(e),"Deposit"))),...Lr(t[3]).map((e=>zr(Lr(e),"Borrow")))]}}},"position:flash_loan":e=>({topic:"position:flash_loan",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),receiver:Pr(e.receiver),caller:Pr(e.caller),amount:Br(e.amount),fee:Br(e.fee)}}),"config:asset_oracle":e=>({topic:"config:asset_oracle",data:{key:Dr(e.key),oracle:Vr(e.oracle)}}),"config:oracle":e=>({topic:"config:oracle",data:{asset:Pr(e.asset),oracle:Vr(e.config??e.oracle)}}),"position:liquidation":e=>({topic:"position:liquidation",data:{liquidator:Pr(e.liquidator),accountId:Br(e.account_id),repaidUsdWad:Br(e.repaid_usd_wad),bonusBps:Br(e.bonus_bps)}}),"debt:bad_debt":e=>({topic:"debt:bad_debt",data:{accountId:Br(e.account_id),totalBorrowUsdWad:Br(e.total_borrow_usd_wad),totalCollateralUsdWad:Br(e.total_collateral_usd_wad)}}),"strategy:initial_payment":e=>({topic:"strategy:initial_payment",data:{token:Pr(e.token),amount:Br(e.amount),usdValueWad:Br(e.usd_value_wad),accountId:Br(e.account_id)}}),"strategy:fee":e=>({topic:"strategy:fee",data:{hubId:Nr(e.hub_id),asset:Pr(e.asset),amount:Br(e.amount),fee:Br(e.fee),amountSent:Br(e.amount_sent)}}),"config:approve_blend_pool":e=>({topic:"config:approve_blend_pool",data:{pool:Pr(e.pool??e.blend_pool??e.token),approved:Boolean(e.approved??e.is_approved??!0)}}),"config:approve_token":e=>({topic:"config:approve_token",data:{wasmHash:Or(e.wasm_hash??e.pool),approved:Boolean(e.approved)}}),"config:swap_aggregator":e=>({topic:"config:swap_aggregator",data:{aggregator:Pr(e.aggregator??e.swap_aggregator)}}),"config:price_aggregator":e=>({topic:"config:price_aggregator",data:{aggregator:Pr(e.aggregator??e.price_aggregator)}}),"config:aggregator":e=>({topic:"config:aggregator",data:{aggregator:Pr(e.aggregator)}}),"config:accumulator":e=>({topic:"config:accumulator",data:{accumulator:Pr(e.accumulator)}}),"config:pool_template":e=>({topic:"config:pool_template",data:{wasmHash:Or(e.wasm_hash)}}),"config:position_limits":e=>({topic:"config:position_limits",data:{maxSupplyPositions:Nr(e.max_supply_positions),maxBorrowPositions:Nr(e.max_borrow_positions)}}),"config:min_borrow_collateral":e=>({topic:"config:min_borrow_collateral",data:{minBorrowCollateralUsdWad:Br(e.min_borrow_collateral_usd_wad??e.floor_wad??e.value)}}),"config:oracle_disabled":e=>({topic:"config:oracle_disabled",data:{asset:Pr(e.asset)}}),"config:spoke":e=>{const t=e.spoke;return{topic:"config:spoke",data:{spokeId:Nr(t.spoke_id),isDeprecated:Boolean(t.is_deprecated),liquidationTargetHfWad:Br(t.liquidation_target_hf_wad),healthFactorForMaxBonusWad:Br(t.hf_for_max_bonus_wad),liquidationBonusFactorBps:Nr(t.liquidation_bonus_factor_bps)}}}},Fr=Object.freeze(Object.keys(Mr));function Gr(e,t){const r=$r(e),o=Mr[r];return o?o(s(Er(t))):null}const Xr=1e4;function Hr(e,t){return`${e}-${BigInt(t).toString(10)}`}function jr(e){const t=e.split("-");return t.length>=2&&parseInt(t[1],10)||0}function Jr(e,t=0){return 1e4*e+t}function Qr(e){switch(e){case"liq_repay":return"lendingLiquidateRepayDebt";case"liq_seize":return"lendingLiquidateSeizeCollateral";case"liq_credit":default:return"lendingUpdateAccountPosition";case"param_upd":return"lendingUpdateAccountParameters"}}const Kr=(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()},Zr=e=>e.baseUrl??d[e.network];async function Yr(e,t){if(null==e.amountIn==(null==e.amountOut))throw new Error("getStellarAggregatorQuote: exactly one of `amountIn` or `amountOut` must be provided");const r=Kr(Zr(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 eo(e){const t=Kr(Zr(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 to=(e,t)=>(e=>Boolean(e&&"object"==typeof e&&!(e instanceof Uint8Array)&&"paths"in e))(e)&&void 0===e.referralId?{...e,referralId:t??0}:e,ro=e=>L(e).toXDR("base64");function oo(t,a){const s=t.routerAddress??h(t.network),i=new o(s),l=new e(t.caller,t.sourceSequence),u=D(to(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 ao(e,t){return oo(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(lo),splitPpm:e.splitPpm}))):[{hops:e.hops.map(lo),splitPpm:1e6}],referralId:t.referralId??0,tokenIn:e.from,tokenOut:e.to,totalMinOut:e.amountOutMin}}function so(e,t={}){const r=e;return"string"==typeof r.routeXdr&&r.routeXdr.length>0?{routeXdr:r.routeXdr}:no(e,t)}const io=no,lo=e=>({amountOut:e.amountOut,pool:e.address,tokenIn:e.from,tokenOut:e.to,venue:e.dex});function uo(e,t){const r=t instanceof Error?t.message:String(t);return new Error(`[xoxno-invoked:${e}] ${r}`)}async function co(e,t,r){const o=n.fromXDR(t,"base64");try{return(await e.prepareTransaction(o)).toXDR()}catch(e){if(r?.invokedContractId)throw uo(r.invokedContractId,e);throw e}}async function po(e,t,r){return co(e,t.xdr,r)}function mo(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 fo(e,t){return new Uint8Array(0)}const ho=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 go(t){const r=new e(t.caller,t.sourceSequence),a=new o(t.forwarderAddress).call("mint_and_forward",i.ScVal.scvBytes(ho(t.message)),i.ScVal.scvBytes(ho(t.attestation)));return{xdr:new n(r,{fee:t.fee??"10000000",networkPassphrase:m[t.network]}).addOperation(a).setTimeout(t.timeoutSeconds??120).build().toXDR()}}const wo={1:{name:"AssetNotSupported",message:"This asset is not supported by the protocol."},2:{name:"AssetAlreadySupported",message:"This asset is already supported."},3:{name:"InvalidTicker",message:"Invalid asset ticker."},6:{name:"InvalidAsset",message:"Invalid asset address."},10:{name:"InvalidWasmHash",message:"The WASM hash is empty or invalid."},11:{name:"InvalidExchangeSrc",message:"The oracle configuration is invalid."},12:{name:"PairNotActive",message:"No oracle is configured for this asset."},32:{name:"OwnerNotSet",message:"The contract owner has not been set."},39:{name:"InvalidTimelockDelay",message:"The timelock delay is out of the allowed range."},41:{name:"InvalidRole",message:"The caller does not hold the required role."},43:{name:"HubNotActive",message:"This hub is not active."},44:{name:"NotAuthorized",message:"The caller is not authorized to perform this action."},46:{name:"OperationNotCancellable",message:"This governance operation cannot be cancelled."},113:{name:"InvalidLiqThreshold",message:"LTV, liquidation threshold, or bonus is out of bounds."},116:{name:"InvalidBorrowParams",message:"Supply or borrow cap configuration is invalid."},117:{name:"InvalidUtilRange",message:"Interest-rate utilization breakpoints are invalid."},132:{name:"AssetDecimalsTooHigh",message:"Asset decimals exceed the protocol maximum (27)."},300:{name:"SpokeNotFound",message:"This spoke does not exist."},301:{name:"SpokeDeprecated",message:"This spoke has been deprecated."},307:{name:"AssetNotInSpoke",message:"This asset is not listed on the spoke."},308:{name:"AssetAlreadyInSpoke",message:"This asset is already listed in the spoke."},309:{name:"SpokeAssetInUse",message:"This spoke asset still has live positions; drain usage before removal."},315:{name:"SpokeAssetPaused",message:"This spoke asset is paused."},316:{name:"SpokeAssetFrozen",message:"This spoke asset is frozen."},317:{name:"SpokeAssetFlagRelaxation",message:"Guardian flag updates may only tighten; clearing a flag requires the timelocked edit."},318:{name:"SpokeAssetSeizureHalted",message:"Liquidation seizure is halted for this spoke asset."},220:{name:"InvalidOracleBase",message:"The oracle quote asset/market is missing or invalid."},221:{name:"InvalidOracleDecimals",message:"The oracle decimals value is invalid."},224:{name:"InvalidSanityBounds",message:"Oracle sanity bounds are invalid (require 0 < min < max)."},225:{name:"OracleCycleDetected",message:"A cycle was detected in the oracle quote chain."}};function _o(e){const t=e.match(/Error\(Contract,\s*#(\d+)\)/);if(!t)return null;const r=Number(t[1]),o=wo[r];return o?{code:r,...o}:null}export{u as STELLAR_AGGREGATOR_ROUTER,c as STELLAR_GOVERNANCE,Rt as STELLAR_GOVERNANCE_ZERO_PREDECESSOR,l as STELLAR_LENDING_CONTROLLER,Fr as STELLAR_LENDING_TOPICS,m as STELLAR_NETWORK_PASSPHRASE,d as STELLAR_QUOTE_URL,p as STELLAR_SOROBAN_RPC_URL,Xr as SYNTHETIC_EVENT_ORDER_STRIDE,fo as buildSameTokenRepaySwapSteps,rt as buildStellarAcceptOwnershipTx,vt as buildStellarAddRewardsTx,lt as buildStellarApproveBlendPoolTx,ct as buildStellarApproveTokenTx,ao as buildStellarBatchSwapTx,X as buildStellarBorrowBatchTx,H as buildStellarBorrowTx,go as buildStellarCctpForwardTx,St as buildStellarClaimRevenueTx,bt as buildStellarCreateLiquidityPoolTx,yr as buildStellarExecuteCancellerResetTx,oo as buildStellarExecuteStrategyTx,ee as buildStellarFlashLoanTx,Rr as buildStellarGovernanceAddSpokeImmediateTx,kr as buildStellarGovernanceCreateHubImmediateTx,mr as buildStellarGovernanceExecuteGovernanceUpgradeTx,hr as buildStellarGovernanceExecuteGrantGovernanceRoleTx,gr as buildStellarGovernanceExecuteRevokeGovernanceRoleTx,wr as buildStellarGovernanceExecuteTransferGovOwnTx,dr as buildStellarGovernanceExecuteTx,fr as buildStellarGovernanceExecuteUpdateDelayTx,Ir as buildStellarGovernancePauseTx,Tr as buildStellarGovernanceRevokeRoleImmediateTx,vr as buildStellarGovernanceSetOracleSanityBoundsImmediateTx,Sr as buildStellarGovernanceSetSpokeAssetFlagsImmediateTx,Ye as buildStellarGrantRoleTx,Hr as buildStellarLendingIdentifier,Z as buildStellarLiquidateTx,te as buildStellarMigrateFromBlendTx,Qe as buildStellarMigrateTx,re as buildStellarMultiplyTx,Ke as buildStellarPauseTx,Dt as buildStellarProposeAddAssetToSpokeTx,Wt as buildStellarProposeAddSpokeTx,Jt as buildStellarProposeApproveBlendPoolTx,Ht as buildStellarProposeApproveTokenTx,br as buildStellarProposeCancellerResetTx,ar as buildStellarProposeConfigureAssetOracleTx,nr as buildStellarProposeConfigureMarketOracleTx,zt as buildStellarProposeCreateHubTx,Kt as buildStellarProposeCreateLiquidityPoolTx,Yt as buildStellarProposeDeployPoolTx,Vt as buildStellarProposeEditAssetInSpokeTx,sr as buildStellarProposeEditOracleToleranceTx,ir as buildStellarProposeGovernanceUpgradeTx,ur as buildStellarProposeGrantGovernanceRoleTx,rr as buildStellarProposeMigrateControllerTx,Mt as buildStellarProposeRemoveAssetFromSpokeTx,Ct as buildStellarProposeRemoveSpokeTx,Qt as buildStellarProposeRevokeBlendPoolTx,cr as buildStellarProposeRevokeGovernanceRoleTx,jt as buildStellarProposeRevokeTokenTx,qt as buildStellarProposeSetAccumulatorTx,Ut as buildStellarProposeSetAggregatorTx,Xt as buildStellarProposeSetMinBorrowCollatTx,Lt as buildStellarProposeSetPositionLimitsTx,Gt as buildStellarProposeSetPositionManagerTx,Ot as buildStellarProposeSetPriceAggregatorTx,Ft as buildStellarProposeSetSpokeLiquidationCurveTx,Pt as buildStellarProposeSetSwapAggregatorTx,or as buildStellarProposeTransferCtrlOwnershipTx,pr as buildStellarProposeTransferGovOwnTx,xr as buildStellarProposeUnpauseTx,lr as buildStellarProposeUpdateDelayTx,tr as buildStellarProposeUpgradeControllerTx,Zt as buildStellarProposeUpgradePoolParamsTx,er as buildStellarProposeUpgradePoolTx,_t as buildStellarRenewAccountTx,Q as buildStellarRepayBatchTx,ne as buildStellarRepayDebtWithCollateralTx,K as buildStellarRepayTx,ut as buildStellarRevokeBlendPoolTx,et as buildStellarRevokeRoleTx,pt as buildStellarRevokeTokenTx,st as buildStellarSetAccumulatorTx,nt as buildStellarSetAggregatorTx,mt as buildStellarSetMarketOracleConfigTx,gt as buildStellarSetOracleSanityBoundsTx,ft as buildStellarSetOracleToleranceTx,dt as buildStellarSetOracleTx,it as buildStellarSetPositionLimitsTx,at as buildStellarSetPriceAggregatorTx,ht as buildStellarSetSpokeAssetFlagsTx,ot as buildStellarSetSwapAggregatorTx,F as buildStellarSupplyBatchTx,G as buildStellarSupplyTx,ae as buildStellarSwapCollateralTx,oe as buildStellarSwapDebtTx,tt as buildStellarTransferOwnershipTx,Ze as buildStellarUnpauseTx,kt as buildStellarUpdateAccountThresholdTx,wt as buildStellarUpdateIndexesTx,Je as buildStellarUpgradeControllerTx,yt as buildStellarUpgradeLiquidityPoolParamsTx,j as buildStellarWithdrawBatchTx,J as buildStellarWithdrawTx,M as buildTx,Gr as decodeStellarLendingEvent,Y as decodeStellarLiquidateReturn,He as encodeAssetOracle,qe as encodeInterestRateModel,je as encodeMarketOracleConfigInput,Le as encodeMarketParamsRaw,ze as encodePositionLimits,We as encodePriceKey,ro as encodeStrategyPayloadToRouteXdr,jr as extractEventOrder,Pe as getStellarAccountDelegates,Re as getStellarAccountPositions,Yr as getStellarAggregatorQuote,h as getStellarAggregatorRouter,we as getStellarAsset,Ie as getStellarAssetGraph,be as getStellarAssetMarkets,_e as getStellarAssetPage,pe as getStellarAssets,Oe as getStellarBlendPools,Be as getStellarContractConfig,Ne as getStellarContractRoles,g as getStellarGovernance,Te as getStellarGovernanceProposals,ye as getStellarHub,xe as getStellarHubGraph,de as getStellarHubs,ue as getStellarLendingContext,f as getStellarLendingController,ce as getStellarLendingLiveState,$e as getStellarProtocolConfig,eo as getStellarQuoteTokens,he as getStellarReserve,Ee as getStellarReserveGraph,ge as getStellarReserveHolders,fe as getStellarReserves,Se as getStellarSpoke,Ae as getStellarSpokeGraph,me as getStellarSpokes,ke as getStellarUserActivity,ve as getStellarUserPositions,io as mapQuoteResponseToAggregatorSwap,no as mapQuoteResponseToStrategyPayload,so as mapQuoteResponseToStrategySwap,_o as mapSorobanError,Qr as mapStellarPositionActivityType,po as prepareStellarBuiltTx,co as prepareStellarTxXdr,$r as stellarLendingDispatchKey,Ue as stellarLendingRead,Jr as syntheticEventOrder,uo as tagStellarInvokedContractError,Ar as toBase64Xdr,mo as toStellarPositionMode};
|
package/dist/sdk/swagger.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PublicOnly, RateType, LoginAccessDto, LoginRequestDto, UserNetworkInfoDto, UserTokenInventoryResponseDto, UserProfileDoc, UserProfileEditDto, UserProfileDto, UserSettingsDoc, NotificationPreferencesPostDto, SetEmailDto, SetPhoneDto, UserBillingDetails, VerifyEmailDto, TradesilvaniaSignature, SuccessDto, CreatorProfileDto, CreatorProfileDoc, CreatorProfileEditDto, CollectionStatsFilter, CollectionStatsPaginated, CheckLikeStatusResponseDto, UserFavoriteResponseDto, TokenDataDocHydrated, XoxnoInfo, XoxnoLiquidStatsDto, AnalyticsMarketplaceUniqueUsers, ProtocolAprType, ProviderDto, DelegationDataOutput, LendingMarketProfile, LendingMarketProfileFilter, LendingMarketProfileQuery, LendingGovernanceProposalFilter, LendingGovernanceProposalQuery, LendingGovernanceProposalDoc, LendingAccountProfile, LendingIndexesDto, LendingAccountPnl, LendingAccountSummary, LendingEModeCategoryProfile, LendingMarketAnalyticsGraph, LendingStatsHistory, LendingMarketAverageGraph, LendingPositionStatus, LendingOverallStats, DefillamaLendingExport, DefillamaLendingHistoryExport, DefillamaLendingRevenueExport, StellarLendingUserStatsExport, NftDocFilter, NftPaginated, LikeNftDto, InventorySummaryDtoHydrated, NftOfferPaginated, NftOfferDocFilter, NftOfferDocHydrated, ValueFp, TraitInfo, CollectionRanksDTO, ListingsResponseDto, NftDocHydrated, SignDataDto, SignWithdrawDto, SignAcceptGlobalOfferDto, SignMintDto, NftDocFull, CollectionProfileDoc, CollectionProfileEditDto, FloorPriceDto, PinnedCollectionDto, CollectionMintProfileDocHydrated, CollectionPinnedStatusDto, FollowCollectionDto, CollectionProfileFilter, CollectionProfilePaginated, CollectionMintProfileFilter, CollectionMintProfilePaginated, CollectionMintProfileDocWithStages, CollectionHoldersDto, CollectionHoldersExportDto, CollectionOwnerDto, CollectionStatsDocHydrated, CollectionOffersFilter, GlobalOfferPaginated, CreatorDetailsDto, ShareholderDto, StakingSummary, StakingPoolDoc, StakingEditDto, OwnedCollectionsDto, UserStakingSummaryDto, StakingCreatorDoc, StakingUserPoolNfts, StakingExploreDtoHydrated, OwnedServicesDto, FilterQueryDto, GlobalSearchResourcesPaginated, LendingNftAttributes, LendingTokenPriceDto, StellarAssetListItemDto, StellarLendingContextDto, StellarLendingLiveStateDto, StellarDetailedMarketDto, StellarHubListItemDto, StellarSpokeListItemDto, StellarReserveListItemDto, ReserveDto, TopHoldersDto, AssetDto, AssetPageDto, AssetMarketDto, HubDto, SpokeDto, AccountPositionsDto, StellarUserActivityItemDto, GovernanceProposalsPageDto, MarketGraphDto, SpokeGraphDto, StellarStatsHistoryDto, StellarPositionsPnlDto, StellarPositionsRankDto, UserHistoryDto, PnlByScopeDto, RevenueSeriesDto, FeeRevenueSeriesDto, ParticipantCountsDto, LiquidationsSeriesDto, LiquidationsLeaderboardDto, VolumeSeriesDto, ActiveUsersSeriesDto, HolderDistributionDto, RateSpreadSeriesDto, DefiLlamaDimensionsDto, NotificationPaginated, PushNotificationCountResponse, NotificationDoc, MobileDeviceDoc, MobileDeviceRegistrationDto, PushNotificationResponse, PushNotificationDoc, NotificationSuccessResponseDto, EventNotificationDto, CreatorMarketingNotificationDto, StellarChallengeResponseDto, Web2UserDoc, SuccessWithMessageDto, NativeWalletDto, SwitchWalletDto, Web2WalletDto, Web2UserShardsDto, NftActivityFilter, NftActivityPaginated, NftActivityDocHydrated, VolumeGraph, AnalyticsVolumeDto, UserAnalyticsDto, GlobalAnalyticsOverviewResponseDto, UserStatsDto, AirdropDtoHydrated, TransactionDetailed, TransactionProcessStatus, TransactionCostData, TransactionCreate, TransactionSendResult, ChatMessageDocHydrated, SendChatMessageDto, UserConversationPaginated, ChatMessagePaginated, GlobalConversationSummaryDto, UserBlockPaginated, WebSocketTokenDto, UserInfo, EventProfile, EventProfileCreateDto, EventProfileEditDto, EventProfileFilter, EventProfileQuery, EventRegistrationResponseDto, EventGuestRegistrationDto, EventTicketProfileDoc, EventTicketProfileCreateDto, EventTicketProfileEditDto, EventStageProfileDoc, EventStageProfileCreateDto, EventStageProfileEditDto, TicketPricesResponse, TicketCalculationRequestDto, DiscountCodeValidationResponse, EventInvitationDoc, EventInvitationCreateDto, EventInvitationFilter, EventInvitationQuery, EventInvitation, EventAcceptInvitation, EventClaimInvitationDto, EventVoucherFilter, EventVoucherQuery, EventQuestionDoc, EventQuestionCreateDto, EventQuestionEditDto, EventGuestFilter, EventGuestProfileQuery, EventGuestProfile, EventGuestExport, EventUserRole, EventUserRoleCreateDto, EventUserRoleEditDto, EventUserRoleDoc, BageQRData, TicketValidationResult, EventCheckInQR, EventVoucherDoc, EventVoucherCreateDto, EventVoucherEditDto, ManualCheckInDto, AnsweredQuestionWithDetails, EventGuestApproveDto, EventCountGroupedByCountry, EventReferralConfigDoc, EventReferralConfigCreateDto, EventReferralConfigEditDto, EventReferralConfigFilter, EventReferralConfigPaginated, EventReferralDoc, EventReferralCreateDto, EventReferralEditDto, EventReferralFilter, EventReferralPaginated, BlendUserPosition, SoroswapQuoteResponseDto, PerpOrderResponse, BarDto, SymbolInfoDto, PerpCoinExtended, PerpSpotCoinExtended, PerpCoinExtendedSlim, PerpLegalCheck, PerpSpotCoinExtendedSlim, L2BookPerpResponseSingle, TradesPerpResponseSingle, ActiveSpotAssetCtx, ActivePerpAssetCtx, PerpEvent } from '@xoxno/types';
|
|
1
|
+
import type { PublicOnly, RateType, LoginAccessDto, LoginRequestDto, UserNetworkInfoDto, UserTokenInventoryResponseDto, UserProfileDoc, UserProfileEditDto, UserProfileDto, UserSettingsDoc, NotificationPreferencesPostDto, SetEmailDto, SetPhoneDto, UserBillingDetails, VerifyEmailDto, TradesilvaniaSignature, SuccessDto, CreatorProfileDto, CreatorProfileDoc, CreatorProfileEditDto, CollectionStatsFilter, CollectionStatsPaginated, CheckLikeStatusResponseDto, UserFavoriteResponseDto, TokenDataDocHydrated, XoxnoInfo, XoxnoLiquidStatsDto, AnalyticsMarketplaceUniqueUsers, ProtocolAprType, ProviderDto, DelegationDataOutput, LendingMarketProfile, LendingMarketProfileFilter, LendingMarketProfileQuery, LendingGovernanceProposalFilter, LendingGovernanceProposalQuery, LendingGovernanceProposalDoc, LendingAccountProfile, LendingIndexesDto, LendingAccountPnl, LendingAccountSummary, LendingEModeCategoryProfile, LendingMarketAnalyticsGraph, LendingStatsHistory, LendingMarketAverageGraph, LendingPositionStatus, LendingOverallStats, DefillamaLendingExport, DefillamaLendingHistoryExport, DefillamaLendingRevenueExport, StellarLendingUserStatsExport, NftDocFilter, NftPaginated, LikeNftDto, InventorySummaryDtoHydrated, NftOfferPaginated, NftOfferDocFilter, NftOfferDocHydrated, ValueFp, TraitInfo, CollectionRanksDTO, ListingsResponseDto, NftDocHydrated, SignDataDto, SignWithdrawDto, SignAcceptGlobalOfferDto, SignMintDto, NftDocFull, CollectionProfileDoc, CollectionProfileEditDto, FloorPriceDto, PinnedCollectionDto, CollectionMintProfileDocHydrated, CollectionPinnedStatusDto, FollowCollectionDto, CollectionProfileFilter, CollectionProfilePaginated, CollectionMintProfileFilter, CollectionMintProfilePaginated, CollectionMintProfileDocWithStages, CollectionHoldersDto, CollectionHoldersExportDto, CollectionOwnerDto, CollectionStatsDocHydrated, CollectionOffersFilter, GlobalOfferPaginated, CreatorDetailsDto, ShareholderDto, StakingSummary, StakingPoolDoc, StakingEditDto, OwnedCollectionsDto, UserStakingSummaryDto, StakingCreatorDoc, StakingUserPoolNfts, StakingExploreDtoHydrated, OwnedServicesDto, FilterQueryDto, GlobalSearchResourcesPaginated, LendingNftAttributes, LendingTokenPriceDto, StellarAssetListItemDto, StellarLendingContextDto, StellarLendingLiveStateDto, StellarDetailedMarketDto, StellarHubListItemDto, StellarSpokeListItemDto, StellarReserveListItemDto, ReserveDto, TopHoldersDto, AssetDto, AssetPageDto, AssetMarketDto, HubDto, SpokeDto, AccountPositionsDto, StellarUserActivityItemDto, GovernanceProposalsPageDto, MarketGraphDto, SpokeGraphDto, StellarStatsHistoryDto, StellarPositionsPnlDto, StellarCampaignLeaderboardDto, StellarCampaignMeDto, StellarPositionsRankDto, UserHistoryDto, PnlByScopeDto, RevenueSeriesDto, FeeRevenueSeriesDto, ParticipantCountsDto, LiquidationsSeriesDto, LiquidationsLeaderboardDto, VolumeSeriesDto, ActiveUsersSeriesDto, HolderDistributionDto, RateSpreadSeriesDto, DefiLlamaDimensionsDto, NotificationPaginated, PushNotificationCountResponse, NotificationDoc, MobileDeviceDoc, MobileDeviceRegistrationDto, PushNotificationResponse, PushNotificationDoc, NotificationSuccessResponseDto, EventNotificationDto, CreatorMarketingNotificationDto, StellarChallengeResponseDto, Web2UserDoc, SuccessWithMessageDto, NativeWalletDto, SwitchWalletDto, Web2WalletDto, Web2UserShardsDto, NftActivityFilter, NftActivityPaginated, NftActivityDocHydrated, VolumeGraph, AnalyticsVolumeDto, UserAnalyticsDto, GlobalAnalyticsOverviewResponseDto, UserStatsDto, AirdropDtoHydrated, TransactionDetailed, TransactionProcessStatus, TransactionCostData, TransactionCreate, TransactionSendResult, ChatMessageDocHydrated, SendChatMessageDto, UserConversationPaginated, ChatMessagePaginated, GlobalConversationSummaryDto, UserBlockPaginated, WebSocketTokenDto, UserInfo, EventProfile, EventProfileCreateDto, EventProfileEditDto, EventProfileFilter, EventProfileQuery, EventRegistrationResponseDto, EventGuestRegistrationDto, EventTicketProfileDoc, EventTicketProfileCreateDto, EventTicketProfileEditDto, EventStageProfileDoc, EventStageProfileCreateDto, EventStageProfileEditDto, TicketPricesResponse, TicketCalculationRequestDto, DiscountCodeValidationResponse, EventInvitationDoc, EventInvitationCreateDto, EventInvitationFilter, EventInvitationQuery, EventInvitation, EventAcceptInvitation, EventClaimInvitationDto, EventVoucherFilter, EventVoucherQuery, EventQuestionDoc, EventQuestionCreateDto, EventQuestionEditDto, EventGuestFilter, EventGuestProfileQuery, EventGuestProfile, EventGuestExport, EventUserRole, EventUserRoleCreateDto, EventUserRoleEditDto, EventUserRoleDoc, BageQRData, TicketValidationResult, EventCheckInQR, EventVoucherDoc, EventVoucherCreateDto, EventVoucherEditDto, ManualCheckInDto, AnsweredQuestionWithDetails, EventGuestApproveDto, EventCountGroupedByCountry, EventReferralConfigDoc, EventReferralConfigCreateDto, EventReferralConfigEditDto, EventReferralConfigFilter, EventReferralConfigPaginated, EventReferralDoc, EventReferralCreateDto, EventReferralEditDto, EventReferralFilter, EventReferralPaginated, BlendUserPosition, SoroswapQuoteResponseDto, PerpOrderResponse, BarDto, SymbolInfoDto, PerpCoinExtended, PerpSpotCoinExtended, PerpCoinExtendedSlim, PerpLegalCheck, PerpSpotCoinExtendedSlim, L2BookPerpResponseSingle, TradesPerpResponseSingle, ActiveSpotAssetCtx, ActivePerpAssetCtx, PerpEvent } from '@xoxno/types';
|
|
2
2
|
import type { ActivityChain, TokenCategory, LendingPositionOrderByColumn, KustoOrderDirection, OfferType, StakingStatus, UserStatsOrderByColumn } from '@xoxno/types/enums';
|
|
3
3
|
export declare const endpoints: {
|
|
4
4
|
readonly "/liquid/xoxno/rate": {
|
|
@@ -1085,6 +1085,19 @@ export declare const endpoints: {
|
|
|
1085
1085
|
};
|
|
1086
1086
|
readonly output: StellarPositionsPnlDto;
|
|
1087
1087
|
};
|
|
1088
|
+
readonly "/stellar-lending/campaign/leaderboard": {
|
|
1089
|
+
readonly input: {
|
|
1090
|
+
skip?: number;
|
|
1091
|
+
top?: number;
|
|
1092
|
+
};
|
|
1093
|
+
readonly output: StellarCampaignLeaderboardDto;
|
|
1094
|
+
};
|
|
1095
|
+
readonly "/stellar-lending/campaign/me": {
|
|
1096
|
+
readonly input: {
|
|
1097
|
+
owner: string;
|
|
1098
|
+
};
|
|
1099
|
+
readonly output: StellarCampaignMeDto;
|
|
1100
|
+
};
|
|
1088
1101
|
readonly "/stellar-lending/positions": {
|
|
1089
1102
|
readonly input: {
|
|
1090
1103
|
token?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xoxno/sdk-js",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.210",
|
|
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.488"
|
|
118
118
|
},
|
|
119
119
|
"peerDependencies": {
|
|
120
120
|
"@stellar/stellar-sdk": ">=15.0.0 <17.0.0"
|