hive-keychain-commons 1.7.1 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
+ export * from './interfaces/global-properties';
1
2
  export * from './interfaces/keychain';
3
+ export * from './interfaces/price';
4
+ export * from './interfaces/tokens';
2
5
  export * from './interfaces/vsc';
3
6
  export { LeaseKeys } from './lease-market/lease-keys';
4
7
  export { AcceptRequestJSON, CancelDelegationJSON, CancelRequestJSON, PaymentJSON, ReimbursmentJSON, RequestCancelRequestJSON, RequestJSON, } from './lease-market/lease-market.interface';
@@ -8,6 +11,7 @@ export * from './swaps/swap.interface';
8
11
  export * from './utils/assets.utils';
9
12
  export * from './utils/crypto.utils';
10
13
  export * from './utils/export-transactions.utils';
14
+ export * from './utils/format.utils';
11
15
  export * from './utils/history-filters.utils';
12
16
  export * from './utils/keys.utils';
13
17
  export * from './utils/transaction.utils';
package/lib/index.js CHANGED
@@ -15,7 +15,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.LeaseKeys = void 0;
18
+ __exportStar(require("./interfaces/global-properties"), exports);
18
19
  __exportStar(require("./interfaces/keychain"), exports);
20
+ __exportStar(require("./interfaces/price"), exports);
21
+ __exportStar(require("./interfaces/tokens"), exports);
19
22
  __exportStar(require("./interfaces/vsc"), exports);
20
23
  var lease_keys_1 = require("./lease-market/lease-keys");
21
24
  Object.defineProperty(exports, "LeaseKeys", { enumerable: true, get: function () { return lease_keys_1.LeaseKeys; } });
@@ -25,6 +28,7 @@ __exportStar(require("./swaps/swap.interface"), exports);
25
28
  __exportStar(require("./utils/assets.utils"), exports);
26
29
  __exportStar(require("./utils/crypto.utils"), exports);
27
30
  __exportStar(require("./utils/export-transactions.utils"), exports);
31
+ __exportStar(require("./utils/format.utils"), exports);
28
32
  __exportStar(require("./utils/history-filters.utils"), exports);
29
33
  __exportStar(require("./utils/keys.utils"), exports);
30
34
  __exportStar(require("./utils/transaction.utils"), exports);
