client-aftermath-ts-sdk
Version:
Client Aftermath TypeScript SDK
238 lines (237 loc) • 10.8 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Coin = void 0;
const caller_1 = require("../../general/utils/caller");
const helpers_1 = require("../../general/utils/helpers");
const prices_1 = require("../../general/prices/prices");
class Coin extends caller_1.Caller {
// =========================================================================
// Constructor
// =========================================================================
// TODO: update this class to not be instantiated with a coin type at all
constructor(coinType = undefined, config, Provider) {
super(config, "coins");
this.coinType = coinType;
this.Provider = Provider;
// =========================================================================
// Private Helpers
// =========================================================================
this.useProvider = () => {
var _a;
const provider = (_a = this.Provider) === null || _a === void 0 ? void 0 : _a.Coin();
if (!provider)
throw new Error("missing AftermathApi Provider");
return provider;
};
this.coinType = coinType;
this.coinTypePackageName = this.coinType
? Coin.getCoinTypePackageName(this.coinType)
: "";
this.coinTypeSymbol = this.coinType
? Coin.getCoinTypeSymbol(this.coinType)
: "";
this.innerCoinType = this.coinType
? Coin.getInnerCoinType(this.coinType)
: "";
}
// =========================================================================
// Public Methods
// =========================================================================
// =========================================================================
// Inspections
// =========================================================================
getCoinsToDecimals(inputs) {
return __awaiter(this, void 0, void 0, function* () {
const { coins } = inputs;
const metadatas = yield this.getCoinMetadatas(inputs);
const coinsToDecimals = metadatas
.map((data) => data.decimals)
.reduce((acc, decimals, index) => {
return Object.assign(Object.assign({}, acc), { [coins[index]]: decimals });
}, {});
return coinsToDecimals;
});
}
getCoinMetadata(coin) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.metadata)
return this.metadata;
const coinType = (_a = this.coinType) !== null && _a !== void 0 ? _a : coin;
if (!coinType)
throw new Error("no valid coin type");
const [metadata] = yield this.getCoinMetadatas({ coins: [coinType] });
this.setCoinMetadata(metadata);
return metadata;
});
}
getCoinMetadatas(inputs) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchApi("metadata", inputs);
});
}
setCoinMetadata(metadata) {
this.metadata = metadata;
}
getPrice(coin) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.priceInfo !== undefined)
return this.priceInfo;
const coinType = (_a = this.coinType) !== null && _a !== void 0 ? _a : coin;
if (!coinType)
throw new Error("no valid coin type");
const priceInfo = yield new prices_1.Prices(this.config).getCoinPriceInfo({
coin: coinType,
});
// NOTE: do we want this here ? (unexpected behavior)
// if (price <= 0) throw new Error("No price found.")
this.setPriceInfo(priceInfo);
return priceInfo;
});
}
setPriceInfo(priceInfo) {
this.priceInfo = priceInfo;
}
getVerifiedCoins() {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchApi("verified");
});
}
}
exports.Coin = Coin;
// =========================================================================
// Constants
// =========================================================================
Coin.constants = {
suiCoinType: "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
suiCoinDecimals: 9,
coinObjectType: "0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin",
defaultCoinDecimals: {
sui: 9,
evm: 18,
svm: 9,
},
};
// =========================================================================
// Public Static Methods
// =========================================================================
// =========================================================================
// Coin Type
// =========================================================================
// TODO: remove in favor of sui js implementation Coin.getCoinStructTag() if it is the same
Coin.getCoinTypePackageName = (coin) => {
const splitCoin = coin.split("::");
if (splitCoin.length !== 3)
return "";
const packageName = splitCoin[splitCoin.length - 2];
if (!packageName)
return "";
return packageName;
};
// TODO: remove in favor of sui js implementation ?
Coin.getCoinTypeSymbol = (coin) => {
const startIndex = coin.lastIndexOf("::") + 2;
// NOTE: should error if coin is not a valid coin type instead of empty string ?
if (startIndex <= 1)
return "";
const foundEndIndex = coin.indexOf(">");
const endIndex = foundEndIndex < 0 ? coin.length : foundEndIndex;
const displayType = coin.slice(startIndex, endIndex);
return displayType;
};
Coin.getInnerCoinType = (coin) => coin.includes("<") ? coin.split("<")[1].slice(0, -1) : "";
Coin.coinTypeFromKeyType = (keyType) => {
const startIndex = keyType.lastIndexOf("<") + 1;
const endIndex = keyType.indexOf(">", startIndex);
return keyType.slice(startIndex, endIndex);
};
Coin.isSuiCoin = (coin) => helpers_1.Helpers.stripLeadingZeroesFromType(coin) ===
helpers_1.Helpers.stripLeadingZeroesFromType(Coin.constants.suiCoinType);
Coin.isCoinObjectType = (objectType) => helpers_1.Helpers.stripLeadingZeroesFromType(objectType).startsWith(helpers_1.Helpers.stripLeadingZeroesFromType(Coin.constants.coinObjectType));
// =========================================================================
// Helpers
// =========================================================================
Coin.coinsAndAmountsOverZero = (coinAmounts) => {
// NOTE: will these loops always run in same order (is this a js gurantee or not) ?
const coins = Object.keys(coinAmounts).filter((key) => coinAmounts[key] > 0);
const amounts = Object.values(coinAmounts).filter((amount) => amount > 0);
return { coins, amounts };
};
Coin.coinsAndBalancesOverZero = (coinsToBalance) => {
// NOTE: will these loops always run in same order (is this a js gurantee or not) ?
const coins = Object.keys(coinsToBalance).filter((key) => BigInt(coinsToBalance[key]) > BigInt(0));
const balances = Object.values(coinsToBalance)
.map(BigInt)
.filter((amount) => amount > BigInt(0));
return { coins, balances };
};
Coin.filterCoinsByType = (inputs) => {
var _a;
const filter = inputs.filter.toLowerCase().trim();
return (_a = inputs.coinTypes) === null || _a === void 0 ? void 0 : _a.filter((coinType) => {
try {
return (helpers_1.Helpers.stripLeadingZeroesFromType(coinType)
.toLowerCase()
.includes(helpers_1.Helpers.stripLeadingZeroesFromType(filter)) ||
coinType
.toLowerCase()
.includes(helpers_1.Helpers.addLeadingZeroesToType(filter)));
}
catch (e) { }
return (helpers_1.Helpers.stripLeadingZeroesFromType(coinType)
.toLowerCase()
.includes(filter) || coinType.toLowerCase().includes(filter));
});
};
Coin.filterCoinsByMetadata = (inputs) => {
var _a;
return (_a = Object.entries(inputs.coinMetadatas)) === null || _a === void 0 ? void 0 : _a.filter(([coin, metadata]) => {
const cleanInput = inputs.filter.toLowerCase().trim();
return (coin.startsWith(cleanInput) ||
[metadata.name, metadata.symbol].some((str) => str.toLowerCase().includes(cleanInput)));
}).map(([coin]) => coin);
};
// =========================================================================
// Balance
// =========================================================================
// =========================================================================
// Conversions
// =========================================================================
/*
Convert user-inputted values into their onchain counterparts (e.g. u64)
TO-DO: change name
*/
Coin.normalizeBalance = (balance, decimals) => BigInt(
// Take the floor in case user provides greater than `decimals` decimals
Math.floor(balance * Math.pow(10, decimals)));
Coin.balanceWithDecimals = (amount, decimals) => {
// TO-DO: make this conversion via string so no overflow or loss when bigint to number
return Number(amount) / Number(Math.pow(10, decimals));
};
Coin.balanceWithDecimalsUsd = (amount, decimals, price) => {
return Coin.balanceWithDecimals(amount, decimals) * price;
};
Coin.coinSymbolForCoinType = (inputs) => {
const { coinType, coinSymbolToCoinTypes } = inputs;
try {
const fullCoinType = helpers_1.Helpers.addLeadingZeroesToType(coinType);
const foundCoinData = Object.entries(coinSymbolToCoinTypes).find(([, coinsTypes]) => coinsTypes
.map(helpers_1.Helpers.addLeadingZeroesToType)
.includes(fullCoinType));
const foundCoinSymbol = foundCoinData === null || foundCoinData === void 0 ? void 0 : foundCoinData[0];
return foundCoinSymbol;
}
catch (e) {
return undefined;
}
};