UNPKG

hive-keychain-commons

Version:

Platform-agnostic functions used in Hive Keychain mobile and extensions

220 lines (219 loc) 7.5 kB
"use strict"; 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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.VscUtils = void 0; const moment_1 = __importDefault(require("moment")); const config_1 = __importDefault(require("../config")); const vsc_1 = require("../interfaces/vsc"); const format_utils_1 = require("./format.utils"); const waitForStatus = (id, timeoutSeconds = 10, endAtStatus = vsc_1.VscStatus.CONFIRMED) => __awaiter(void 0, void 0, void 0, function* () { let iterations = 0; let status = vsc_1.VscStatus.UNCONFIRMED; const wait = 500; const maxIterations = (timeoutSeconds / wait) * 1000; while (iterations < maxIterations) { status = yield checkStatus(id); if (status === endAtStatus || status === vsc_1.VscStatus.FAILED) return status; iterations++; yield new Promise((resolve) => setTimeout(resolve, wait)); } return status; }); const checkStatus = (id) => { const query = `{ findTransaction( filterOptions: {byId:"${id}"} ) { status } }`; return fetchQuery(query).then((res) => { var _a, _b, _c, _d, _e, _f; if ((_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.findTransaction) === null || _b === void 0 ? void 0 : _b[0]) return (_c = res.data.findTransaction) === null || _c === void 0 ? void 0 : _c[0].status; return ((_f = (_e = (_d = res === null || res === void 0 ? void 0 : res.data) === null || _d === void 0 ? void 0 : _d.findLedgerTXs) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.id) === id ? vsc_1.VscStatus.CONFIRMED : vsc_1.VscStatus.UNCONFIRMED; }); }; const fetchHistory = (username, limit = null, offset = null) => __awaiter(void 0, void 0, void 0, function* () { const query = `{ findTransaction(filterOptions: {byAccount: "hive:${username}",limit:${limit},offset:${offset}}) { id anchr_height anchr_index anchr_ts type op_types first_seen nonce rc_limit required_auths status ops { required_auths type index data } } }`; const response = yield fetchQuery(query); if (!(response === null || response === void 0 ? void 0 : response.data)) { console.error('Invalid response from VSC API:', response); return { findTransaction: [], findLedgerTXs: [] }; } return response.data; }); const getOrganizedHistory = (username) => __awaiter(void 0, void 0, void 0, function* () { const history = yield fetchHistory(username); const organizedHistory = [ ...(history.findTransaction || []) .flatMap((e) => e.ops.map((op) => ({ from: op.data.from, to: op.data.to, amount: parseFloat(op.data.amount), timestamp: new Date(e.first_seen), txId: e.id, memo: op.data.memo, asset: op.data.asset, status: e.status, type: op.type, }))) .filter((e) => !(e.type === 'withdraw' && e.from !== `hive:${username}`)), ].sort((a, b) => { return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(); }); return organizedHistory; }); const blockHeightToTimestamp = (height) => { const START_BLOCK = 88079516; const START_BLOCK_TIME = (0, moment_1.default)('2024-08-16T02:46:48Z'); return START_BLOCK_TIME.clone() .add((height - START_BLOCK) * 3, 'seconds') .toDate(); }; const getAddressFromDid = (did) => { const regex = new RegExp(':([a-zA-Z0-9.-]*)$'); const matches = did.match(regex); return matches === null || matches === void 0 ? void 0 : matches[matches.length - 1]; }; const getFormattedAddress = (address) => { if (address.startsWith('hive:')) return `@${getAddressFromDid(address)}`; else return format_utils_1.FormatUtils.shortenString(getAddressFromDid(address), 4); }; const fetchQuery = (query) => { return fetch(config_1.default.vsc.API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query, }), }).then((res) => res.json()); }; const getAccountBalance = (username) => __awaiter(void 0, void 0, void 0, function* () { const query = `{ getAccountBalance(account: "hive:${username}") { account hbd hive hbd_savings hbd_claim hbd_modify hbd_avg block_height hive_consensus pending_hbd_unstaking } }`; return ((yield fetchQuery(query)).data.getAccountBalance || { hive: 0, hbd: 0, hive_consensus: 0, hbd_avg: 0, hbd_claim: 0, hbd_modify: 0, hbd_savings: 0, pending_hbd_unstaking: 0, }); }); const getWithdrawJson = (data, netId) => { const JSON_ID = 'vsc.withdraw'; const json = { net_id: data.netId || netId, from: data.username.startsWith('hive:') ? data.username : `hive:${data.username}`, to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`, amount: data.amount, asset: data.currency.toLowerCase(), memo: data.memo, }; return { id: JSON_ID, json, }; }; const getTransferJson = (data, netId) => { const JSON_ID = 'vsc.transfer'; const json = { net_id: data.netId || netId, from: data.username.startsWith('hive:') ? data.username : `hive:${data.username}`, to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`, amount: data.amount, asset: data.currency.toLowerCase(), memo: data.memo, }; return { id: JSON_ID, json, }; }; const getStakingJson = (data, netId) => { const JSON_ID = data.operation === vsc_1.VscStakingOperation.STAKING ? 'vsc.stake_hbd' : 'vsc.unstake_hbd'; const json = { net_id: data.netId || netId, from: data.username.startsWith('hive:') ? data.username : `hive:${data.username}`, to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`, amount: data.amount, asset: data.currency.toLowerCase(), }; return { id: JSON_ID, json, }; }; exports.VscUtils = { checkStatus, waitForStatus, getOrganizedHistory, getAddressFromDid, getAccountBalance, blockHeightToTimestamp, getFormattedAddress, getWithdrawJson, getTransferJson, getStakingJson, };