@@ -0,0 +1,18 @@
1
+ import type { DynamicGlobalProperties, Price } from '@hiveio/dhive';
2
+ export interface RewardFund {
3
+ author_reward_curve: string;
4
+ content_constant: string;
5
+ curation_reward_curve: string;
6
+ id: number;
7
+ last_update: string;
8
+ name: string;
9
+ percent_content_rewards: number;
10
+ percent_curation_rewards: number;
11
+ recent_claims: string;
12
+ reward_balance: string;
13
+ }
14
+ export interface GlobalProperties {
15
+ globals?: DynamicGlobalProperties;
16
+ price?: Price;
17
+ rewardFund?: RewardFund;
18
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -341,4 +341,9 @@ export type KeychainRequestWrapper = {
341
341
  request: KeychainRequest;
342
342
  request_id: number;
343
343
  };
344
+ export declare enum LoadingState {
345
+ LOADING = 0,
346
+ LOADED = 1,
347
+ FAILED = 2
348
+ }
344
349
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeychainKeyTypesLC = exports.KeychainKeyTypes = exports.KeychainRequestTypes = void 0;
3
+ exports.LoadingState = exports.KeychainKeyTypesLC = exports.KeychainKeyTypes = exports.KeychainRequestTypes = void 0;
4
4
  var KeychainRequestTypes;
5
5
  (function (KeychainRequestTypes) {
6
6
  KeychainRequestTypes["decode"] = "decode";
@@ -50,3 +50,9 @@ var KeychainKeyTypesLC;
50
50
  KeychainKeyTypesLC["active"] = "active";
51
51
  KeychainKeyTypesLC["memo"] = "memo";
52
52
  })(KeychainKeyTypesLC = exports.KeychainKeyTypesLC || (exports.KeychainKeyTypesLC = {}));
53
+ var LoadingState;
54
+ (function (LoadingState) {
55
+ LoadingState[LoadingState["LOADING"] = 0] = "LOADING";
56
+ LoadingState[LoadingState["LOADED"] = 1] = "LOADED";
57
+ LoadingState[LoadingState["FAILED"] = 2] = "FAILED";
58
+ })(LoadingState = exports.LoadingState || (exports.LoadingState = {}));
@@ -0,0 +1,9 @@
1
+ export interface Currency {
2
+ usd_24h_change?: number;
3
+ usd?: number;
4
+ }
5
+ export interface CurrencyPrices {
6
+ bitcoin: Currency;
7
+ hive: Currency;
8
+ hive_dollar: Currency;
9
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ export declare enum TokenType {
2
+ HIVE = "HIVE",
3
+ HIVE_ENGINE = "HIVE_ENGINE",
4
+ VSC = "VSC"
5
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TokenType = void 0;
4
+ var TokenType;
5
+ (function (TokenType) {
6
+ TokenType["HIVE"] = "HIVE";
7
+ TokenType["HIVE_ENGINE"] = "HIVE_ENGINE";
8
+ TokenType["VSC"] = "VSC";
9
+ })(TokenType = exports.TokenType || (exports.TokenType = {}));
@@ -6,15 +6,11 @@ export declare enum VscStatus {
6
6
  }
7
7
  export declare enum VscHistoryType {
8
8
  CONTRACT_CALL = "CONTRACT_CALL",
9
- TRANSFER = "TRANSFER",
10
- DEPOSIT = "DEPOSIT",
11
- WITHDRAW = "WITHDRAW",
12
- STAKING = "STAKING",
13
- UNSTAKING = "UNSTAKING"
14
- }
15
- export declare enum VscLedgerType {
9
+ TRANSFER = "transfer",
10
+ DEPOSIT = "deposit",
16
11
  WITHDRAW = "withdraw",
17
- DEPOSIT = "deposit"
12
+ STAKING = "stake_hbd",
13
+ UNSTAKING = "unstake_hbd"
18
14
  }
19
15
  export declare enum VscToken {
20
16
  HIVE = "HIVE",
@@ -28,39 +24,64 @@ export type VscRequestParams = {
28
24
  netId?: string;
29
25
  };
30
26
  export type VscHistoryResponse = {
31
- findLedgerTXs: {
32
- txs: VscTransfer[];
33
- };
34
- findTransaction: {
35
- txs: VscCall[];
36
- };
27
+ findLedgerTXs: VscLedgerTxResponse[];
28
+ findTransaction: VscTxResponse[];
37
29
  };
38
- export type VscTransfer = {
39
- type?: VscHistoryType.TRANSFER;
30
+ declare enum VscAsset {
31
+ HIVE = "hive",
32
+ HBD = "hbd"
33
+ }
34
+ export type VscLedgerTxResponse = {
40
35
  amount: number;
41
36
  block_height: number;
42
37
  from: string;
43
38
  id: string;
44
- memo: string | null;
45
39
  owner: string;
46
- t: VscLedgerType;
47
- tk: VscToken;
48
40
  timestamp: Date;
49
- status: VscStatus;
41
+ asset: VscAsset;
42
+ tx_id: string;
43
+ type: string;
50
44
  };
51
- export type VscCall = {
52
- type?: VscHistoryType.CONTRACT_CALL;
45
+ export type VscTxResponse = {
53
46
  status: VscStatus;
54
47
  id: string;
55
- anchored_height: number;
48
+ anchr_height: number;
56
49
  timestamp: Date;
57
- data: {
58
- action: string;
59
- contract_id: string;
60
- op: string;
61
- payload: object;
62
- };
50
+ data: VscTxData;
63
51
  required_auths: {
64
52
  value: string;
65
53
  }[];
54
+ anchr_index: number;
55
+ anchr_opidx: number;
56
+ anchr_ts: Date;
57
+ first_seen: Date;
58
+ ledger: any[];
59
+ nonce: number;
60
+ rc_limit: number;
61
+ type: string;
62
+ };
63
+ export type VscTxData = {
64
+ amount: number;
65
+ asset: VscAsset;
66
+ from: string;
67
+ memo?: string;
68
+ to: string;
69
+ type: VscHistoryType;
70
+ };
71
+ export type VscHistoryItem = VscTxData & {
72
+ timestamp: Date;
73
+ status: VscStatus;
74
+ txId: string;
75
+ };
76
+ export type VscAccountBalance = {
77
+ account: string;
78
+ block_height: number;
79
+ hbd: number;
80
+ hbd_avg: number;
81
+ hbd_claim: number;
82
+ hbd_modify: number;
83
+ hbd_savings: number;
84
+ hive: number;
85
+ hive_consensus: number;
66
86
  };
87
+ export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VscStakingOperation = exports.VscToken = exports.VscLedgerType = exports.VscHistoryType = exports.VscStatus = void 0;
3
+ exports.VscStakingOperation = exports.VscToken = exports.VscHistoryType = exports.VscStatus = void 0;
4
4
  var VscStatus;
5
5
  (function (VscStatus) {
6
6
  VscStatus["UNCONFIRMED"] = "UNCONFIRMED";
@@ -11,17 +11,12 @@ var VscStatus;
11
11
  var VscHistoryType;
12
12
  (function (VscHistoryType) {
13
13
  VscHistoryType["CONTRACT_CALL"] = "CONTRACT_CALL";
14
- VscHistoryType["TRANSFER"] = "TRANSFER";
15
- VscHistoryType["DEPOSIT"] = "DEPOSIT";
16
- VscHistoryType["WITHDRAW"] = "WITHDRAW";
17
- VscHistoryType["STAKING"] = "STAKING";
18
- VscHistoryType["UNSTAKING"] = "UNSTAKING";
14
+ VscHistoryType["TRANSFER"] = "transfer";
15
+ VscHistoryType["DEPOSIT"] = "deposit";
16
+ VscHistoryType["WITHDRAW"] = "withdraw";
17
+ VscHistoryType["STAKING"] = "stake_hbd";
18
+ VscHistoryType["UNSTAKING"] = "unstake_hbd";
19
19
  })(VscHistoryType = exports.VscHistoryType || (exports.VscHistoryType = {}));
20
- var VscLedgerType;
21
- (function (VscLedgerType) {
22
- VscLedgerType["WITHDRAW"] = "withdraw";
23
- VscLedgerType["DEPOSIT"] = "deposit";
24
- })(VscLedgerType = exports.VscLedgerType || (exports.VscLedgerType = {}));
25
20
  var VscToken;
26
21
  (function (VscToken) {
27
22
  VscToken["HIVE"] = "HIVE";
@@ -32,3 +27,8 @@ var VscStakingOperation;
32
27
  VscStakingOperation["STAKING"] = "STAKING";
33
28
  VscStakingOperation["UNSTAKING"] = "UNSTAKING";
34
29
  })(VscStakingOperation = exports.VscStakingOperation || (exports.VscStakingOperation = {}));
30
+ var VscAsset;
31
+ (function (VscAsset) {
32
+ VscAsset["HIVE"] = "hive";
33
+ VscAsset["HBD"] = "hbd";
34
+ })(VscAsset || (VscAsset = {}));
@@ -0,0 +1,24 @@
1
+ import type { DynamicGlobalProperties } from '@hiveio/dhive';
2
+ import { Asset } from '..';
3
+ import { GlobalProperties } from '../interfaces/global-properties';
4
+ import { CurrencyPrices } from '../interfaces/price';
5
+ export declare const FormatUtils: {
6
+ withCommas: (nb: string, decimals?: number, removeTrailingZeros?: boolean) => string;
7
+ toHP: (vests: string, props?: DynamicGlobalProperties) => number;
8
+ toFormattedHP: (vests: number, props?: DynamicGlobalProperties) => string;
9
+ fromHP: (hp: string, props: DynamicGlobalProperties) => number;
10
+ formatCurrencyValue: (value: string | Asset | number, digits?: number, removeTrailingZeros?: boolean) => string;
11
+ nFormatter: (num: number, digits: number) => string;
12
+ hasMoreThanXDecimal: (nb: number, decimal: number) => boolean;
13
+ toNumber: (value: string | Asset) => number;
14
+ getSymbol: (nai: string) => "HIVE" | "HBD" | "HP" | undefined;
15
+ getAmountFromNai: (obj: any) => number;
16
+ fromNaiAndSymbol: (obj: any) => string;
17
+ removeHtmlTags: (str: string) => string;
18
+ getValFromString: (str: string) => number;
19
+ trimUselessZero: (nb: number, precision: number) => string;
20
+ getUSDFromVests: (vestAmount: number, globalProperties: GlobalProperties, currencyPrices: CurrencyPrices) => string;
21
+ getOrdinalLabelTranslation: (activeRank: string) => "html_popup_witness_ranking_ordinal_st_label" | "html_popup_witness_ranking_ordinal_nd_label" | "html_popup_witness_ranking_ordinal_rd_label" | "html_popup_witness_ranking_ordinal_th_label";
22
+ dateToFormattedString: (date: Date) => string;
23
+ shortenString: (str: string, length?: number) => string;
24
+ };
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FormatUtils = void 0;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ const __1 = require("..");
9
+ const withCommas = (nb, decimals = 3, removeTrailingZeros = false) => {
10
+ const currency = nb.split(' ')[1];
11
+ const value = parseFloat(nb).toFixed(decimals);
12
+ const parts = value.split('.');
13
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
14
+ let finalNumber = parts.join('.');
15
+ if (removeTrailingZeros) {
16
+ finalNumber = finalNumber.replace(/^([\d,]+)$|^([\d,]+)\.0*$|^([\d,]+\.[0-9]*?)0*$/, '$1$2$3');
17
+ }
18
+ if (currency) {
19
+ finalNumber = finalNumber + ' ' + currency;
20
+ }
21
+ return finalNumber;
22
+ };
23
+ const toHP = (vests, props) => props
24
+ ? (parseFloat(vests) * parseFloat(props.total_vesting_fund_hive + '')) /
25
+ parseFloat(props.total_vesting_shares + '')
26
+ : 0;
27
+ const toFormattedHP = (vests, props) => {
28
+ return `${toHP(vests.toString(), props).toFixed(3)} HP`;
29
+ };
30
+ const fromHP = (hp, props) => (parseFloat(hp) / parseFloat(props.total_vesting_fund_hive + '')) *
31
+ parseFloat(props.total_vesting_shares + '');
32
+ const formatCurrencyValue = (value, digits = 3, removeTrailingZeros = false) => {
33
+ if (value === undefined || value === null) {
34
+ return '...';
35
+ }
36
+ return withCommas(value.toString().replace('HBD', '').replace('HIVE', '').trim(), digits, removeTrailingZeros);
37
+ };
38
+ const nFormatter = (num, digits) => {
39
+ const si = [
40
+ {
41
+ value: 1,
42
+ symbol: '',
43
+ },
44
+ {
45
+ value: 1e3,
46
+ symbol: 'k',
47
+ },
48
+ {
49
+ value: 1e6,
50
+ symbol: 'M',
51
+ },
52
+ {
53
+ value: 1e9,
54
+ symbol: 'G',
55
+ },
56
+ {
57
+ value: 1e12,
58
+ symbol: 'T',
59
+ },
60
+ {
61
+ value: 1e15,
62
+ symbol: 'P',
63
+ },
64
+ {
65
+ value: 1e18,
66
+ symbol: 'E',
67
+ },
68
+ ];
69
+ const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
70
+ let i;
71
+ for (i = si.length - 1; i > 0; i--) {
72
+ if (num >= si[i].value) {
73
+ break;
74
+ }
75
+ }
76
+ return (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol;
77
+ };
78
+ const hasMoreThanXDecimal = (nb, decimal) => {
79
+ const splitedNumber = nb.toString().split('.');
80
+ return splitedNumber.length > 1 ? splitedNumber[1].length > decimal : false;
81
+ };
82
+ const toNumber = (value) => {
83
+ return parseFloat(value.toString().split(' ')[0].trim());
84
+ };
85
+ const getSymbol = (nai) => {
86
+ if (nai === '@@000000013')
87
+ return 'HBD';
88
+ if (nai === '@@000000021')
89
+ return 'HIVE';
90
+ if (nai === '@@000000037')
91
+ return 'HP';
92
+ };
93
+ const fromNaiAndSymbol = (obj) => {
94
+ return `${(obj.amount / 1000).toFixed(obj.precision)} ${exports.FormatUtils.getSymbol(obj.nai)}`;
95
+ };
96
+ const getAmountFromNai = (obj) => {
97
+ const res = fromNaiAndSymbol(obj);
98
+ return __1.Asset.fromString(res).amount;
99
+ };
100
+ const removeHtmlTags = (str) => {
101
+ return str.replace(/<(?:.|\n)*?>/gm, '');
102
+ };
103
+ const getValFromString = (str) => {
104
+ return parseFloat(str.split(' ')[0]);
105
+ };
106
+ const trimUselessZero = (nb, precision) => {
107
+ var _a;
108
+ const numberWithPrecision = nb.toFixed(precision);
109
+ const n = parseFloat(numberWithPrecision).toString();
110
+ if (n.split('.').length > 0 && ((_a = n.split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) > 3)
111
+ return exports.FormatUtils.withCommas(n);
112
+ else
113
+ return exports.FormatUtils.withCommas(parseFloat(n).toFixed(3));
114
+ };
115
+ const getUSDFromVests = (vestAmount, globalProperties, currencyPrices) => {
116
+ return (exports.FormatUtils.toHP(vestAmount.toString(), globalProperties.globals) *
117
+ currencyPrices.hive.usd).toFixed(2);
118
+ };
119
+ const getOrdinalLabelTranslation = (activeRank) => {
120
+ const result = parseFloat(activeRank) % 10;
121
+ switch (result) {
122
+ case 1:
123
+ return 'html_popup_witness_ranking_ordinal_st_label';
124
+ case 2:
125
+ return 'html_popup_witness_ranking_ordinal_nd_label';
126
+ case 3:
127
+ return 'html_popup_witness_ranking_ordinal_rd_label';
128
+ default:
129
+ return 'html_popup_witness_ranking_ordinal_th_label';
130
+ }
131
+ };
132
+ const dateToFormattedString = (date) => {
133
+ return (0, moment_1.default)(date).format('MM/DD/YY');
134
+ };
135
+ const shortenString = (str, length = 3) => {
136
+ // TODO : remove during merge EVM (duplicate)
137
+ return (str === null || str === void 0 ? void 0 : str.length) > length * 2
138
+ ? `${str.substring(length, 0)}...${str === null || str === void 0 ? void 0 : str.toString().slice(-length)}`
139
+ : str;
140
+ };
141
+ exports.FormatUtils = {
142
+ withCommas,
143
+ toHP,
144
+ toFormattedHP,
145
+ fromHP,
146
+ formatCurrencyValue,
147
+ nFormatter,
148
+ hasMoreThanXDecimal,
149
+ toNumber,
150
+ getSymbol,
151
+ getAmountFromNai,
152
+ fromNaiAndSymbol,
153
+ removeHtmlTags,
154
+ getValFromString,
155
+ trimUselessZero,
156
+ getUSDFromVests,
157
+ getOrdinalLabelTranslation,
158
+ dateToFormattedString,
159
+ shortenString,
160
+ };
@@ -1,7 +1,43 @@
1
- import { VscHistoryType, VscStatus } from '../interfaces/vsc';
1
+ import { RequestVscStaking, RequestVscTransfer, RequestVscWithdrawal } from '../interfaces/keychain';
2
+ import { VscHistoryItem, VscHistoryType, VscStatus } from '../interfaces/vsc';
2
3
  export declare const VscUtils: {
3
4
  checkStatus: (id: string, type: VscHistoryType) => Promise<VscStatus>;
4
- waitForStatus: (id: string, type: VscHistoryType, maxIterations?: number, wait?: number) => Promise<VscStatus>;
5
- getOrganizedHistory: (username: string) => Promise<(import("../interfaces/vsc").VscTransfer | import("../interfaces/vsc").VscCall)[]>;
5
+ waitForStatus: (id: string, type: VscHistoryType, timeoutSeconds?: number, endAtStatus?: VscStatus) => Promise<VscStatus>;
6
+ getOrganizedHistory: (username: string) => Promise<VscHistoryItem[]>;
6
7
  getAddressFromDid: (did: string) => string | undefined;
8
+ getAccountBalance: (username: string) => Promise<any>;
9
+ blockHeightToTimestamp: (height: number) => Date;
10
+ getFormattedAddress: (address: string) => string;
11
+ getWithdrawJson: (data: Omit<RequestVscWithdrawal, 'domain' | 'type'>, netId?: string) => {
12
+ id: string;
13
+ json: {
14
+ net_id: string | undefined;
15
+ from: string | undefined;
16
+ to: string;
17
+ amount: string;
18
+ asset: string;
19
+ memo: string;
20
+ };
21
+ };
22
+ getTransferJson: (data: Omit<RequestVscTransfer, 'domain' | 'type'>, netId?: string) => {
23
+ id: string;
24
+ json: {
25
+ net_id: string | undefined;
26
+ from: string | undefined;
27
+ to: string;
28
+ amount: string;
29
+ asset: string;
30
+ memo: string;
31
+ };
32
+ };
33
+ getStakingJson: (data: Omit<RequestVscStaking, 'domain' | 'type'>, netId?: string) => {
34
+ id: string;
35
+ json: {
36
+ net_id: string | undefined;
37
+ from: string | undefined;
38
+ to: string;
39
+ amount: string;
40
+ asset: string;
41
+ };
42
+ };
7
43
  };
@@ -16,12 +16,15 @@ exports.VscUtils = void 0;
16
16
  const moment_1 = __importDefault(require("moment"));
17
17
  const config_1 = __importDefault(require("../config"));
18
18
  const vsc_1 = require("../interfaces/vsc");
19
- const waitForStatus = (id, type, maxIterations = 20, wait = 500) => __awaiter(void 0, void 0, void 0, function* () {
19
+ const format_utils_1 = require("./format.utils");
20
+ const waitForStatus = (id, type, timeoutSeconds = 10, endAtStatus = vsc_1.VscStatus.CONFIRMED) => __awaiter(void 0, void 0, void 0, function* () {
20
21
  let iterations = 0;
21
22
  let status = vsc_1.VscStatus.UNCONFIRMED;
23
+ const wait = 500;
24
+ const maxIterations = (timeoutSeconds / wait) * 1000;
22
25
  while (iterations < maxIterations) {
23
26
  status = yield checkStatus(id, type);
24
- if (status === vsc_1.VscStatus.CONFIRMED || status === vsc_1.VscStatus.FAILED)
27
+ if (status === endAtStatus || status === vsc_1.VscStatus.FAILED)
25
28
  return status;
26
29
  iterations++;
27
30
  yield new Promise((resolve) => setTimeout(resolve, wait));
@@ -29,65 +32,57 @@ const waitForStatus = (id, type, maxIterations = 20, wait = 500) => __awaiter(vo
29
32
  return status;
30
33
  });
31
34
  const checkStatus = (id, type) => {
32
- let query;
33
- if (type === vsc_1.VscHistoryType.CONTRACT_CALL ||
34
- type === vsc_1.VscHistoryType.WITHDRAW ||
35
- type === vsc_1.VscHistoryType.STAKING ||
36
- type === vsc_1.VscHistoryType.UNSTAKING ||
37
- type === vsc_1.VscHistoryType.TRANSFER) {
38
- query = `{
35
+ const query = `{
39
36
  findTransaction(
40
37
  filterOptions: {byId:"${id}"}
41
38
  ) {
42
39
  status
43
40
  }
44
41
  }`;
45
- }
46
- else if (type === vsc_1.VscHistoryType.DEPOSIT) {
47
- query = `{
48
- findLedgerTXs(filterOptions: {byTxId: "${id}-0"}) {
49
-
50
- status
51
-
52
- }
53
- }`;
54
- }
55
42
  return fetchQuery(query).then((res) => {
56
43
  var _a, _b, _c, _d, _e, _f;
57
- return (((_c = (_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]) === null || _c === void 0 ? void 0 : _c.status) ||
58
- ((_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.status));
44
+ 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])
45
+ return (_c = res.data.findTransaction) === null || _c === void 0 ? void 0 : _c[0].status;
46
+ 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
47
+ ? vsc_1.VscStatus.CONFIRMED
48
+ : vsc_1.VscStatus.UNCONFIRMED;
59
49
  });
60
50
  };
61
51
  const fetchHistory = (username) => __awaiter(void 0, void 0, void 0, function* () {
62
52
  const query = `{
63
- findLedgerTXs(
64
- filterOptions: {byToFrom: "hive:${username}"}
65
- ) {
66
- txs {
67
- amount
68
- block_height
69
- from
70
- id
71
- memo
72
- owner
73
- t
74
- tk
75
- status
76
- }
53
+ # findLedgerTXs(filterOptions: {byToFrom: "hive:${username}",byTypes: "deposit"}) {
54
+ # amount
55
+ # asset
56
+ # block_height
57
+ # from
58
+ # id
59
+ # owner
60
+ # timestamp
61
+ # tx_id
62
+ # type
63
+ # }
64
+ findTransaction(filterOptions: {byLedgerToFrom: "hive:${username}"}) {
65
+ anchr_height
66
+ anchr_index
67
+ anchr_opidx
68
+ anchr_ts
69
+ data
70
+ first_seen
71
+ id
72
+ ledger {
73
+ amount
74
+ asset
75
+ from
76
+ memo
77
+ params
78
+ to
79
+ type
77
80
  }
78
- findTransaction(filterOptions: {byAccount: "${username}"}) {
79
- txs {
80
- status
81
- id
82
- anchored_height
83
- data {
84
- action
85
- contract_id
86
- op
87
- payload
88
- }
89
- required_auths{value}
90
- }
81
+ nonce
82
+ rc_limit
83
+ required_auths
84
+ status
85
+ type
91
86
  }}
92
87
  `;
93
88
  return (yield fetchQuery(query)).data;
@@ -95,18 +90,37 @@ const fetchHistory = (username) => __awaiter(void 0, void 0, void 0, function* (
95
90
  const getOrganizedHistory = (username) => __awaiter(void 0, void 0, void 0, function* () {
96
91
  const history = yield fetchHistory(username);
97
92
  const organizedHistory = [
98
- ...history.findLedgerTXs.txs.map((e) => {
99
- e.type = vsc_1.VscHistoryType.TRANSFER;
100
- e.timestamp = blockHeightToTimestamp(e.block_height);
101
- return e;
102
- }),
103
- ...history.findTransaction.txs.map((e) => {
104
- e.type = vsc_1.VscHistoryType.CONTRACT_CALL;
105
- e.timestamp = blockHeightToTimestamp(e.anchored_height);
106
- return e;
107
- }),
93
+ // ...(history.findLedgerTXs || [])
94
+ // .map((e) => {
95
+ // return {
96
+ // from: e.from,
97
+ // to: e.owner,
98
+ // amount: e.amount,
99
+ // timestamp: new Date(e.timestamp + 'Z'),
100
+ // txId: e.id,
101
+ // asset: e.asset,
102
+ // status: VscStatus.CONFIRMED,
103
+ // type: VscHistoryType.DEPOSIT,
104
+ // };
105
+ // })
106
+ // .filter((e) => e.to === `hive:${username}`),
107
+ ...(history.findTransaction || [])
108
+ .map((e) => {
109
+ return {
110
+ from: e.data.from,
111
+ to: e.data.to,
112
+ amount: e.data.amount,
113
+ timestamp: e.first_seen,
114
+ txId: e.id,
115
+ memo: e.data.memo,
116
+ asset: e.data.asset,
117
+ status: e.status,
118
+ type: e.data.type,
119
+ };
120
+ })
121
+ .filter((e) => !(e.type === 'withdraw' && e.from !== `hive:${username}`)),
108
122
  ].sort((a, b) => {
109
- return b.timestamp.getTime() - a.timestamp.getTime();
123
+ return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
110
124
  });
111
125
  return organizedHistory;
112
126
  });
@@ -118,10 +132,16 @@ const blockHeightToTimestamp = (height) => {
118
132
  .toDate();
119
133
  };
120
134
  const getAddressFromDid = (did) => {
121
- const regex = new RegExp(':([a-zA-Z0-9]*)$');
135
+ const regex = new RegExp(':([a-zA-Z0-9.-]*)$');
122
136
  const matches = did.match(regex);
123
137
  return matches === null || matches === void 0 ? void 0 : matches[matches.length - 1];
124
138
  };
139
+ const getFormattedAddress = (address) => {
140
+ if (address.startsWith('hive:'))
141
+ return `@${getAddressFromDid(address)}`;
142
+ else
143
+ return format_utils_1.FormatUtils.shortenString(getAddressFromDid(address), 4);
144
+ };
125
145
  const fetchQuery = (query) => {
126
146
  return fetch(config_1.default.vsc.API_URL, {
127
147
  method: 'POST',
@@ -133,9 +153,83 @@ const fetchQuery = (query) => {
133
153
  }),
134
154
  }).then((res) => res.json());
135
155
  };
156
+ const getAccountBalance = (username) => __awaiter(void 0, void 0, void 0, function* () {
157
+ const query = `{
158
+ getAccountBalance(account: "hive:${username}") {
159
+ account
160
+ hbd
161
+ hive
162
+ hbd_savings
163
+ hbd_claim
164
+ hbd_modify
165
+ hbd_avg
166
+ block_height
167
+ hive_consensus
168
+ }
169
+ }`;
170
+ return (yield fetchQuery(query)).data.getAccountBalance;
171
+ });
172
+ const getWithdrawJson = (data, netId) => {
173
+ const JSON_ID = 'vsc.withdraw';
174
+ const json = {
175
+ net_id: data.netId || netId,
176
+ from: data.username.startsWith('hive:')
177
+ ? data.username
178
+ : `hive:${data.username}`,
179
+ to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`,
180
+ amount: data.amount,
181
+ asset: data.currency.toLowerCase(),
182
+ memo: data.memo,
183
+ };
184
+ return {
185
+ id: JSON_ID,
186
+ json,
187
+ };
188
+ };
189
+ const getTransferJson = (data, netId) => {
190
+ const JSON_ID = 'vsc.transfer';
191
+ const json = {
192
+ net_id: data.netId || netId,
193
+ from: data.username.startsWith('hive:')
194
+ ? data.username
195
+ : `hive:${data.username}`,
196
+ to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`,
197
+ amount: data.amount,
198
+ asset: data.currency.toLowerCase(),
199
+ memo: data.memo,
200
+ };
201
+ return {
202
+ id: JSON_ID,
203
+ json,
204
+ };
205
+ };
206
+ const getStakingJson = (data, netId) => {
207
+ const JSON_ID = data.operation === vsc_1.VscStakingOperation.STAKING
208
+ ? 'vsc.stake_hbd'
209
+ : 'vsc.unstake_hbd';
210
+ const json = {
211
+ net_id: data.netId || netId,
212
+ from: data.username.startsWith('hive:')
213
+ ? data.username
214
+ : `hive:${data.username}`,
215
+ to: data.to.startsWith('hive:') ? data.to : `hive:${data.to}`,
216
+ amount: data.amount,
217
+ asset: data.currency.toLowerCase(),
218
+ };
219
+ return {
220
+ id: JSON_ID,
221
+ json,
222
+ };
223
+ };
136
224
  exports.VscUtils = {
137
225
  checkStatus,
138
226
  waitForStatus,
139
227
  getOrganizedHistory,
140
228
  getAddressFromDid,
229
+ getAccountBalance,
230
+ blockHeightToTimestamp,
231
+ getFormattedAddress,
232
+ getWithdrawJson,
233
+ getTransferJson,
234
+ getStakingJson,
141
235
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hive-keychain-commons",
3
- "version": "1.7.1",
3
+ "version": "1.7.3",
4
4
  "description": "Platform-agnostic functions used in Hive Keychain mobile and extensions",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",