@cityofzion/blockchain-service 1.18.2 → 1.19.0

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.
@@ -0,0 +1,4 @@
1
+ export declare class BSError extends Error {
2
+ readonly code: string;
3
+ constructor(message: string, code: string);
4
+ }
package/dist/error.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BSError = void 0;
4
+ class BSError extends Error {
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.code = code;
8
+ this.name = 'BSError';
9
+ }
10
+ }
11
+ exports.BSError = BSError;
@@ -1,11 +1,11 @@
1
- import { Account, BlockchainService, BSCalculableFee, BSClaimable, BSWithExplorerService, BSWithLedger, BSWithNameService, BSWithNft, UntilIndexRecord } from './interfaces';
1
+ import { Account, BlockchainService, BSCalculableFee, BSClaimable, BSWithExplorerService, BSWithLedger, BSWithNameService, BSWithNft, IBSWithNeo3NeoXBridge, UntilIndexRecord } from './interfaces';
2
2
  export declare function hasNameService<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSWithNameService;
3
3
  export declare function isClaimable<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSClaimable<BSName>;
4
4
  export declare function isCalculableFee<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSCalculableFee<BSName>;
5
5
  export declare function hasNft<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSWithNft;
6
6
  export declare function hasExplorerService<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSWithExplorerService;
7
7
  export declare function hasLedger<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & BSWithLedger<BSName>;
8
- export declare function wait(ms: number): Promise<unknown>;
8
+ export declare function hasNeo3NeoXBridge<BSName extends string = string>(service: BlockchainService<BSName>): service is BlockchainService<BSName> & IBSWithNeo3NeoXBridge<BSName>;
9
9
  /**
10
10
  * @deprecated use `waitForAccountTransaction` instead
11
11
  */
@@ -19,9 +19,3 @@ export declare function waitForAccountTransaction<BSName extends string = string
19
19
  export declare function fetchAccounts<BSName extends string = string>(blockchainServices: BlockchainService<BSName>, initialIndex: number, getAccountCallback: (service: BlockchainService<BSName>, index: number) => Promise<Account<BSName>>): Promise<Account<BSName>[]>;
20
20
  export declare function generateAccount<BSName extends string = string>(blockchainServices: BlockchainService<BSName>, initialIndex: number, untilIndex: number, getAccountCallback: (service: BlockchainService<BSName>, index: number) => Promise<Account<BSName>>): Promise<Account<BSName>[]>;
21
21
  export declare function generateAccountForBlockchainService<BSName extends string = string>(blockchainServices: BlockchainService<BSName>[], getAccountCallback: (service: BlockchainService<BSName>, index: number) => Promise<Account<BSName>>, untilIndexByBlockchainService?: UntilIndexRecord<BSName>): Promise<Map<BSName, Account<BSName>[]>>;
22
- type NormalizedHashOptions = {
23
- lowercase?: boolean;
24
- };
25
- export declare function normalizeHash(hash: string, options?: NormalizedHashOptions): string;
26
- export declare function denormalizeHash(hash: string): string;
27
- export {};
package/dist/functions.js CHANGED
@@ -9,7 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.denormalizeHash = exports.normalizeHash = exports.generateAccountForBlockchainService = exports.generateAccount = exports.fetchAccounts = exports.waitForAccountTransaction = exports.waitForTransaction = exports.wait = exports.hasLedger = exports.hasExplorerService = exports.hasNft = exports.isCalculableFee = exports.isClaimable = exports.hasNameService = void 0;
12
+ exports.generateAccountForBlockchainService = exports.generateAccount = exports.fetchAccounts = exports.waitForAccountTransaction = exports.waitForTransaction = exports.hasNeo3NeoXBridge = exports.hasLedger = exports.hasExplorerService = exports.hasNft = exports.isCalculableFee = exports.isClaimable = exports.hasNameService = void 0;
13
+ const BSUtilsHelper_1 = require("./helpers/BSUtilsHelper");
13
14
  function hasNameService(service) {
14
15
  return 'resolveNameServiceDomain' in service && 'validateNameServiceDomainFormat' in service;
15
16
  }
@@ -34,10 +35,10 @@ function hasLedger(service) {
34
35
  return 'ledgerService' in service;
35
36
  }
36
37
  exports.hasLedger = hasLedger;
