UNPKG

@hyperionxyz/sdk

Version:

This SDK allows you to interact with the Hyperion API. You can use it to request data, create pools/positions and more.

2 lines (1 loc) 19.4 kB
"use strict";var U=Object.defineProperty;var K=(n,t,e)=>t in n?U(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var d=(n,t,e)=>K(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("@aptos-labs/ts-sdk"),g=require("aptos-tool"),i=require("bignumber.js"),D=require("long"),h=require("@aptos-labs/script-composer-sdk");i.config({EXPONENTIAL_AT:1e9});const p=n=>D.fromInt(i(n).dp(0).toNumber()).toUnsigned().toInt(),O=1.0001,x=n=>Math.log(new i(n).toNumber())/Math.log(O),b=()=>Math.floor(100*365*24*60*60+Date.now()/1e3),v="-443636",L="443636";var H=(n=>(n[n["PER_0.01_SPACING_1"]=0]="PER_0.01_SPACING_1",n[n["PER_0.05_SPACING_5"]=1]="PER_0.05_SPACING_5",n[n["PER_0.3_SPACING_60"]=2]="PER_0.3_SPACING_60",n[n.PER_1_SPACING_200=3]="PER_1_SPACING_200",n[n["PER_0.1_SPACING_20"]=4]="PER_0.1_SPACING_20",n[n["PER_0.25_SPACING_50"]=5]="PER_0.25_SPACING_50",n))(H||{});const W=["1","5","30","100","10","25"],G=[1,10,60,200,20,50],z=[-443636,-443630,-443580,-443600,-443620,-443600],Y=[443636,443630,443580,443600,443620,443600],V=0x28f5c28f5c28f60,k=(n,t)=>{const e=G[t];return new i(n).div(e).dp(0,i.ROUND_HALF_UP).times(e).toString()},X=({price:n,feeTierIndex:t,decimalsRatio:e})=>{const o=x(new i(n).div(e));return isNaN(o)?null:i(o).lt(0)?i.max(k(o,t),k(v,t)):i.min(k(o,t),k(L,t))},J=({tick:n,decimalsRatio:t})=>new i(Math.pow(O,new i(n).dp(0).toNumber())).times(t).toString(),B=!1,A=n=>{if(!n.currencyA||!n.currencyB)throw new Error("currencyA and currencyB are required and can not be empty");if(!n.currencyA.startsWith("0x")||!n.currencyB.startsWith("0x"))throw new Error("currencyA and currencyB must be valid aptos account/token address")},f=n=>{if((!n.slippage||i(n.slippage).isNaN())&&(n.slippage=.5),i(n.slippage).lt(0))throw new Error("slippage must be greater than 0");if(i(n.slippage).gt(20))throw new Error("slippage must be less than 20")},w=(n,t)=>new i(n).minus(i(n).times(t).div(100)).dp(0).toNumber();i.config({EXPONENTIAL_AT:1e9});class Q{constructor(t){d(this,"_sdk");this._sdk=t}async fetchAllPools(){const t=await this._sdk.requestModule.get("/base/data/pools/stats");return(t==null?void 0:t.items)||[]}async fetchPoolById({poolId:t}){const e=await this._sdk.requestModule.get("/base/data/pools/stats",{poolId:t});return(e==null?void 0:e.items)||[]}async getPoolByTokenPairAndFeeTier({token1:t,token2:e,feeTier:o}){const s=await this._sdk.requestModule.get("/base/data/pools/by-token-pair",{token1:t,token2:e,feeTier:o});return(s==null?void 0:s.item)||s||{}}async createPoolTransactionPayload(t){A(t),f(t);const e=[t.currencyA,t.currencyB],o=[i(t.currencyAAmount).toNumber(),i(t.currencyBAmount).toNumber()],s=o.map(c=>w(c,t.slippage)),a=[i(t.feeTierIndex).toNumber(),B,p(t.tickLower),p(t.tickUpper),p(t.currentPriceTick),...o,...s,b()],r=[...a];return[r[5],r[6]]=[r[6],r[5]],[r[7],r[8]]=[r[8],r[7]],[r[2],r[3],r[4]]=[p(i(t.tickUpper).times(-1).toNumber()),p(i(t.tickLower).times(-1).toNumber()),p(i(t.currentPriceTick).times(-1).toNumber())],g.TokenPairs.TokenPairTypeCheck(e,[{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_entry`,typeArguments:[],functionArguments:[...e,...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_both_coin_entry`,typeArguments:[...e],functionArguments:[...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_coin_entry`,typeArguments:[e[0]],functionArguments:[e[1],...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_coin_entry`,typeArguments:[e[1]],functionArguments:[e[0],...r]}])}async fetchTicks({poolId:t}){const e=await this._sdk.requestModule.get(`/base/data/pools/${t}/liquidity-accumulation`);return(e==null?void 0:e.items)||[]}async estCurrencyAAmountFromB(t){const e={function:`${this._sdk.sdkOptions.contractAddress}::router_v3::optimal_liquidity_amounts_from_b`,typeArguments:[],functionArguments:[p(t.tickLower),p(t.tickUpper),p(t.currentPriceTick),t.currencyA,t.currencyB,t.feeTierIndex,t.currencyBAmount,0,0]};return console.log(e),await this._sdk.AptosClient.view({payload:e})}async estCurrencyBAmountFromA(t){const e={function:`${this._sdk.sdkOptions.contractAddress}::router_v3::optimal_liquidity_amounts_from_a`,typeArguments:[],functionArguments:[p(t.tickLower),p(t.tickUpper),p(t.currentPriceTick),t.currencyA,t.currencyB,t.feeTierIndex,t.currencyAAmount,0,0]};return await this._sdk.AptosClient.view({payload:e})}}i.config({EXPONENTIAL_AT:1e9});class Z{constructor(t){d(this,"_sdk");this._sdk=t}async fetchAllPositionsByAddress({address:t}){const e=await this._sdk.requestModule.get("/base/data/positions",{address:t});return Array.isArray(e)?e:(e==null?void 0:e.items)||[]}async fetchPositionById(t){const e=await this._sdk.requestModule.get("/base/data/liquidity/ownerships",{objectId:t.positionId,ownerAddress:t.address});return(e==null?void 0:e.items)||[]}async fetchFeeHistory(t){var o;const e=await this._sdk.requestModule.get("/base/data/rewards/claimed-fees",{objectId:t.positionId,ownerAddress:t.address});return(o=e==null?void 0:e.items)==null?void 0:o.filter(s=>!new i(s.amount).isEqualTo(0))}async addLiquidityTransactionPayload(t){A(t),f(t);const e=[t.currencyA,t.currencyB],o=[i(t.currencyAAmount).toNumber(),i(t.currencyBAmount).toNumber()],s=o.map(c=>w(c,t.slippage)),a=[i(t.feeTierIndex).toNumber(),B,...o,...s,b()],r=[...a];return[r[2],r[3]]=[r[3],r[2]],[r[4],r[5]]=[r[5],r[4]],g.TokenPairs.TokenPairTypeCheck(e,[{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_entry`,typeArguments:[],functionArguments:[t.positionId,...e,...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_both_coin_entry`,typeArguments:[...e],functionArguments:[t.positionId,...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_coin_entry`,typeArguments:[e[0]],functionArguments:[t.positionId,e[1],...a]},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_coin_entry`,typeArguments:[e[1]],functionArguments:[t.positionId,e[0],...r]}])}removeLiquidityTransactionPayload(t){if(console.log(t),A(t),f(t),!_.AccountAddress.isValid({input:t.recipient,strict:!0}).valid)throw new Error("Invalid recipient address");const e=[t.currencyA,t.currencyB],s=[i(t.currencyAAmount).toNumber(),i(t.currencyBAmount).toNumber()].map(r=>w(r,t.slippage)),a=[t.positionId,i(t.deltaLiquidity).dp(0).toNumber(),...s,t.recipient,b()];return g.TokenPairs.TokenPairTypeCheck(e,[{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_entry_v2`,typeArguments:[],functionArguments:a},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_both_coins_entry_v2`,typeArguments:[...e],functionArguments:a},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_coin_entry_v2`,typeArguments:[e[0]],functionArguments:a},{function:`${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_coin_entry_v2`,typeArguments:[e[1]],functionArguments:a}])}claimFeeTransactionPayload({positionId:t,recipient:e}){return{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::claim_fees`,typeArguments:[],functionArguments:[[t],e]}}claimRewardTransactionPayload({positionId:t,recipient:e}){return{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::claim_rewards`,typeArguments:[],functionArguments:[t,e]}}claimAllRewardsTransactionPayload({positionId:t,recipient:e}){return{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::claim_fees_and_rewards`,typeArguments:[],functionArguments:[[t],e]}}async fetchTokensAmountByPositionId({positionId:t}){const e={function:`${this._sdk.sdkOptions.contractAddress}::router_v3::get_amount_by_liquidity`,typeArguments:[],functionArguments:[t]};return await this._sdk.AptosClient.view({payload:e})}}function tt(n){return n.replace(/\/v1\/graphql\/?$/,"").replace(/\/$/,"")}class et{constructor(t){d(this,"_apiHost");this._apiHost=tt(t.indexerURL)}async get(t,e={}){const o=new URL(t,`${this._apiHost}/`);Object.entries(e).forEach(([a,r])=>{r!==void 0&&o.searchParams.set(a,r.toString())});const s=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`Hyperion API request failed: ${s.status} ${s.statusText}`);return await s.json()}get indexerURL(){return this._apiHost}}i.config({EXPONENTIAL_AT:1e9});class nt{constructor(t){d(this,"_sdk");this._sdk=t}fetchRewardsPayload({positionId:t}){return{function:`${this._sdk.sdkOptions.contractAddress}::pool_v3::get_pending_rewards`,typeArguments:[],functionArguments:[t]}}async fetchRewardHistory(t){var o;const e=await this._sdk.requestModule.get("/base/data/rewards/claimed-farms",{objectId:t.positionId,ownerAddress:t.address});return(o=e==null?void 0:e.items)==null?void 0:o.filter(s=>!new i(s.amount).isEqualTo(0))}claimRewardPayload({positionId:t,recipient:e}){return{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::claim_rewards`,typeArguments:[],functionArguments:[t,e]}}}const T="0xc3290d98d622b9ab354277e0b1c5e66552f9784d2d4fb473ff321b9338485117",ot="hyperion-aggregator";async function C(n,t){let e=await P(n,"0x1::fungible_asset::Metadata",t);return(await n.addBatchedCalls({function:"0x1::fungible_asset::zero",typeArguments:["0x1::fungible_asset::Metadata"],functionArguments:[e]}))[0]}async function rt(n,t,e){return(await n.addBatchedCalls({function:"0x1::fungible_asset::extract",typeArguments:[],functionArguments:[t.borrowMut(),e]}))[0]}async function E(n,t,e){await n.addBatchedCalls({function:"0x1::fungible_asset::merge",typeArguments:[],functionArguments:[t.borrowMut(),e]})}async function st(n,t,e){return(await n.addBatchedCalls({function:"0x1::primary_fungible_store::withdraw",typeArguments:["0x1::fungible_asset::Metadata"],functionArguments:[h.CallArgument.newSigner(0),t,e]}))[0]}async function m(n,t,e){await n.addBatchedCalls({function:"0x1::primary_fungible_store::deposit",typeArguments:[],functionArguments:[t,e]})}async function I(n,t){return(await n.addBatchedCalls({function:"0x1::fungible_asset::amount",typeArguments:[],functionArguments:[t.borrow()]}))[0]}async function P(n,t,e){return(await n.addBatchedCalls({function:"0x1::object::address_to_object",typeArguments:[t],functionArguments:[e]}))[0]}async function at(n,t,e,o){return(await n.addBatchedCalls({function:`${T}::tool::split_fa_proportionlly`,typeArguments:[],functionArguments:[t.borrowMut(),e,o*100]}))[0]}async function $(n,t,e){await n.addBatchedCalls({function:`${T}::tool::fa_amount_check`,typeArguments:[],functionArguments:[t.borrow(),e]})}async function it(n,t,e,o){await n.addBatchedCalls({function:`${T}::tool::deposit_fa_exact`,typeArguments:[],functionArguments:[t,e.borrowMut(),o]})}async function ct(n){return(await n.addBatchedCalls({function:`${T}::tool::get_signer_address`,typeArguments:[],functionArguments:[h.CallArgument.newSigner(0)]}))[0]}const ut="0x4bf51972879e3b95c4781a5cdcb9e1ee24ef483e7d22f2d903626f126df62bd1";async function dt(n,t,e,o){return(await n.addBatchedCalls({function:`${ut}::router::swap`,typeArguments:[],functionArguments:[t,0,e,o]}))[0]}async function pt(n,t,e,o,s,a,r,c,u){let l=await I(n,a),y=await n.addBatchedCalls({function:`${c.contractAddress}::partnership::swap`,typeArguments:[],functionArguments:[e,o,s,l,a,r,u||ot]});return await m(n,t,y[1]),y[2]}const q="0x7730cd28ee1cdc9e999336cbc430f99e7c44397c0aa77516f6f23a78559bb5";async function lt(n,t,e,o){let s=await P(n,"0x1::fungible_asset::Metadata",o);return(await n.addBatchedCalls({function:`${q}::pool::swap_exact_in_stable`,typeArguments:[],functionArguments:[h.CallArgument.newSigner(0),t,e,s]}))[0]}async function yt(n,t,e,o){let s=await P(n,"0x1::fungible_asset::Metadata",o);return(await n.addBatchedCalls({function:`${q}::pool::swap_exact_in_metastable`,typeArguments:[],functionArguments:[h.CallArgument.newSigner(0),t,e,s]}))[0]}async function _t(n,t,e,o){return(await n.addBatchedCalls({function:`${q}::pool::swap_exact_in_weighted`,typeArguments:[],functionArguments:[h.CallArgument.newSigner(0),t,e,o]}))[0]}async function mt(n,t,e,o,s,a,r,c){return(await n.addBatchedCalls({function:`${T}::tool::swap_in_emoji`,typeArguments:[t,e],functionArguments:[h.CallArgument.newSigner(0),s,a,r,c,o]}))[1]}async function At(n,t,e,o,s,a){let r;return r=await pt(n,o.copy(),t.poolId,t.a2b,!0,e,t.sqrtPriceLimit,s,a),r}async function ft(n,t,e){let o;if(t.poolType=="stable")o=!0;else if(t.poolType=="unstable")o=!1;else throw"pool type mismatch";return await dt(n,e,t.toToken.tokenType,o)}async function wt(n,t,e){let o;if(t.poolType=="stable")o=await lt(n,t.poolId,e,t.toToken.tokenType);else if(t.poolType=="weighted")o=await _t(n,t.poolId,e,t.toToken.tokenType);else if(t.poolType=="meta")o=await yt(n,t.poolId,e,t.toToken.tokenType);else throw"type mismatch";return o}async function ht(n,t,e){return await mt(n,t.firstType,t.secondType,e,t.poolId,t.isSell,t.integrator,t.integratorFee)}async function kt(n,t,e,o,s,a){let r;if(t.dexName=="Hyperion")r=await At(n,t,e,o.copy(),s,a);else if(t.dexName=="Cellana")r=await ft(n,t,e);else if(t.dexName=="ThalaSwapV2")r=await wt(n,t,e);else if(t.dexName=="EmojiCoin")r=await ht(n,t,e);else throw"Dex Not Supported";return r}async function M(n,t,e,o,s,a){for(const r of t){let c;c=await C(n,r.toToken.tokenType);let u=await kt(n,r,e,o.copy(),s,a);await E(n,c,u),e=c}return e}class gt{constructor(t){d(this,"_sdk");this._sdk=t}async fetchAggregateSwapRoute(t){const e=new URLSearchParams({slippage:t.slippage.toString(),amount:t.amount.toString(),from:t.from,input:t.input,to:t.to}),o=await fetch(`${this._sdk.sdkOptions.hyperionAPIHost}/base/aggregator/getAggRoute?${e.toString()}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch aggregate swap route: ${o.statusText}`);return await o.json()}async generateAggregateSwapTransactionScript(t){const{builder:e}=t;let o=await ct(e),s;t.exactIn?s=Number(t.fromTokenAmount):s=Number(t.maxFromTokenAmount);let a,r,c=await P(e,"0x1::fungible_asset::Metadata",t.fromToken.address);r=await st(e,c,s),a=await I(e,r);const u=await C(e,t.toToken.address);for(const l of t.quotes.route){let y;y=await rt(e,r,l.amountIn);let S=await M(e,l.routeTaken,y,o.copy(),this._sdk.sdkOptions,t.partnershipId);await E(e,u,S)}if(t.exactIn)await $(e,u,Number(t.minToTokenAmount)),await m(e,o.copy(),u),await m(e,o.copy(),r);else{let l=0;await $(e,u,Number(t.toTokenAmount)),await it(e,o.copy(),u,Number(t.toTokenAmount));let y;y=await C(e,t.fromToken.address),a=await I(e,u);for(const S of t.quotes.refundRoute){let R,N=S.percentage;l+=N,l==100&&(N=100),R=await at(e,u,a.copy(),N);let F=await M(e,S.routeTaken,R,o.copy(),this._sdk.sdkOptions,t.partnershipId);await E(e,y,F)}if(await m(e,o.copy(),u),await m(e,o.copy(),r),await m(e,o.copy(),y),l!=100)throw"not 100% refund"}}}class Tt{constructor(t){d(this,"_sdk");d(this,"_aggregateSwapHelper");this._sdk=t,this._aggregateSwapHelper=new gt(t)}swapTransactionPayload(t){A(t),f(t);const e=[t.currencyA,t.currencyB],o=[t.currencyAAmount,t.currencyBAmount],s=[o[0],w(o[1],t.slippage)],a=[...e];a.forEach((c,u)=>{if((c==null?void 0:c.indexOf("::"))>-1){const l=new g.Token({coinType:c,name:"token",symbol:"token",decimals:5,assetType:""});l.faTypeCalculate(),l.faType&&(a[u]=l.faType)}});const r=[t.poolRoute,...a,...s,t.recipient];return g.TokenPairs.TokenPairTypeCheck(e,[{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::swap_batch`,typeArguments:[],functionArguments:[...r]},{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::swap_batch_coin_entry`,typeArguments:[e[0]],functionArguments:[...r]},{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::swap_batch_coin_entry`,typeArguments:[e[0]],functionArguments:[...r]},{function:`${this._sdk.sdkOptions.contractAddress}::router_v3::swap_batch`,typeArguments:[],functionArguments:[...r]}])}swapWithPartnershipTransactionPayload(t){if(A(t),f(t),!t.partnership||t.partnership.length===0)throw new Error("partnership is required");const e=[t.currencyA,t.currencyB],o=[t.currencyAAmount,t.currencyBAmount],s=[o[0],w(o[1],t.slippage)];return{function:`${this._sdk.sdkOptions.contractAddress}::partnership::swap_batch_directly_deposit`,typeArguments:[],functionArguments:[t.poolRoute,e[0],e[1],...s,t.partnership]}}async estFromAmount(t){const e=new URLSearchParams({amount:t.amount.toString(),from:t.from,to:t.to,safeMode:t.safeMode?"true":"false",flag:"out"});return await(await fetch(`${this._sdk.sdkOptions.hyperionAPIHost}/base/rate/getSwapInfo?${e.toString()}`,{method:"GET",headers:{"Content-Type":"application/json"}})).json()}async estToAmount(t){const e=new URLSearchParams({amount:t.amount.toString(),from:t.from,to:t.to,safeMode:t.safeMode?"true":"false",flag:"in"});return await(await fetch(`${this._sdk.sdkOptions.hyperionAPIHost}/base/rate/getSwapInfo?${e.toString()}`,{method:"GET",headers:{"Content-Type":"application/json"}})).json()}async estAmountByAggregateSwap(t){if(this._sdk.sdkOptions.network!==_.Network.MAINNET)throw new Error("Aggregate swap is only supported on MAINNET");return await this._aggregateSwapHelper.fetchAggregateSwapRoute(t)}async generateAggregateSwapTransactionScript(t){if(this._sdk.sdkOptions.network!==_.Network.MAINNET)throw new Error("Aggregate swap is only supported on MAINNET");return await this._aggregateSwapHelper.generateAggregateSwapTransactionScript(t)}}const St={network:_.Network.TESTNET,contractAddress:"0x69faed94da99abb7316cb3ec2eeaa1b961a47349fad8c584f67a930b0d14fec7",hyperionFullNodeIndexerURL:"https://api-testnet.hyperion.xyz",hyperionAPIHost:"https://api-testnet.hyperion.xyz",APTOS_API_KEY:""},bt={network:_.Network.MAINNET,contractAddress:"0x8b4a2c4bb53857c718a04c020b98f8c2e1f99a68b0f57389a8bf5434cd22e05c",hyperionFullNodeIndexerURL:"https://api.hyperion.xyz",hyperionAPIHost:"https://api.hyperion.xyz",APTOS_API_KEY:""};function Pt(n){const{network:t,APTOS_API_KEY:e}=n;return new j({...t==_.Network.MAINNET?bt:St,APTOS_API_KEY:e})}class j{constructor(t){d(this,"_options");d(this,"_requestModule");d(this,"_pool");d(this,"_position");d(this,"_swap");d(this,"_reward");d(this,"_aptosClient");this._options=t,this._requestModule=new et({indexerURL:this._options.hyperionFullNodeIndexerURL}),this._pool=new Q(this),this._position=new Z(this),this._swap=new Tt(this),this._reward=new nt(this);const e={API_KEY:this._options.APTOS_API_KEY};this._aptosClient=new _.Aptos(new _.AptosConfig({network:this._options.network,clientConfig:e}))}get Pool(){return this._pool}get Position(){return this._position}get Swap(){return this._swap}get Reward(){return this._reward}get AptosClient(){return this._aptosClient}get sdkOptions(){return this._options}get requestModule(){return this._requestModule}}exports.BASE=O;exports.FeeTierIndex=H;exports.FeeTierItems=W;exports.FeeTierStep=G;exports.HIGHEST_TICK=L;exports.HighestTickByStep=Y;exports.HyperionSDK=j;exports.LOWEST_TICK=v;exports.LowestTickByStep=z;exports.POOL_STABLE_TYPE=B;exports.currencyCheck=A;exports.initHyperionSDK=Pt;exports.logBase=x;exports.poolDeadline=b;exports.priceToTick=X;exports.roundTickBySpacing=k;exports.slippageCalculator=w;exports.slippageCheck=f;exports.tickComplement=p;exports.tickToPrice=J;exports.u64Max=V;