@bluefin-exchange/bluefin7k-aggregator-sdk
Version:
66 lines (65 loc) • 2.07 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCoinOjectIdsByAmount = void 0;
const config_1 = require("../config");
const orderByKey = (array, key, sortBy) => {
if (!array?.length) {
return;
}
let swapped;
do {
swapped = false;
for (let i = 0; i < array.length - 1; i++) {
const a = BigInt(array[i][key]);
const b = BigInt(array[i + 1][key]);
if (sortBy === "desc" ? a < b : a > b) {
const temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return array;
};
const getCoinOjectIdsByAmount = async (address, amount, coinType) => {
let coinBalances = [];
let hasNextPage = true;
let nextCursor = undefined;
while (hasNextPage) {
try {
const coins = await config_1.Config.getSuiClient().getCoins({
owner: address,
coinType,
cursor: nextCursor,
});
coinBalances = [...coinBalances, ...coins.data];
hasNextPage = coins.hasNextPage;
nextCursor = coins.nextCursor;
}
catch (error) {
console.error("Error fetching data:", error);
hasNextPage = false;
}
}
// sort coin balance before get object id
const coinObj = orderByKey(coinBalances.map((item) => {
return {
...item,
balance: item.balance,
};
}), "balance", "desc") ?? [];
let balance = "0";
const objectIds = [];
const objectCoins = [];
for (const coin of coinObj) {
balance = (BigInt(coin.balance) + BigInt(balance)).toString(10);
objectIds.push(coin.coinObjectId);
objectCoins.push(coin);
if (BigInt(balance) >= BigInt(amount)) {
break;
}
}
return { objectIds, balance, objectCoins };
};
exports.getCoinOjectIdsByAmount = getCoinOjectIdsByAmount;
;