All files / src utils.ts

93.75% Statements 105/112
70.9% Branches 39/55
92.3% Functions 24/26
94.05% Lines 95/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 2286x 6x                   6x 6x 6x 6x     37x 37x 13x 12x     27x     36x 1152x 1152x 22x     36x       13x       13x 13x 13x 13x 1x       12x 28x 28x 1x   27x     12x       5x 5x 5x         37x       37x                           1x                   15x 15x 60x 54x   6x   15x               15x     13x 4x       9x 1x       8x             6x 26x 2x 28x   26x 26x                     6x 10x 11x 11x 2x   9x 1x 1x   8x         10x   8x           6x 8x     6x 22x     6x                   170x 86x     6x 1x 1x 1x 1x 13x 13x 1x 1x   13x 1x   13x 1x   13x 1x   13x 1x     1x       6x 6x 6x 6x 6x 6x 6x    
import { decode } from '@gandlaf21/bolt11-decode';
import { encodeBase64ToJson, encodeJsonToBase64 } from './base64.js';
import {
	AmountPreference,
	InvoiceData,
	MintKeys,
	Proof,
	Token,
	TokenEntry,
	TokenV2
} from './model/types/index.js';
import { TOKEN_PREFIX, TOKEN_VERSION } from './utils/Constants.js';
import { bytesToHex } from '@noble/curves/abstract/utils';
import { sha256 } from '@noble/hashes/sha256';
import { Buffer } from 'buffer/';
 
function splitAmount(value: number, amountPreference?: Array<AmountPreference>): Array<number> {
	const chunks: Array<number> = [];
	if (amountPreference) {
		chunks.push(...getPreference(value, amountPreference));
		value =
			value -
			chunks.reduce((curr, acc) => {
				return curr + acc;
			}, 0);
	}
	for (let i = 0; i < 32; i++) {
		const mask: number = 1 << i;
		if ((value & mask) !== 0) {
			chunks.push(Math.pow(2, i));
		}
	}
	return chunks;
}
 
function isPowerOfTwo(number: number) {
	return number && !(number & (number - 1));
}
 
function getPreference(amount: number, preferredAmounts: Array<AmountPreference>): Array<number> {
	const chunks: Array<number> = [];
	let accumulator = 0;
	preferredAmounts.forEach((pa) => {
		if (!isPowerOfTwo(pa.amount)) {
			throw new Error(
				'Provided amount preferences contain non-power-of-2 numbers. Use only ^2 numbers'
			);
		}
		for (let i = 1; i <= pa.count; i++) {
			accumulator += pa.amount;
			if (accumulator > amount) {
				return;
			}
			chunks.push(pa.amount);
		}
	});
	return chunks;
}
 
function getDefaultAmountPreference(amount: number): Array<AmountPreference> {
	const amounts = splitAmount(amount);
	return amounts.map((a) => {
		return { amount: a, count: 1 };
	});
}
 
function bytesToNumber(bytes: Uint8Array): bigint {
	return hexToNumber(bytesToHex(bytes));
}
 
function hexToNumber(hex: string): bigint {
	return BigInt(`0x${hex}`);
}
 
//used for json serialization
function bigIntStringify<T>(_key: unknown, value: T) {
	return typeof value === 'bigint' ? value.toString() : value;
}
 
/**
 * Helper function to encode a v3 cashu token
 * @param token
 * @returns
 */
function getEncodedToken(token: Token): string {
	return TOKEN_PREFIX + TOKEN_VERSION + encodeJsonToBase64(token);
}
 
/**
 * Helper function to decode cashu tokens into object
 * @param token an encoded cashu token (cashuAey...)
 * @returns cashu token object
 */
function getDecodedToken(token: string): Token {
	// remove prefixes
	const uriPrefixes = ['web+cashu://', 'cashu://', 'cashu:', 'cashuA'];
	uriPrefixes.forEach((prefix) => {
		if (!token.startsWith(prefix)) {
			return;
		}
		token = token.slice(prefix.length);
	});
	return handleTokens(token);
}
 
