UNPKG

@trezor/connect

Version:

High-level javascript interface for Trezor hardware wallet.

98 lines 3.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BitcoinFeeLevels = void 0; const bigNumber_1 = require("@trezor/utils/lib/bigNumber"); const MiscFees_1 = require("../common/MiscFees"); const convertFeeRate = (fee, minFee) => { const feePerKB = new bigNumber_1.BigNumber(fee); if (feePerKB.isNaN() || feePerKB.lte('0')) return; const feePerB = feePerKB.div(1000); if (feePerB.lt(minFee)) return minFee.toString(); return feePerB.isInteger() ? feePerB.toString() : feePerB.toFixed(2); }; const fillGap = (from, step, size) => { const fill = []; for (let i = from + step; i <= from + size; i += step) { fill.push(i); } return fill; }; const findNearest = (requested, blocks) => { if (typeof blocks[requested] === 'string') return blocks[requested]; const len = blocks.length; let index = requested; while (typeof blocks[index] !== 'string' && index < len) { index++; } if (typeof blocks[index] === 'string') { return blocks[index]; } index = requested; while (typeof blocks[index] !== 'string' && index > 0) { index--; } return blocks[index]; }; const findLowest = (blocks) => blocks .slice(0) .reverse() .find(item => typeof item === 'string'); class BitcoinFeeLevels { coinInfo; levels; longTermFeeRate; blocks = []; constructor(coinInfo) { this.coinInfo = coinInfo; this.levels = coinInfo.defaultFees; } async load(blockchain) { let blocks = fillGap(0, 1, 10); if (this.levels.length > 1) { blocks = this.levels .map(l => l.blocks) .reduce((result, bl) => { if (result.length === 0) return result.concat([bl]); const from = result[result.length - 1]; const gap = bl - from; const incr = gap <= 30 ? 1 : 6; const fill = fillGap(from, incr, gap); return result.concat(fill); }, []); } const oneDayBlocks = 6 * 24; blocks.push(...fillGap(oneDayBlocks, oneDayBlocks / 2, oneDayBlocks * 6)); try { const response = await blockchain.estimateFee({ blocks }); response.forEach(({ feePerUnit }, index) => { this.blocks[blocks[index]] = convertFeeRate(feePerUnit || '0', this.coinInfo.minFee); }); this.levels.forEach(level => { const updatedValue = findNearest(level.blocks, this.blocks); if (typeof updatedValue === 'string') { level.blocks = this.blocks.indexOf(updatedValue); level.feePerUnit = updatedValue; } }); this.longTermFeeRate = findLowest(this.blocks); } catch { } return this.levels; } updateBitcoinCustomFee(feePerUnit) { this.levels = this.levels.filter(l => l.label !== 'custom'); const blocks = (0, MiscFees_1.findBlocksForFee)(feePerUnit, this.blocks); this.levels.push({ label: 'custom', feePerUnit, blocks, }); } } exports.BitcoinFeeLevels = BitcoinFeeLevels; //# sourceMappingURL=BitcoinFees.js.map