@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.
1,288 lines (1,287 loc) • 34.2 kB
JavaScript
var W = Object.defineProperty;
var Q = (n, t, e) => t in n ? W(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
var u = (n, t, e) => Q(n, typeof t != "symbol" ? t + "" : t, e);
import { AccountAddress as z, Network as f, Aptos as Y, AptosConfig as V } from "@aptos-labs/ts-sdk";
import { TokenPairs as I, Token as X } from "aptos-tool";
import a from "bignumber.js";
import O, { gql as m } from "graphql-request";
import J from "long";
import { CallArgument as A } from "@aptos-labs/script-composer-sdk";
const B = `
assetType
bridge
coinMarketcapId
coinType
coingeckoId
decimals
faType
hyperfluidSymbol
logoUrl
name
symbol
isBanned
websiteUrl`, E = `
currentTick
feeRate
feeTier
poolId
senderAddress
sqrtPrice
token1
token2
token1Info {
${B}
}
token2Info {
${B}
}
`, j = `
id
dailyVolumeUSD
feesUSD
tvlUSD
feeAPR
farmAPR
pool {
${E}
}
`, Z = m`
query queryAllPools {
api {
getPoolStat {
${j}
}
}
}
`, tt = m`
query queryPoolById($poolId: String = "") {
api {
getPoolStat(poolId: $poolId) {
${j}
}
}
}
`, et = m`
query queryTickChart($poolId: String = "") {
api {
getLiquidityAccumulation(poolId: $poolId) {
price0
price1
tick
totalAmount
}
}
}
`, F = `
amount
amountUSD
token
`, v = `
claimed {
${F}
}
`, M = `
unclaimed {
${F}
}
`, nt = m`
query queryAllPositionByAddress($address: String = "") {
api {
getPositionStatsByAddress(address: $address) {
isActive
value
farm {
${v}
${M}
}
fees {
${v}
${M}
}
position {
objectId
poolId
tickLower
tickUpper
createdAt
pool {
${E}
}
}
}
}
}
`, ot = m`
query queryPoolInfoByObjectId($ownerAddress: String = "", $objectId: String = "") {
objectOwnership(
where: {
ownerAddress: { _eq: $ownerAddress }
isDelete: { _eq: false }
objectId: { _eq: $objectId }
}
) {
objectId
poolId
txnTimestamp
currentAmount
position {
tickLower
tickUpper
}
pool {
${E}
}
}
}
`, rt = m`
query queryPoolByTokenPair(
$token1: String = ""
$token2: String = ""
$feeTier: Float = 1.5
) {
api {
getPoolByTokenPair(feeTier: $feeTier, token1: $token1, token2: $token2) {
currentTick
token1
token2
poolId
}
}
}
`;
a.config({ EXPONENTIAL_AT: 1e9 });
const l = (n) => J.fromInt(a(n).dp(0).toNumber()).toUnsigned().toInt(), G = 1.0001, st = (n) => Math.log(new a(n).toNumber()) / Math.log(G), q = () => Math.floor(100 * 365 * 24 * 60 * 60 + Date.now() / 1e3), it = "-443636", at = "443636";
var ct = /* @__PURE__ */ ((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))(ct || {});
const Wt = ["1", "5", "30", "100", "10", "25"], ut = [1, 10, 60, 200, 20, 50], Qt = [
-443636,
-443630,
-443580,
-443600,
-443620,
-443600
], zt = [
443636,
443630,
443580,
443600,
443620,
443600
], Yt = 184467440737095520, b = (n, t) => {
const e = ut[t];
return new a(n).div(e).dp(0, a.ROUND_HALF_UP).times(e).toString();
}, Vt = ({
price: n,
feeTierIndex: t,
decimalsRatio: e
}) => {
const o = st(new a(n).div(e));
return isNaN(o) ? null : a(o).lt(0) ? a.max(
b(o, t),
b(it, t)
) : a.min(
b(o, t),
b(at, t)
);
}, Xt = ({
tick: n,
decimalsRatio: t
}) => new a(Math.pow(G, new a(n).dp(0).toNumber())).times(t).toString(), H = !1, w = (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"
);
}, h = (n) => {
if ((!n.slippage || a(n.slippage).isNaN()) && (n.slippage = 0.5), a(n.slippage).lt(0))
throw new Error("slippage must be greater than 0");
if (a(n.slippage).gt(20))
throw new Error("slippage must be less than 20");
}, k = (n, t) => new a(n).minus(a(n).times(t).div(100)).dp(0).toNumber();
a.config({ EXPONENTIAL_AT: 1e9 });
class dt {
constructor(t) {
u(this, "_sdk");
this._sdk = t;
}
async fetchAllPools() {
var e;
const t = await this._sdk.requestModule.queryIndexer({
document: Z
});
return ((e = t == null ? void 0 : t.api) == null ? void 0 : e.getPoolStat) || [];
}
async fetchPoolById({ poolId: t }) {
var o;
const e = await this._sdk.requestModule.queryIndexer({
document: tt,
variables: {
poolId: t
}
});
return ((o = e == null ? void 0 : e.api) == null ? void 0 : o.getPoolStat) || [];
}
async getPoolByTokenPairAndFeeTier({
token1: t,
token2: e,
feeTier: o
}) {
const s = await this._sdk.requestModule.queryIndexer({
document: rt,
variables: {
token1: t,
token2: e,
feeTier: o
}
});
return (s == null ? void 0 : s.api.getPoolByTokenPair) || {};
}
// TODO: fetch pool by tokenPair Addresses and fee rate
/**
* Creates a liquidity pool
*
* This method is used to initialize a liquidity pool.
*/
async createPoolTransactionPayload(t) {
w(t), h(t);
const e = [t.currencyA, t.currencyB], o = [
a(t.currencyAAmount).toNumber(),
a(t.currencyBAmount).toNumber()
], s = o.map(
(c) => k(c, t.slippage)
), i = [
a(t.feeTierIndex).toNumber(),
H,
l(t.tickLower),
l(t.tickUpper),
l(t.currentPriceTick),
...o,
...s,
q()
], r = [...i];
return [r[5], r[6]] = [r[6], r[5]], [r[7], r[8]] = [r[8], r[7]], [r[2], r[3], r[4]] = [
l(a(t.tickUpper).times(-1).toNumber()),
l(a(t.tickLower).times(-1).toNumber()),
l(a(t.currentPriceTick).times(-1).toNumber())
], I.TokenPairTypeCheck(e, [
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_entry`,
typeArguments: [],
functionArguments: [...e, ...i]
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_both_coin_entry`,
typeArguments: [...e],
functionArguments: [...i]
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_coin_entry`,
typeArguments: [e[0]],
functionArguments: [e[1], ...i]
},
// fa & coin
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::create_liquidity_coin_entry`,
// TokenB
typeArguments: [e[1]],
// TokenA
// [AmountB, AmountA]
// [SlippageB, SlippageA]
functionArguments: [e[0], ...r]
}
]);
}
async fetchTicks({ poolId: t }) {
var o;
const e = await this._sdk.requestModule.queryIndexer({
document: et,
variables: {
poolId: t
}
});
return ((o = e == null ? void 0 : e.api) == null ? void 0 : o.getLiquidityAccumulation) || [];
}
// TODO: return data type in docs
// [number_a, number_b]
async estCurrencyAAmountFromB(t) {
const e = {
function: `${this._sdk.sdkOptions.contractAddress}::router_v3::optimal_liquidity_amounts_from_b`,
typeArguments: [],
functionArguments: [
l(t.tickLower),
l(t.tickUpper),
l(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: [
// fixed tick order
l(t.tickLower),
l(t.tickUpper),
l(t.currentPriceTick),
t.currencyA,
t.currencyB,
t.feeTierIndex,
t.currencyAAmount,
0,
0
]
};
return await this._sdk.AptosClient.view({ payload: e });
}
}
const D = `
amount
objectId
poolId
senderAddress
ownerAddress
token
type
`, pt = m`
query queryClaimedFee($objectId: String = "", $ownerAddress:String = "") {
rewardStatement(where: { objectId: { _eq: $objectId }, ownerAddress: {_eq: $ownerAddress}, type: { _eq: ${0} } }) {
${D}
}
}
`, lt = m`
query queryClaimedRewards($objectId: String = "", $ownerAddress:String = "") {
rewardStatement(where: { objectId: { _eq: $objectId }, ownerAddress: {_eq: $ownerAddress}, type: { _eq: ${1} } }) {
${D}
}
}
`;
a.config({ EXPONENTIAL_AT: 1e9 });
class yt {
constructor(t) {
u(this, "_sdk");
this._sdk = t;
}
async fetchAllPositionsByAddress({ address: t }) {
var o;
const e = await this._sdk.requestModule.queryIndexer({
document: nt,
variables: {
address: t
}
});
return ((o = e == null ? void 0 : e.api) == null ? void 0 : o.getPositionStatsByAddress) || [];
}
async fetchPositionById(t) {
const e = await this._sdk.requestModule.queryIndexer({
document: ot,
variables: {
objectId: t.positionId,
ownerAddress: t.address
}
});
return (e == null ? void 0 : e.objectOwnership) || [];
}
/**
* Fetch the history of Fee Reward claim
*
* @param args
* @returns
*/
async fetchFeeHistory(t) {
var o;
return (o = (await this._sdk.requestModule.queryIndexer({
document: pt,
variables: {
objectId: t.positionId,
ownerAddress: t.address
}
})).rewardStatement) == null ? void 0 : o.filter((s) => !new a(s.amount).isEqualTo(0));
}
// async fetchFeePayload({ positionId }: { positionId: string }) {
// return {
// function: `${this._sdk.sdkOptions.contractAddress}::pool_v3::get_pending_fees`,
// typeArguments: [],
// functionArguments: [positionId],
// };
// }
/**
* Adds liquidity to a liquidity pool
*
* This method is used to add liquidity to a liquidity pool.
*/
async addLiquidityTransactionPayload(t) {
w(t), h(t);
const e = [t.currencyA, t.currencyB], o = [
a(t.currencyAAmount).toNumber(),
a(t.currencyBAmount).toNumber()
], s = o.map(
(c) => k(c, t.slippage)
), i = [
a(t.feeTierIndex).toNumber(),
H,
...o,
...s,
q()
], r = [...i];
return [r[2], r[3]] = [r[3], r[2]], [r[4], r[5]] = [r[5], r[4]], I.TokenPairTypeCheck(e, [
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_entry`,
typeArguments: [],
functionArguments: [t.positionId, ...e, ...i]
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_both_coin_entry`,
typeArguments: [...e],
functionArguments: [t.positionId, ...i]
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_coin_entry`,
typeArguments: [e[0]],
functionArguments: [t.positionId, e[1], ...i]
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::add_liquidity_coin_entry`,
typeArguments: [e[1]],
functionArguments: [
t.positionId,
e[0],
...r
]
}
]);
}
/**
* Removes liquidity from a liquidity pool
*
* This method is used to remove liquidity from a liquidity pool.
*/
removeLiquidityTransactionPayload(t) {
if (console.log(t), w(t), h(t), !z.isValid({ input: t.recipient, strict: !0 }).valid)
throw new Error("Invalid recipient address");
const e = [t.currencyA, t.currencyB], s = [
a(t.currencyAAmount).toNumber(),
a(t.currencyBAmount).toNumber()
].map(
(r) => k(r, t.slippage)
), i = [
t.positionId,
a(t.deltaLiquidity).dp(0).toNumber(),
...s,
t.recipient,
q()
];
return I.TokenPairTypeCheck(e, [
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_entry_v2`,
typeArguments: [],
functionArguments: i
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_both_coins_entry_v2`,
typeArguments: [...e],
functionArguments: i
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_coin_entry_v2`,
typeArguments: [e[0]],
functionArguments: i
},
{
function: `${this._sdk.sdkOptions.contractAddress}::router_adapter::remove_liquidity_coin_entry_v2`,
typeArguments: [e[1]],
functionArguments: i
}
]);
}
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]
};
}
/**
*
* @param positionId
*
* @returns [currencyAAmount, currencyBAmount]
*/
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
});
}
}
class mt {
constructor(t) {
u(this, "_indexerURL");
u(this, "_officialIndexerURL");
this._indexerURL = t.indexerURL, this._officialIndexerURL = t.officialIndexerURL;
}
async queryIndexer({
document: t,
variables: e = {}
}) {
return await O({
url: this._indexerURL,
document: t,
variables: e
});
}
async queryOfficialIndexer({
document: t,
variables: e = {}
}) {
return await O({
url: this._officialIndexerURL,
document: t,
variables: e
});
}
get indexerURL() {
return this._indexerURL;
}
}
a.config({ EXPONENTIAL_AT: 1e9 });
class _t {
constructor(t) {
u(this, "_sdk");
this._sdk = t;
}
fetchRewardsPayload({ positionId: t }) {
return {
function: `${this._sdk.sdkOptions.contractAddress}::pool_v3::get_pending_rewards`,
typeArguments: [],
functionArguments: [t]
};
}
/**
* Fetch the history of Fee Farm claim
*
* @param args
* @returns
*/
async fetchRewardHistory(t) {
var o;
return (o = (await this._sdk.requestModule.queryIndexer({
document: lt,
variables: {
objectId: t.positionId,
ownerAddress: t.address
}
})).rewardStatement) == null ? void 0 : o.filter((s) => !new a(s.amount).isEqualTo(0));
}
claimRewardPayload({
positionId: t,
recipient: e
}) {
return {
function: `${this._sdk.sdkOptions.contractAddress}::router_v3::claim_rewards`,
typeArguments: [],
functionArguments: [t, e]
};
}
}
const g = "0xc3290d98d622b9ab354277e0b1c5e66552f9784d2d4fb473ff321b9338485117", At = "hyperion-aggregator";
async function $(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 ft(n, t, e) {
return (await n.addBatchedCalls({
function: "0x1::fungible_asset::extract",
typeArguments: [],
functionArguments: [t.borrowMut(), e]
}))[0];
}
async function N(n, t, e) {
await n.addBatchedCalls({
function: "0x1::fungible_asset::merge",
typeArguments: [],
functionArguments: [t.borrowMut(), e]
});
}
async function wt(n, t, e) {
return (await n.addBatchedCalls({
function: "0x1::primary_fungible_store::withdraw",
typeArguments: ["0x1::fungible_asset::Metadata"],
functionArguments: [A.newSigner(0), t, e]
}))[0];
}
async function _(n, t, e) {
await n.addBatchedCalls({
function: "0x1::primary_fungible_store::deposit",
typeArguments: [],
functionArguments: [t, e]
});
}
async function C(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 ht(n, t, e, o) {
return (await n.addBatchedCalls({
function: `${g}::tool::split_fa_proportionlly`,
typeArguments: [],
functionArguments: [t.borrowMut(), e, o * 100]
}))[0];
}
async function L(n, t, e) {
await n.addBatchedCalls({
function: `${g}::tool::fa_amount_check`,
typeArguments: [],
functionArguments: [t.borrow(), e]
});
}
async function kt(n, t, e, o) {
await n.addBatchedCalls({
function: `${g}::tool::deposit_fa_exact`,
typeArguments: [],
functionArguments: [t, e.borrowMut(), o]
});
}
async function gt(n) {
return (await n.addBatchedCalls({
function: `${g}::tool::get_signer_address`,
typeArguments: [],
functionArguments: [A.newSigner(0)]
}))[0];
}
const Tt = "0x4bf51972879e3b95c4781a5cdcb9e1ee24ef483e7d22f2d903626f126df62bd1";
async function bt(n, t, e, o) {
return (await n.addBatchedCalls({
function: `${Tt}::router::swap`,
typeArguments: [],
functionArguments: [t, 0, e, o]
}))[0];
}
async function It(n, t, e, o, s, i, r, c, d) {
let p = await C(n, i), y = await n.addBatchedCalls({
function: `${c.contractAddress}::partnership::swap`,
typeArguments: [],
functionArguments: [
e,
o,
s,
p,
i,
r,
d || At
]
});
return await _(n, t, y[1]), y[2];
}
const x = "0x7730cd28ee1cdc9e999336cbc430f99e7c44397c0aa77516f6f23a78559bb5";
async function Pt(n, t, e, o) {
let s = await P(
n,
"0x1::fungible_asset::Metadata",
o
);
return (await n.addBatchedCalls({
function: `${x}::pool::swap_exact_in_stable`,
typeArguments: [],
functionArguments: [A.newSigner(0), t, e, s]
}))[0];
}
async function St(n, t, e, o) {
let s = await P(
n,
"0x1::fungible_asset::Metadata",
o
);
return (await n.addBatchedCalls({
function: `${x}::pool::swap_exact_in_metastable`,
typeArguments: [],
functionArguments: [A.newSigner(0), t, e, s]
}))[0];
}
async function qt(n, t, e, o) {
return (await n.addBatchedCalls({
function: `${x}::pool::swap_exact_in_weighted`,
typeArguments: [],
functionArguments: [A.newSigner(0), t, e, o]
}))[0];
}
async function $t(n, t, e, o, s, i, r, c) {
return (await n.addBatchedCalls({
function: `${g}::tool::swap_in_emoji`,
typeArguments: [t, e],
functionArguments: [
A.newSigner(0),
s,
i,
r,
c,
o
]
}))[1];
}
async function Nt(n, t, e, o, s, i) {
let r;
return r = await It(
n,
o.copy(),
t.poolId,
t.a2b,
!0,
e,
t.sqrtPriceLimit,
s,
i
), r;
}
async function Ct(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 bt(
n,
e,
t.toToken.tokenType,
o
);
}
async function Et(n, t, e) {
let o;
if (t.poolType == "stable")
o = await Pt(
n,
t.poolId,
e,
t.toToken.tokenType
);
else if (t.poolType == "weighted")
o = await qt(
n,
t.poolId,
e,
t.toToken.tokenType
);
else if (t.poolType == "meta")
o = await St(
n,
t.poolId,
e,
t.toToken.tokenType
);
else
throw "type mismatch";
return o;
}
async function xt(n, t, e) {
return await $t(
n,
t.firstType,
t.secondType,
e,
t.poolId,
t.isSell,
t.integrator,
t.integratorFee
);
}
async function Rt(n, t, e, o, s, i) {
let r;
if (t.dexName == "Hyperion")
r = await Nt(
n,
t,
e,
o.copy(),
s,
i
);
else if (t.dexName == "Cellana")
r = await Ct(n, t, e);
else if (t.dexName == "ThalaSwapV2")
r = await Et(n, t, e);
else if (t.dexName == "EmojiCoin")
r = await xt(n, t, e);
else
throw "Dex Not Supported";
return r;
}
async function U(n, t, e, o, s, i) {
for (const r of t) {
let c;
c = await $(n, r.toToken.tokenType);
let d = await Rt(
n,
r,
e,
o.copy(),
s,
i
);
await N(n, c, d), e = c;
}
return e;
}
class Ot {
constructor(t) {
u(this, "_sdk");
this._sdk = t;
}
/**
* Fetch the aggregate swap route
* @param args AggregateSwapRouteArgs
* @param args.amount The amount of the input token
* @param args.from The address of the input token
* @param args.input The address of the input token, either equals to args.from or args.to
* @param args.slippage The slippage tolerance
* @param args.to The address of the output token
* @returns
*/
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();
}
/**
* Generate the aggregate swap transaction script
* @param args AggregateSwapInfoResult & { builder: AptosScriptComposer; partnershipId?: string }
* @param args.builder The builder of the transaction
* @param args.partnershipId The partnership ID, only work on MAINNET
* @returns The transaction script
*/
async generateAggregateSwapTransactionScript(t) {
const { builder: e } = t;
let o = await gt(e), s;
t.exactIn ? s = Number(t.fromTokenAmount) : s = Number(t.maxFromTokenAmount);
let i, r, c = await P(
e,
"0x1::fungible_asset::Metadata",
t.fromToken.address
);
r = await wt(e, c, s), i = await C(e, r);
const d = await $(e, t.toToken.address);
for (const p of t.quotes.route) {
let y;
y = await ft(e, r, p.amountIn);
let T = await U(
e,
p.routeTaken,
y,
o.copy(),
this._sdk.sdkOptions,
t.partnershipId
);
await N(e, d, T);
}
if (t.exactIn)
await L(e, d, Number(t.minToTokenAmount)), await _(e, o.copy(), d), await _(e, o.copy(), r);
else {
let p = 0;
await L(e, d, Number(t.toTokenAmount)), await kt(
e,
o.copy(),
d,
Number(t.toTokenAmount)
);
let y;
y = await $(e, t.fromToken.address), i = await C(e, d);
for (const T of t.quotes.refundRoute) {
let R, S = T.percentage;
p += S, p == 100 && (S = 100), R = await ht(
e,
d,
i.copy(),
S
);
let K = await U(
e,
T.routeTaken,
R,
o.copy(),
this._sdk.sdkOptions,
t.partnershipId
);
await N(e, y, K);
}
if (await _(e, o.copy(), d), await _(e, o.copy(), r), await _(e, o.copy(), y), p != 100) throw "not 100% refund";
}
}
}
class Bt {
constructor(t) {
u(this, "_sdk");
u(this, "_aggregateSwapHelper");
this._sdk = t, this._aggregateSwapHelper = new Ot(t);
}
/**
* Generate the transaction payload for swap
* @param args SwapTransactionPayloadArgs
* @param args.currencyA The FA address of currency
* @param args.currencyB The FA address of currency
* @param args.currencyAAmount The amount of the input token
* @param args.currencyBAmount The amount of the output token
* @param args.slippage The slippage tolerance
* @param args.poolRoute The pool route
* @param args.recipient The recipient address
* @returns The transaction payload for swap
*/
swapTransactionPayload(t) {
w(t), h(t);
const e = [t.currencyA, t.currencyB], o = [t.currencyAAmount, t.currencyBAmount], s = [
o[0],
k(o[1], t.slippage)
], i = [...e];
i.forEach((c, d) => {
if ((c == null ? void 0 : c.indexOf("::")) > -1) {
const p = new X({
coinType: c,
// for construct Token instance, useless & meaningless
name: "token",
symbol: "token",
decimals: 5,
assetType: ""
});
p.faTypeCalculate(), p.faType && (i[d] = p.faType);
}
});
const r = [
t.poolRoute,
...i,
...s,
t.recipient
];
return I.TokenPairTypeCheck(e, [
{
function: `${this._sdk.sdkOptions.contractAddress}::router_v3::swap_batch`,
typeArguments: [],
functionArguments: [...r]
},
// ================
// if the from token is coin token
{
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]
}
]);
}
/**
* Generate the transaction payload for swap with partnership
* @param args SwapTransactionPayloadArgs & { partnership: string }
* @param args.currencyA The FA address of currency
* @param args.currencyB The FA address of currency
* @param args.currencyAAmount The amount of the input token
* @param args.currencyBAmount The amount of the output token
* @param args.slippage The slippage tolerance
* @param args.poolRoute The pool route
* @param args.recipient The recipient address
* @param args.partnership The partnership address
* @returns
*/
swapWithPartnershipTransactionPayload(t) {
if (w(t), h(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],
k(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
]
};
}
/**
* Estimate the amount of currency A from currency B
* @param args EstFromAmountArgs
* @param args.amount The amount of the input token
* @param args.from The address of the input token
* @param args.to The address of the output token
* @param args.safeMode Whether to use safe mode, only work on MAINNET
* @returns
*/
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();
}
/**
* Estimate the amount of currency B from currency A
* @param args EstFromAmountArgs
* @param args.amount The amount of the input token
* @param args.from The address of the input token
* @param args.to The address of the output token
* @param args.safeMode Whether to use safe mode, only work on MAINNET
* @returns
*/
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();
}
/**
* Estimate the amount of currency A from currency B by aggregate swap
* @param args AggregateSwapRouteArgs
* @param args.amount The amount of the input token
* @param args.from The address of the input token
* @param args.input The address of the input token, either equals to args.from or args.to
* @param args.slippage The slippage tolerance
* @param args.to The address of the output token
* @returns The result of aggregate swap
*
* @example
* ```ts
* // Estimate the result of currency A from currency B by aggregate swap
* const result = await SDK.Swap.estAmountByAggregateSwap({
* amount: "10000000",
* from: "A_AssetType",
* input: "B_AssetType",
* slippage: 0.1,
* to: "B_AssetType",
* });
* console.log(result);
* ```
*
* or
* ```ts
* // Estimate the result of currency B from currency A by aggregate swap
* const result = await SDK.Swap.estAmountByAggregateSwap({
* amount: "10000000",
* from: "B_AssetType",
* input: "A_AssetType",
* slippage: 0.1,
* to: "A_AssetType",
* });
* console.log(result);
* ```
*/
async estAmountByAggregateSwap(t) {
if (this._sdk.sdkOptions.network !== f.MAINNET)
throw new Error("Aggregate swap is only supported on MAINNET");
return await this._aggregateSwapHelper.fetchAggregateSwapRoute(t);
}
/**
* Generate the transaction script for aggregate swap
* @param args AggregateSwapRouteArgs
* @param args.amount The amount of the input token
* @param args.from The address of the input token
* @param args.input The address of the input token, either equals to args.from or args.to
* @param args.slippage The slippage tolerance
* @param args.to The address of the output token
* @param args.builder The builder of the transaction
* @param args.partnershipId The partnership ID, only work on MAINNET
* @returns The transaction script for aggregate swap
*/
async generateAggregateSwapTransactionScript(t) {
if (this._sdk.sdkOptions.network !== f.MAINNET)
throw new Error("Aggregate swap is only supported on MAINNET");
return await this._aggregateSwapHelper.generateAggregateSwapTransactionScript(
t
);
}
}
const vt = {
network: f.TESTNET,
contractAddress: "0x69faed94da99abb7316cb3ec2eeaa1b961a47349fad8c584f67a930b0d14fec7",
hyperionFullNodeIndexerURL: "https://api-testnet.hyperion.xyz/v1/graphql",
hyperionAPIHost: "https://api-testnet.hyperion.xyz",
officialFullNodeIndexerURL: "https://api.testnet.aptoslabs.com/v1/graphql",
APTOS_API_KEY: ""
}, Mt = {
network: f.MAINNET,
contractAddress: "0x8b4a2c4bb53857c718a04c020b98f8c2e1f99a68b0f57389a8bf5434cd22e05c",
hyperionFullNodeIndexerURL: "https://api.hyperion.xyz/v1/graphql",
hyperionAPIHost: "https://api.hyperion.xyz",
officialFullNodeIndexerURL: "https://api.mainnet.aptoslabs.com/v1/graphql",
APTOS_API_KEY: ""
};
function Jt(n) {
const { network: t, APTOS_API_KEY: e } = n;
return new Lt({
...t == f.MAINNET ? Mt : vt,
APTOS_API_KEY: e
});
}
class Lt {
constructor(t) {
u(this, "_options");
u(this, "_requestModule");
u(this, "_pool");
u(this, "_position");
u(this, "_swap");
u(this, "_reward");
u(this, "_aptosClient");
this._options = t, this._requestModule = new mt({
indexerURL: this._options.hyperionFullNodeIndexerURL,
officialIndexerURL: this._options.officialFullNodeIndexerURL
}), this._pool = new dt(this), this._position = new yt(this), this._swap = new Bt(this), this._reward = new _t(this);
const e = {
API_KEY: this._options.APTOS_API_KEY
};
this._aptosClient = new Y(
new V({
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;
}
}
export {
G as BASE,
ct as FeeTierIndex,
Wt as FeeTierItems,
ut as FeeTierStep,
at as HIGHEST_TICK,
zt as HighestTickByStep,
Lt as HyperionSDK,
it as LOWEST_TICK,
Qt as LowestTickByStep,
H as POOL_STABLE_TYPE,
w as currencyCheck,
Jt as initHyperionSDK,
st as logBase,
q as poolDeadline,
Vt as priceToTick,
b as roundTickBySpacing,
k as slippageCalculator,
h as slippageCheck,
l as tickComplement,
Xt as tickToPrice,
Yt as u64Max
};