37
- function wait(ms) {
38
- return new Promise(resolve => setTimeout(resolve, ms));
38
+ function hasNeo3NeoXBridge(service) {
39
+ return 'neo3NeoXBridgeService' in service;
39
40
  }
40
- exports.wait = wait;
41
+ exports.hasNeo3NeoXBridge = hasNeo3NeoXBridge;
41
42
  /**
42
43
  * @deprecated use `waitForAccountTransaction` instead
43
44
  */
@@ -55,7 +56,7 @@ function waitForTransaction(service, txId) {
55
56
  // Empty block
56
57
  }
57
58
  attempts++;
58
- yield wait(waitMs);
59
+ yield BSUtilsHelper_1.BSUtilsHelper.wait(waitMs);
59
60
  } while (attempts < maxAttempts);
60
61
  return false;
61
62
  });
@@ -66,7 +67,7 @@ function waitForAccountTransaction(params) {
66
67
  const { address, maxAttempts = 10, service, txId } = params;
67
68
  let attempts = 1;
68
69
  do {
69
- yield wait(60000);
70
+ yield BSUtilsHelper_1.BSUtilsHelper.wait(60000);
70
71
  try {
71
72
  const response = yield service.blockchainDataService.getTransactionsByAddress({ address });
72
73
  const isTransactionConfirmed = response.transactions.some(transaction => transaction.hash === txId);
@@ -140,15 +141,3 @@ function generateAccountForBlockchainService(blockchainServices, getAccountCallb
140
141
  });
141
142
  }
142
143
  exports.generateAccountForBlockchainService = generateAccountForBlockchainService;
143
- function normalizeHash(hash, options) {
144
- const { lowercase = true } = options !== null && options !== void 0 ? options : {};
145
- hash = hash.replace('0x', '');
146
- if (lowercase)
147
- hash = hash.toLowerCase();
148
- return hash;
149
- }
150
- exports.normalizeHash = normalizeHash;
151
- function denormalizeHash(hash) {
152
- return hash.startsWith('0x') ? hash : `0x${hash}`;
153
- }
154
- exports.denormalizeHash = denormalizeHash;
@@ -0,0 +1,11 @@
1
+ import BigNumber from 'bignumber.js';
2
+ type FormatNumberOptions = {
3
+ decimals?: number;
4
+ };
5
+ export declare class BSBigNumberHelper {
6
+ static toDecimals(value: BigNumber, decimals?: number): string;
7
+ static fromNumber(value: string | number): BigNumber;
8
+ static fromDecimals(value: string | number, decimals?: number): BigNumber;
9
+ static format(value?: string | number | BigNumber, options?: FormatNumberOptions): string;
10
+ }
11
+ export {};
@@ -0,0 +1,41 @@
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.BSBigNumberHelper = void 0;
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ class BSBigNumberHelper {
9
+ static toDecimals(value, decimals = 0) {
10
+ return new bignumber_js_1.default(value).shiftedBy(decimals).toString();
11
+ }
12
+ static fromNumber(value) {
13
+ return new bignumber_js_1.default(value);
14
+ }
15
+ static fromDecimals(value, decimals = 0) {
16
+ return new bignumber_js_1.default(value).shiftedBy(-decimals);
17
+ }
18
+ static format(value, options) {
19
+ const { decimals = 0 } = options || {};
20
+ if (!value)
21
+ return '0';
22
+ if (typeof value === 'string') {
23
+ value = value.replace(/,|\.\.|\.,/g, '.').replace(/^([^.]*\.)(.*)$/, function (_a, b, c) {
24
+ return b + c.replace(/\./g, '');
25
+ });
26
+ }
27
+ try {
28
+ const bigValue = new bignumber_js_1.default(value);
29
+ if (bigValue.isNaN()) {
30
+ return '0';
31
+ }
32
+ const formattedValue = bigValue.decimalPlaces(decimals, bignumber_js_1.default.ROUND_DOWN);
33
+ return formattedValue.toFixed();
34
+ }
35
+ catch (error) {
36
+ console.error('Invalid value provided to format:', value);
37
+ return '0';
38
+ }
39
+ }
40
+ }
41
+ exports.BSBigNumberHelper = BSBigNumberHelper;
@@ -0,0 +1,21 @@
1
+ import { Token } from '../interfaces';
2
+ type TPredicateToken = {
3
+ hash: string;
4
+ symbol?: string;
5
+ };
6
+ export declare class BSTokenHelper {
7
+ static predicate({ hash, symbol }: TPredicateToken): (params: TPredicateToken) => boolean;
8
+ static predicateByHash(tokenOrHash: string | {
9
+ hash: string;
10
+ }): (params: string | {
11
+ hash: string;
12
+ }) => boolean;
13
+ static predicateBySymbol(tokenOrSymbol: string | {
14
+ symbol: string;
15
+ }): (params: string | {
16
+ symbol: string;
17
+ }) => boolean;
18
+ static normalizeToken<T extends Token | Token[]>(token: T): T;
19
+ static normalizeHash(hash: string): string;
20
+ }
21
+ export {};
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BSTokenHelper = void 0;
4
+ class BSTokenHelper {
5
+ static predicate({ hash, symbol }) {
6
+ const normalizedHash = this.normalizeHash(hash);
7
+ return (params) => {
8
+ if (normalizedHash === this.normalizeHash(params.hash))
9
+ return true;
10
+ if (symbol && params.symbol && symbol.toLowerCase() === params.symbol.toLowerCase())
11
+ return true;
12
+ return false;
13
+ };
14
+ }
15
+ static predicateByHash(tokenOrHash) {
16
+ const hash = typeof tokenOrHash === 'string' ? tokenOrHash : tokenOrHash.hash;
17
+ const normalizedHash = this.normalizeHash(hash);
18
+ return (params) => normalizedHash === this.normalizeHash(typeof params === 'string' ? params : params.hash);
19
+ }
20
+ static predicateBySymbol(tokenOrSymbol) {
21
+ const symbol = typeof tokenOrSymbol === 'string' ? tokenOrSymbol : tokenOrSymbol.symbol;
22
+ const lowercaseSymbol = symbol.toLowerCase();
23
+ return (params) => {
24
+ const tokenSymbol = typeof params === 'string' ? params : params.symbol;
25
+ const lowercaseTokenSymbol = tokenSymbol.toLowerCase();
26
+ return lowercaseSymbol === lowercaseTokenSymbol;
27
+ };
28
+ }
29
+ static normalizeToken(token) {
30
+ if (Array.isArray(token)) {
31
+ return token.map(item => (Object.assign(Object.assign({}, item), { hash: this.normalizeHash(item.hash) })));
32
+ }
33
+ return Object.assign(Object.assign({}, token), { hash: this.normalizeHash(token.hash) });
34
+ }
35
+ static normalizeHash(hash) {
36
+ return hash.startsWith('0x') ? hash : `0x${hash}`;
37
+ }
38
+ }
39
+ exports.BSTokenHelper = BSTokenHelper;
@@ -0,0 +1,10 @@
1
+ type RetryOptions = {
2
+ retries?: number;
3
+ delay?: number;
4
+ shouldRetry?: (error: any) => boolean;
5
+ };
6
+ export declare class BSUtilsHelper {
7
+ static wait(ms: number): Promise<unknown>;
8
+ static retry<T = any>(callback: () => Promise<T>, options?: RetryOptions): Promise<T>;
9
+ }
10
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BSUtilsHelper = void 0;
13
+ class BSUtilsHelper {
14
+ static wait(ms) {
15
+ return new Promise(resolve => setTimeout(resolve, ms));
16
+ }
17
+ static retry(callback, options) {
18
+ const { retries = 50, delay = 100, shouldRetry } = options || {};
19
+ // eslint-disable-next-line no-async-promise-executor
20
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
21
+ for (let i = 0; i < retries; i++) {
22
+ try {
23
+ const result = yield callback();
24
+ return resolve(result);
25
+ }
26
+ catch (error) {
27
+ if (shouldRetry && !shouldRetry(error)) {
28
+ return reject(error);
29
+ }
30
+ }
31
+ yield this.wait(delay);
32
+ }
33
+ return reject(new Error('timeout'));
34
+ }));
35
+ }
36
+ }
37
+ exports.BSUtilsHelper = BSUtilsHelper;
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  export * from './constants/BSCommonConstants';
2
2
  export * from './helpers/BSFullTransactionsByAddressHelper';
