import test, { Locator, Page, TestInfo, expect } from '@playwright/test'; import { IntlMessageFormat } from 'intl-messageformat'; import { readdirSync } from 'node:fs'; import path from 'node:path'; import { formatCompactCryptoAmount, isMoneyLikeToken } from '@suite-common/formatters'; import { validJws } from '@suite-common/message-system/src/__fixtures__/messageSystemActions'; import { getAccountDecimals } from '@suite-common/wallet-utils'; import { BigNumber, localizeNumber, splitStringEveryNCharacters } from '@trezor/utils'; import { PlaywrightTarget } from './testExtends/suiteTestOptions'; import { PercentageOfBalanceParams } from './types'; export const isDesktopProject = (target: PlaywrightTarget) => target === PlaywrightTarget.Desktop; export const isWebProject = (target: PlaywrightTarget) => target === PlaywrightTarget.Web; export const getUrl = (testInfo: TestInfo, target: PlaywrightTarget) => { const electronApiURL = 'file:///'; const apiURL = isDesktopProject(target) ? electronApiURL : testInfo.project.use.baseURL; if (!apiURL) { throw new Error('apiURL is not defined'); } return apiURL; }; // Wraps whole page object methods with test.step export function step(stepName?: string) { /* eslint-disable @typescript-eslint/no-unsafe-function-type */ return function decorator(target: Function, context: ClassMethodDecoratorContext) { return function replacementMethod(this: any, ...args: any) { const result = target.call(this, ...args); // Only wrap async results in test.step. Wrapping synchronous methods could introduce // race conditions, so we return their result untouched. if (result instanceof Promise) { const name = stepName || `${this.constructor.name + '.' + (context.name as string)}`; const params = args.map((arg: any) => JSON.stringify(arg)).join(', '); // Serialize arguments return test.step(`${name}(${params})`, async () => await result); } return result; }; }; /* eslint-enable @typescript-eslint/no-unsafe-function-type */ } export const formatAddress = (address: string) => splitStringEveryNCharacters(address, 4).join(' '); const REGEXP_ADDRESS_CHUNKS = /((?:\S+\s){3}\S+)\s/g; const EVM_ADDRESS_PREFIX = '0x'; export const DEVICE_RENDERED_EVM_INDENT = ' '; export const T3T1_FIRST_PAGE_KEY_LENGTH = 122; export const formatEvmAddress = (address: string) => { if (!address.startsWith(EVM_ADDRESS_PREFIX)) { return formatAddress(address); } const spacedBody = splitStringEveryNCharacters(address.slice(2), 4).join(' '); if (!spacedBody) { return address; } return `${DEVICE_RENDERED_EVM_INDENT}${EVM_ADDRESS_PREFIX} ${spacedBody}`; }; export const formatAddressWithNewlines = (address: string) => formatEvmAddress(address).replace(REGEXP_ADDRESS_CHUNKS, '$1\n'); // This overrides any auto fixture in tests that opt out of it; the skipped value is undefined, so // consumers of an optional fixture must guard against it (e.g. watcher?.stop()). /* eslint-disable react-hooks/rules-of-hooks */ export async function skipFixture({}, use: (fixture: T | undefined) => Promise) { await use(undefined); } /* eslint-enable react-hooks/rules-of-hooks */ export const getVideoPath = (videoFolder: string): string | false => { const videoFilenames = readdirSync(videoFolder).filter(file => file.endsWith('.webm')); if (videoFilenames.length < 1) { console.error( `Test teardown error: No test video files found in the output directory: ${videoFolder}`, ); return false; } if (videoFilenames.length > 1) { console.warn( `Test teardown warning: Multiple test video files found in the output directory: ${videoFilenames}.\nUsing the first one: ${videoFilenames[0]}`, ); } return path.join(videoFolder, videoFilenames[0] ?? ''); }; type CompactAmountOptions = { /** * The `decimals` the token states, as the app passes to `FormattedCryptoAmount`. Omit for a * network coin. Six of them (USDC, USDT) make a token read as money: two decimals and a * `<0.01` dust limit, rather than five and `<0.00001`. */ tokenDecimals?: number; }; /** * The amount as a compact surface shows it, by way of the formatter the app itself uses, so that * dust, millions, zero and stablecoins are covered rather than approximated here. * * Accepts a grouped value (`1,234.5`), which is what the rest of this file produces and what * `BigNumber` would otherwise read as NaN. */ export const toCompactAmount = (value: string, { tokenDecimals }: CompactAmountOptions = {}) => { const ungroupedValue = value.replace(/,/g, ''); if (!new BigNumber(ungroupedValue).isFinite()) { throw new Error(`Cannot compact "${value}": not a finite number.`); } return formatCompactCryptoAmount({ value: ungroupedValue, locale: 'en-US', isMoneyLike: isMoneyLikeToken(tokenDecimals), }); }; /** * As {@link toCompactAmount}, for a value that arrives with its symbol attached: `"1.2009 SOL"`. */ export const toCompactAmountWithSymbol = ( amountWithSymbol: string, options?: CompactAmountOptions, ) => { const [value, ...symbol] = amountWithSymbol.split(' '); if (value === undefined) { throw new Error(`Cannot compact an empty amount: "${amountWithSymbol}"`); } return [toCompactAmount(value, options), ...symbol].join(' '); }; export const calculatePercentageOfBalance = (params: PercentageOfBalanceParams) => { const maxDecimals = getAccountDecimals(params.symbol); const exactFraction = BigNumber(params.balance).times(params.percentage).div(100); // The form rounds a fraction of the balance to the coin's precision, while `localizeNumber` // truncates, so round before handing it over. const fraction = maxDecimals === undefined ? exactFraction : exactFraction.decimalPlaces(maxDecimals, BigNumber.ROUND_HALF_UP); return localizeNumber(fraction, 'en-US', 0, maxDecimals); }; export const countDecimalPlaces = (value: string | number) => { if (typeof value === 'string' && isNaN(Number(value))) { throw new Error('Value is not a valid number string'); } return value.toString().split('.')[1]?.length ?? 0; }; export const getBigNumberFromBalance = async (locator: Locator) => { await expect(locator).toHaveText(/\d/); let originalBalanceText = await locator.innerText(); const hasEllipsis = originalBalanceText.includes('…'); if (hasEllipsis) { originalBalanceText = originalBalanceText.slice(0, -1); } // Grouped past a thousand (`1,000.99`), which BigNumber reads as NaN. const originalBalance = BigNumber(originalBalanceText.replace(/,/g, '')); return { originalBalance, hasEllipsis }; }; /** * Mocks remote message-system with an empty JWS config signed by develop key. */ export const mockRemoteMessageSystem = async (page: Page): Promise => { await page.route('**/config.v1.jws', async route => { await route.fulfill({ status: 200, body: validJws }); }); }; export const normalizeWhitespace = (obj: any): any => { if (typeof obj === 'string') { // Normalize whitespace: \u00A0 is non-breaking space, \u0020 is regular space. return obj.replace(/[\u00A0\u0020]/g, ' '); } if (Array.isArray(obj)) { return obj.map(normalizeWhitespace); } if (obj && typeof obj === 'object') { const result: any = {}; for (const [key, value] of Object.entries(obj)) { result[key] = normalizeWhitespace(value); } return result; } return obj; }; export const analyzeObject = (obj: any): any => { const padding = 3; // Padding for character codes const analyzeText = (text: string) => { const chars = Array.from(text); const paddedChars = chars.map(char => char.padStart(padding, ' ')); const paddedCodes = chars.map(char => char.charCodeAt(0).toString().padStart(padding, ' ')); return { chars: paddedChars.join(' '), codes: paddedCodes.join(' '), }; }; if (typeof obj === 'string') { return analyzeText(obj); } if (Array.isArray(obj)) { return obj.map(analyzeObject); } if (obj && typeof obj === 'object') { const result: any = {}; for (const [key, value] of Object.entries(obj)) { result[key] = analyzeObject(value); } return result; } return obj; }; export const toADA = (lovelace: number, options?: { maxDecimals?: number }) => { const maxDecimals = options?.maxDecimals ?? 6; // A fee is rounded up, never truncated, so it is not understated. `localizeNumber` // truncates, so round first. const ada = BigNumber(lovelace) .div(1_000_000) .decimalPlaces(maxDecimals, BigNumber.ROUND_HALF_UP); return `${localizeNumber(ada, 'en-US', 0, maxDecimals)} ADA`; }; export const replaceTemplatesInTranslation = ( template: string, values: Record, ) => String(new IntlMessageFormat(template, 'en').format(values));