/**
 * @param token
 * @returns
 */
function handleTokens(token: string): Token {
	const obj = encodeBase64ToJson<TokenV2 | Array<Proof> | Token>(token);
 
	// check if v3
	if ('token' in obj) {
		return obj;
	}
 
	// check if v1
	if (Array.isArray(obj)) {
		return { token: [{ proofs: obj, mint: '' }] };
	}
 
	// if v2 token return v3 format
	return { token: [{ proofs: obj.proofs, mint: obj?.mints[0]?.url ?? '' }] };
}
/**
 * Returns the keyset id of a set of keys
 * @param keys keys object to derive keyset id from
 * @returns
 */
export function deriveKeysetId(keys: MintKeys) {
	const pubkeysConcat = Object.entries(keys)
		.sort((a, b) => +a[0] - +b[0])
		.map(([, pubKey]) => pubKey)
		.join('');
	const hash = sha256(new TextEncoder().encode(pubkeysConcat));
	return Buffer.from(hash).toString('base64').slice(0, 12);
}
/**
 * merge proofs from same mint,
 * removes TokenEntrys with no proofs or no mint field
 * and sorts proofs by id
 *
 * @export
 * @param {Token} token
 * @return {*}  {Token}
 */
export function cleanToken(token: Token): Token {
	const tokenEntryMap: { [key: string]: TokenEntry } = {};
	for (const tokenEntry of token.token) {
		if (!tokenEntry?.proofs?.length || !tokenEntry?.mint) {
			continue;
		}
		if (tokenEntryMap[tokenEntry.mint]) {
			tokenEntryMap[tokenEntry.mint].proofs.push(...[...tokenEntry.proofs]);
			continue;
		}
		tokenEntryMap[tokenEntry.mint] = {
			mint: tokenEntry.mint,
			proofs: [...tokenEntry.proofs]
		};
	}
	return {
		memo: token?.memo,
		token: Object.values(tokenEntryMap).map((x) => ({
			...x,
			proofs: sortProofsById(x.proofs)
		}))
	};
}
export function sortProofsById(proofs: Array<Proof>) {
	return proofs.sort((a, b) => a.id.localeCompare(b.id));
}
 
export function isObj(v: unknown): v is object {
	return typeof v === 'object';
}
 
export function checkResponse(data: { error?: string; detail?: string }) {
	Iif (!isObj(data)) return;
	Iif ('error' in data && data.error) {
		throw new Error(data.error);
	}
	Iif ('detail' in data && data.detail) {
		throw new Error(data.detail);
	}
}
 
export function joinUrls(...parts: Array<string>): string {
	return parts.map((part) => part.replace(/(^\/+|\/+$)/g, '')).join('/');
}
 
export function decodeInvoice(bolt11Invoice: string): InvoiceData {
	const invoiceData: InvoiceData = {} as InvoiceData;
	const decodeResult = decode(bolt11Invoice);
	invoiceData.paymentRequest = decodeResult.paymentRequest;
	for (let i = 0; i < decodeResult.sections.length; i++) {
		const decodedSection = decodeResult.sections[i];
		if (decodedSection.name === 'amount') {
			invoiceData.amountInSats = Number(decodedSection.value) / 1000;
			invoiceData.amountInMSats = Number(decodedSection.value);
		}
		if (decodedSection.name === 'timestamp') {
			invoiceData.timestamp = decodedSection.value;
		}
		if (decodedSection.name === 'description') {
			invoiceData.memo = decodedSection.value;
		}
		if (decodedSection.name === 'expiry') {
			invoiceData.expiry = decodedSection.value;
		}
		if (decodedSection.name === 'payment_hash') {
			invoiceData.paymentHash = decodedSection.value.toString('hex');
		}
	}
	return invoiceData;
}
 
export {
	bigIntStringify,
	bytesToNumber,
	getDecodedToken,
	getEncodedToken,
	hexToNumber,
	splitAmount,
	getDefaultAmountPreference
};