3
3
  export * from './helpers/BSPromisesHelper';
4
- export * from './helpers/BSNumberHelper';
4
+ export * from './helpers/BSBigNumberHelper';
5
+ export * from './helpers/BSTokenHelper';
6
+ export * from './helpers/BSUtilsHelper';
5
7
  export * from './services/exchange-data/CryptoCompareEDS';
6
8
  export * from './services/exchange-data/FlamingoForthewinEDS';
7
9
  export * from './BSAggregator';
8
10
  export * from './functions';
9
11
  export * from './interfaces';
12
+ export * from './error';
package/dist/index.js CHANGED
@@ -17,9 +17,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./constants/BSCommonConstants"), exports);
18
18
  __exportStar(require("./helpers/BSFullTransactionsByAddressHelper"), exports);
19
19
  __exportStar(require("./helpers/BSPromisesHelper"), exports);
20
- __exportStar(require("./helpers/BSNumberHelper"), exports);
20
+ __exportStar(require("./helpers/BSBigNumberHelper"), exports);
21
+ __exportStar(require("./helpers/BSTokenHelper"), exports);
22
+ __exportStar(require("./helpers/BSUtilsHelper"), exports);
21
23
  __exportStar(require("./services/exchange-data/CryptoCompareEDS"), exports);
22
24
  __exportStar(require("./services/exchange-data/FlamingoForthewinEDS"), exports);
23
25
  __exportStar(require("./BSAggregator"), exports);
24
26
  __exportStar(require("./functions"), exports);
25
27
  __exportStar(require("./interfaces"), exports);
28
+ __exportStar(require("./error"), exports);
@@ -76,6 +76,9 @@ export interface BSWithLedger<BSName extends string = string> {
76
76
  ledgerService: LedgerService<BSName>;
77
77
  generateAccountFromPublicKey(publicKey: string): Account<BSName>;
78
78
  }
79
+ export interface IBSWithNeo3NeoXBridge<BSName extends string = string> {
80
+ neo3NeoXBridgeService: INeo3NeoXBridgeService<BSName>;
81
+ }
79
82
  export type TransactionNotificationTypedResponse = {
80
83
  type: string;
81
84
  value?: string;
@@ -359,3 +362,37 @@ export interface SwapService<BSName extends string = string> {
359
362
  swap(): Promise<SwapServiceSwapResult>;
360
363
  calculateFee(): Promise<string>;
361
364
  }
365
+ export type TNeo3NeoXBridgeServiceCalculateMaxAmountParams<BSName extends string> = {
366
+ account: Account<BSName>;
367
+ receiverAddress: string;
368
+ token: Token;
369
+ balances: BalanceResponse[];
370
+ };
371
+ export type TNeo3NeoXBridgeServiceValidatedInputs = {
372
+ amount: string;
373
+ receiveAmount: string;
374
+ token: Token;
375
+ };
376
+ export type TNeo3NeoXBridgeServiceBridgeParam<BSName extends string> = {
377
+ account: Account<BSName>;
378
+ receiverAddress: string;
379
+ validatedInputs: TNeo3NeoXBridgeServiceValidatedInputs;
380
+ };
381
+ export type TNeo3NeoXBridgeServiceValidateInputParams<BSName extends string> = {
382
+ account: Account<BSName>;
383
+ receiverAddress: string;
384
+ amount: string;
385
+ token: Token;
386
+ balances: BalanceResponse[];
387
+ };
388
+ export type TNeo3NeoXBridgeServiceWaitParams = {
389
+ transactionHash: string;
390
+ validatedInputs: TNeo3NeoXBridgeServiceValidatedInputs;
391
+ };
392
+ export interface INeo3NeoXBridgeService<BSName extends string = string> {
393
+ calculateMaxAmount(params: TNeo3NeoXBridgeServiceCalculateMaxAmountParams<BSName>): Promise<string>;
394
+ calculateFee(params: TNeo3NeoXBridgeServiceBridgeParam<BSName>): Promise<string>;
395
+ bridge(params: TNeo3NeoXBridgeServiceBridgeParam<BSName>): Promise<string>;
396
+ validateInputs(params: TNeo3NeoXBridgeServiceValidateInputParams<BSName>): Promise<TNeo3NeoXBridgeServiceValidatedInputs>;
397
+ wait(params: TNeo3NeoXBridgeServiceWaitParams): Promise<boolean>;
398
+ }
@@ -4,5 +4,4 @@ export declare class FlamingoForthewinEDS extends CryptoCompareEDS implements Ex
4
4
  #private;
5
5
  constructor();
6
6
  getTokenPrices({ tokens }: GetTokenPricesParams): Promise<TokenPricesResponse[]>;
7
- private predicateToken;
8
7
  }
@@ -21,7 +21,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.FlamingoForthewinEDS = void 0;
22
22
  const axios_1 = __importDefault(require("axios"));
23
23
  const CryptoCompareEDS_1 = require("./CryptoCompareEDS");
24
- const functions_1 = require("../../functions");
24
+ const BSTokenHelper_1 = require("../../helpers/BSTokenHelper");
25
25
  class FlamingoForthewinEDS extends CryptoCompareEDS_1.CryptoCompareEDS {
26
26
  constructor() {
27
27
  super();
@@ -33,13 +33,13 @@ class FlamingoForthewinEDS extends CryptoCompareEDS_1.CryptoCompareEDS {
33
33
  const { data: flamingoData } = yield __classPrivateFieldGet(this, _FlamingoForthewinEDS_flamingoAxiosInstance, "f").get('/live-data/prices/latest');
34
34
  const prices = [];
35
35
  const neoToken = tokens.find(({ symbol }) => symbol === 'NEO');
36
- if (neoToken && !flamingoData.find(this.predicateToken(neoToken)))
36
+ if (neoToken && !flamingoData.find(BSTokenHelper_1.BSTokenHelper.predicate(neoToken)))
37
37
  flamingoData.forEach(item => {
38
38
  if (item.symbol === 'bNEO')
39
39
  flamingoData.push(Object.assign(Object.assign({}, item), { symbol: neoToken.symbol, hash: neoToken.hash }));
40
40
  });
41
41
  flamingoData.forEach(item => {
42
- const token = tokens.find(this.predicateToken(item));
42
+ const token = tokens.find(BSTokenHelper_1.BSTokenHelper.predicate(item));
43
43
  if (!token)
44
44
  return;
45
45
  prices.push({ usdPrice: item.usd_price, token });
@@ -47,10 +47,10 @@ class FlamingoForthewinEDS extends CryptoCompareEDS_1.CryptoCompareEDS {
47
47
  if (tokens.length > prices.length) {
48
48
  const { data: forthewinData } = yield __classPrivateFieldGet(this, _FlamingoForthewinEDS_forthewinAxiosInstance, "f").get('/mainnet/prices');
49
49
  Object.entries(forthewinData).forEach(([hash, usdPrice]) => {
50
- const hasPrice = !!prices.find(({ token }) => this.predicateToken({ hash })(token));
50
+ const hasPrice = !!prices.find(({ token }) => BSTokenHelper_1.BSTokenHelper.predicate({ hash })(token));
51
51
  if (hasPrice)
52
52
  return;
53
- const foundToken = tokens.find(this.predicateToken({ hash }));
53
+ const foundToken = tokens.find(BSTokenHelper_1.BSTokenHelper.predicate({ hash }));
54
54
  if (!foundToken)
55
55
  return;
56
56
  prices.push({ usdPrice, token: foundToken });
@@ -59,10 +59,6 @@ class FlamingoForthewinEDS extends CryptoCompareEDS_1.CryptoCompareEDS {
59
59
  return prices;
60
60
  });
61
61
  }
62
- predicateToken({ hash, symbol }) {
63
- const normalizedHash = (0, functions_1.normalizeHash)(hash);
64
- return (params) => normalizedHash === (0, functions_1.normalizeHash)(params.hash) || (!!symbol && !!params.symbol && symbol === params.symbol);
65
- }
66
62
  }
67
63
  exports.FlamingoForthewinEDS = FlamingoForthewinEDS;
68
64
  _FlamingoForthewinEDS_flamingoAxiosInstance = new WeakMap(), _FlamingoForthewinEDS_forthewinAxiosInstance = new WeakMap();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cityofzion/blockchain-service",
3
- "version": "1.18.2",
3
+ "version": "1.19.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "repository": "https://github.com/CityOfZion/blockchain-services",
@@ -25,7 +25,8 @@
25
25
  "dependencies": {
26
26
  "@ledgerhq/hw-transport": "~6.30.5",
27
27
  "axios": "1.8.2",
28
- "date-fns": "~4.1.0"
28
+ "date-fns": "~4.1.0",
29
+ "bignumber.js": "~9.3.0"
29
30
  },
30
31
  "scripts": {
31
32
  "build": "tsc --project tsconfig.build.json",
@@ -1,16 +0,0 @@
1
- type FormatNumberOptions = {
2
- decimals?: number;
3
- shouldRemoveLeadingZero?: boolean;
4
- shouldRemoveTrailingZero?: boolean;
5
- };
6
- export declare class BSNumberHelper {
7
- static readonly sciNotationRegex: RegExp;
8
- static countDecimals(value: string | number): number;
9
- static sanitizeCommasAndDotsInNumber(value: string): string;
10
- static isSciNotationValue(value: string): boolean;
11
- static convertSciNotationValueToString(value: number): string;
12
- static removeLeadingZero(value: string): string;
13
- static removeTrailingZero(value: string): string;
14
- static formatNumber(value?: string | number, options?: FormatNumberOptions): string;
15
- }
16
- export {};
@@ -1,75 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BSNumberHelper = void 0;
4
- class BSNumberHelper {
5
- static countDecimals(value) {
6
- var _b;
7
- const [, decimals] = value.toString().split('.');
8
- return (_b = decimals === null || decimals === void 0 ? void 0 : decimals.length) !== null && _b !== void 0 ? _b : 0;
9
- }
10
- static sanitizeCommasAndDotsInNumber(value) {
11
- let newValue = value.replace(/,|\.\.|\.,|,,/g, '.');
12
- const parts = newValue.split('.');
13
- if (parts.length > 2)
14
- newValue = `${parts[0]}.${parts.slice(1).join('')}`;
15
- return newValue;
16
- }
17
- static isSciNotationValue(value) {
18
- return BSNumberHelper.sciNotationRegex.test(value);
19
- }
20
- static convertSciNotationValueToString(value) {
21
- if (Math.abs(value) < 1.0) {
22
- const parts = value.toString().split('e-');
23
- const hasNegativeExponent = parts.length === 2;
24
- if (hasNegativeExponent) {
25
- const negativeExponent = parseInt(parts[1], 10);
26
- value *= Math.pow(10, negativeExponent - 1);
27
- return `0.${'0'.repeat(negativeExponent - 1)}${value.toString().substring(2)}`;
28
- }
29
- }
30
- return value.toString();
31
- }
32
- static removeLeadingZero(value) {
33
- return value.replace(/^0+(?!\.)/, '') || '0';
34
- }
35
- static removeTrailingZero(value) {
36
- return value.replace(/(\.\d*?[1-9])0+$/g, '$1').replace(/\.0+$/, '');
37
- }
38
- static formatNumber(value, options) {
39
- if (!value)
40
- return '0';
41
- const { decimals = 0, shouldRemoveLeadingZero = true, shouldRemoveTrailingZero = true } = options !== null && options !== void 0 ? options : {};
42
- let newValue = typeof value === 'number' ? value.toString() : value.trim();
43
- newValue = BSNumberHelper.sanitizeCommasAndDotsInNumber(newValue);
44
- const newValueAsNumber = Number(newValue);
45
- if (isNaN(newValueAsNumber))
46
- return '0';
47
- const isNegativeValue = newValue.startsWith('-');
48
- if (BSNumberHelper.isSciNotationValue(newValue))
49
- newValue = BSNumberHelper.convertSciNotationValueToString(newValueAsNumber);
50
- if (decimals === 0)
51
- newValue = newValue.split('.')[0];
52
- else {
53
- newValue = newValue.replace(/[^\d.]/g, '');
54
- const countedDecimals = BSNumberHelper.countDecimals(newValue);
55
- if (countedDecimals > decimals)
56
- newValue = newValue.slice(0, newValue.length - countedDecimals + decimals);
57
- }
58
- newValue = newValue.replace(/\s|-/g, '').replace(/^([^.]*\.)(.*)$/, (_a, b, c) => b + c.replace(/\./g, ''));
59
- if (shouldRemoveLeadingZero)
60
- newValue = BSNumberHelper.removeLeadingZero(newValue);
61
- if (shouldRemoveTrailingZero)
62
- newValue = BSNumberHelper.removeTrailingZero(newValue);
63
- if (newValue.startsWith('.'))
64
- newValue = `0${newValue}`;
65
- if (newValue.endsWith('.'))
66
- newValue = newValue.slice(0, newValue.length - 1);
67
- if (!newValue)
68
- newValue = '0';
69
- if (newValue !== '0' && isNegativeValue)
70
- newValue = `-${newValue}`;
71
- return newValue;
72
- }
73
- }
74
- exports.BSNumberHelper = BSNumberHelper;
75
- BSNumberHelper.sciNotationRegex = /^[+-]?\d+(\.\d+)?e[+-]?\d+$/i;